请帮助逃脱Java中String.split()方法中的NPE错误

时间:2018-09-12 09:54:36

标签: java

请帮助逃避Java中String.split()方法中的NullPointExeption错误。字符串来自用户输入。它无法编译。对于变量的硬编码,一切都很好。

类计算器:

public class Calculator {
    private String mathExpression;

    public void setMathExpression(String mathExpression) {
        this.mathExpression = mathExpression;
    }

    private String[] parts = mathExpression.split(" ");

    private String firstNumber1 = parts[0];
    //add other elements to the array...
    public void calculatorRun() {
        //using all the variables
    }
}

类CalculatorTest:

public class CalculatorTest {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String userAnswer = "y";
        Calculator calculator = new Calculator();

        while (userAnswer.equals("y")) {
            System.out.print("Please put the math expression: ");
            calculator.setMathExpression(scanner.nextLine());
            calculator.calculatorRun();
        }
    }
}

2 个答案:

答案 0 :(得分:1)

您需要将split调用放入方法中,否则将在实例化Calculator时立即执行。看到这个

private String[] parts = mathExpression.split(" ");
private String firstNumber1 = parts[0];

将两者都放入方法calculatorRun

答案 1 :(得分:0)

确保mathExpression不为空或为空

if(mathExpression!= null && !mathExpression.isEmpty()) { 


 private String[] parts = mathExpression.split(" ");

 private String firstNumber1 = parts[0];


    /* other code */ }