0

I'm creating a Calculator Object based on our topic OOP now I created the Class but it somehow skipped the scanner in userInputOp() method on the second call from the loop.

    Calculator() {
        System.out.println("Calculator Created");
        while(!ifExit){
            showInstructions();
            userInputOp();
            ifExit();
            if(this.ifExit) {
                break;
            }
            userInputNum();
            compute(this.n1,this.n2);
            printResults();
            this.op = null;
        }
    }
    private void userInputOp() {
        System.out.println("userInputOp");
        System.out.print("Enter operator symbol: ");
        this.op = sc.nextLine();
    }
    private void ifExit() {
        System.out.println("ifExit");
        if(this.op.equals("0"))
            this.ifExit = true;
    }
}

Output

**Below is the 2nd output of the loop**
====================================
      | BASIC CALCULATOR |      
      ADDITION -       ( + )
      SUBTRACTION -    ( - )
      MULTIPLICATION - ( x )
      DIVISION -       ( / )
      MODULO -         ( % )
      EXIT -           ( 0 )
====================================
userInputOp
Enter operator symbol: ifExit
Enter first number: 

I expected it to not skip the scanner in userInputOp() method.

Solution Related Problem Link TL:DR Adding nextLine() on every nextInt/Double fixed the issue.

 System.out.print("Enter first number: ");
    this.n1 = sc.nextDouble();
    sc.nextLine();
    System.out.print("Enter second number: ");
    this.n2 = sc.nextDouble();
    sc.nextLine();
  • 1
    What does the method `userInputNum()` do? Do you use the scanner in that method too? I suspect you call something like `nextInt()` in that method which will lead to: [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo) – OH GOD SPIDERS Dec 07 '22 at 12:07
  • it prints and scans the 'Enter first number: ' and I checked it's nextDouble() – Monstercat456 Dec 07 '22 at 12:14
  • Then it is as I suspected and the question I linked has the answer on why that happens: `nextDouble()` doesn't read in the carriage return / line feed so the next time you call `nextLine()`after that it will only read in that carriage return / line feed. See the question I linked for possible solutions and workarounds to that problem – OH GOD SPIDERS Dec 07 '22 at 12:22
  • The problem is fixed, thank you for your help and linking the solution. Adding nextLine() on every nextDouble() managed to fix the skipping. – Monstercat456 Dec 07 '22 at 12:31

0 Answers0