【发布时间】:2021-10-08 20:14:28
【问题描述】:
我编写的这段代码不断触发这个异常。 代码:
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
enum mathoperators{
MULTIPLY, DIVIDE, ADD, SUBTACT, EQUALS
}
public class binarydecimal {
static boolean state;
static List<mathoperators> mathpos = new ArrayList<mathoperators>();
@SuppressWarnings("null")
public static void main(String[] args) throws InterruptedException {
Random r = new Random();
int intman = r.nextInt(5);
String nani = null;
switch (intman + 1) {
case 1:
state = true;
mathpos.add(mathoperators.MULTIPLY);
System.out.println(intman * 2/420);
TimeUnit.SECONDS.sleep(2);
case 2:
state = false;
mathpos.add(mathoperators.DIVIDE);
System.out.println(intman/2 * 420);
TimeUnit.SECONDS.sleep(2);
case 3:
state=true;
mathpos.add(mathoperators.ADD);
System.out.println(intman + 2/420);
TimeUnit.SECONDS.sleep(2);
case 4:
if (intman < 2) {
intman+=2;
}
state=false;
System.out.println(intman - 2/420);
TimeUnit.SECONDS.sleep(2);
default:
state = (Boolean) null;
mathpos.clear();
}
}}
错误:
线程“main”中的异常 java.lang.NullPointerException:无法调用“java.lang.Boolean.booleanValue()”,因为“null”为 null
这段代码如何在不触发异常的情况下发挥相同的作用。
【问题讨论】:
-
boolean是Booleanint是Integer -
为什么在默认块中将 null 转换为布尔值?如果您的
state可以采用两个以上的值,请不要使用布尔值。