请帮助逃避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();
}
}
}
答案 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 */ }