I am a newbie coder in Java and I am trying to make this calculator in java where a user can enter two numbers and select the operation to be done on those numbers. However when the code comes to selecting the operator it skips the user input and the if statement and directly implements the else statement.
import java.util.Scanner; public class Calculator { public static void main(String[] args) { Scanner Calc = new Scanner(System.in); int n1; int n2; int Answer; System.out.println("Enter the first number: "); n1 = Calc.nextInt(); System.out.println("Enter the second number:" ); n2 = Calc.nextInt(); System.out.println("Select the order of operation: "); char operator = Calc.nextLine().charAt(0); if (operator == '+') { Answer = (n1 + n2); System.out.println("Answer:" + Answer); } if (operator == '-') { Answer = (n1 - n2); System.out.println("Answer:" + Answer); } if (operator == '*') { Answer = (n1 * n2); System.out.println("Answer:" + Answer); } if (operator == '/') { Answer = (n1/n2); System.out.println("Answer:" + Answer); } else { System.out.println("not implemented yet. Sorry!"); } } }
Advertisement
Answer
Add Calc.nextLine();
after n2 = Calc.nextInt();
to consume the line feed.
You are also not using else if
so all those if
conditions will be checked even if previous if
already matched (resulting in your final else being executed as long as operator not '/'
).
In this case you should probably just use a switch
block.