请帮助转义 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 }}类计算器测试: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 回答
冉冉说
TA贡献1877条经验 获得超1个赞
您需要将您的split调用放入一个方法中,否则它会在您实例化Calculator. 看到这个
private String[] parts = mathExpression.split(" ");
private String firstNumber1 = parts[0];
将两者都放入方法中 calculatorRun
潇湘沐
TA贡献1816条经验 获得超6个赞
确保 mathExpression 不为空或为空
if(mathExpression!= null && !mathExpression.isEmpty()) {
private String[] parts = mathExpression.split(" ");
private String firstNumber1 = parts[0];
/* other code */ }
添加回答
举报
0/150
提交
取消