-1

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();
        }
    }
}
npkllr
  • 556
  • 1
  • 5
  • 20
Garibaldi
  • 41
  • 6

2 Answers2

1

You need to put your split call into a method otherwise it will be executed as soon as you instantiate the Calculator. See this

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

put both into the method calculatorRun

Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107
0

Make sure that mathExpression not empty or null

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


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

 private String firstNumber1 = parts[0];


    /* other code */ }
sasikumar
  • 12,540
  • 3
  • 28
  • 48