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();