gpt4 book ai didi

java - 我如何检查空指针异常

转载 作者:行者123 更新时间:2023-11-29 09:55:51 26 4
gpt4 key购买 nike

这是代码

private static HashMap naturalNumbers = new HashMap();

static
{
naturalNumbers.put("zero", new Integer( 0 ) );
naturalNumbers.put("one", new Integer( 1 ) );
naturalNumbers.put("two", new Integer( 2 ) );
naturalNumbers.put("three", new Integer( 3 ) );
}

private static int findANumber( String partOfaNumber ) throws Exception
{
int multiplicand = 0;
multiplicand += (Integer)naturalNumbers.get( partOfaNumber );

如果“get”返回 null,我该如何检查?

我试过:

if ( (Integer)naturalNumbers == null )
{
throw new Exception( "Number not found" );
}
return multiplicand;
}

但 IDE 甚至不接受它:无法从 HashMap 转换为 Integer。

最佳答案

这是一个略有不同的版本:

private static final HashMap<String, Integer> NUMS = new HashMap<String, Integer>();

static
{
NUMS.put("zero", 0);
NUMS.put("one", 1);
NUMS.put("two", 2);
NUMS.put("three", 3);
}

private static int findANumber(final String partOfaNumber) throws IllegalArgumentException
{
int multiplicand = 0;
final Integer theNum = NUM.get(partOfaNumber);
if (theNum != null) {
multiplicand += theNum;
} else {
throw new IllegalArgumentException("Number not found (" + partOfNumber + ")");
}

return multiplicand;
}

关于java - 我如何检查空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11981365/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com