【问题标题】:i keep getting this exception error Null pointer exception how do i stop this error and get a working error [duplicate]我不断收到这个异常错误空指针异常我如何停止这个错误并得到一个工作错误[重复]
【发布时间】: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

这段代码如何在不触发异常的情况下发挥相同的作用。

【问题讨论】:

  • booleanBoolean intInteger
  • 为什么在默认块中将 null 转换为布尔值?如果您的 state 可以采用两个以上的值,请不要使用布尔值。

标签: java exception boolean


【解决方案1】:

只需改变原语

static boolean state; 

static Boolean state; 

基元不能为空。

顺便说一句,您可能希望在每个案例块的末尾添加一个break;

【讨论】:

  • 非常感谢,不知道原语不能设置为空。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-05
  • 2018-10-01
  • 1970-01-01
  • 2017-08-23
相关资源
最近更新 更多