1

I am working on a very simple reverse polish notation calculator using stacks, and having trouble with an if/else statement inside a while loop. The rest of the code is working correctly, but I keep getting a NumberFormatException after the else line. I think this means it is not doing what it says to do in the if statement when the input is "*", but I am not sure how to fix this. Why would it go to else if the input is equal to one of the specified characters? I am not interested in making code more efficient, I would like to keep the format I have if possible, but I am very confused. Thank you so much for your help.

  try {            
        Scanner stackScanner = new Scanner(stackFile);
        while (stackScanner.hasNextLine()) {
            String pls = "+";
            String min = "-";
            String mul = "*";
            String div = "/";
            String mod = "%";
            String exp = "^"; 
            //stackScanner.nextLine();
            if(stackScanner.nextLine().equals(pls) ||
                stackScanner.nextLine().equals(min) ||
                stackScanner.nextLine().equals(mul) ||
                stackScanner.nextLine().equals(div) ||
                stackScanner.nextLine().equals(mod) ||
                stackScanner.nextLine().equals(exp)) {
                stack.push(new operationNode(stackScanner.nextLine()));
            }
            else {
                stack.push(new 
                 numberNode(Double.parseDouble(stackScanner.nextLine())));  
            }

        }

        stackScanner.close();    
Sashaeb
  • 21
  • 3
  • Possible duplicate of [What is a NumberFormatException and how can I fix it?](https://stackoverflow.com/questions/39849984/what-is-a-numberformatexception-and-how-can-i-fix-it) – xenteros Sep 29 '17 at 07:43

1 Answers1

0

The nextLine() method of Scanner reads the next line. If you call it more than once, it will read more than one line. So this statement:

        if(stackScanner.nextLine().equals(pls) ||
            stackScanner.nextLine().equals(min) ||
            stackScanner.nextLine().equals(mul) ||
            stackScanner.nextLine().equals(div) ||
            stackScanner.nextLine().equals(mod) ||
            stackScanner.nextLine().equals(exp)) { 
            stack.push(new operationNode(stackScanner.nextLine()));
        }

Here's what it does:

  1. Reads a line, and tests if it's equal to "+". If it's not:
  2. Reads another line, and tests if that second line is equal to "-". It doesn't test the same line that it tested against "+"--it tests the next line. If it's not "-":
  3. Reads another line ... you get the picture.

Solution: Read the line once and save the result in a variable. (I don't know whether this will solve the entire problem. But you definitely need to fix this.)

ajb
  • 31,309
  • 3
  • 58
  • 84