有没有办法让if(null)做某事

时间:2014-02-21 03:48:47

标签: java if-statement hashmap

我有状态和大写的哈希映射

目前,用户输入状态,并为其提供相应的资金

然后他们会在他们想要退出程序时输入完成

有没有办法制作一个if语句,如果没有所述状态,它将采用hashmap将发送的null?

如果我要求加拿大,它将返回null,因为没有名为Canada的州。

有没有办法使用它在for循环中发回的null,所以我可以做类似

的操作
if(null)
{
   say that that isn't a capital
}
else
{
   say the capital of what was inserted
}

1 个答案:

答案 0 :(得分:1)

是的,只需按照您的要求行事:

String capital = stateMap.get(testValue);
if (capital == null) {
   // error message
   System.err.printf("%s is not a valid state, please try again%n", testValue);
} else {
   // output a valid result
   System.out.printf("The capital of %s is %s%n", testValue, capital);
}
相关问题