Please help to escape NullPointExeption error in the String.split() method in Java. String got from the user entering. It can't compile. In the case of hard code of the variable all is fine.
Class Calculator:
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
}
}
Class 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();
}
}
}