Hi. Im doing a few exercises because I have a test tomorrow (Wish me luck!). This particular exercise asks for a menu calculator. The Menu is like:
- Addition
- Subtraction
- Multiplication
- Division
- Exit
Im using do..while and the switch case is in the do..while. and im having trouble with the choice number 5. Since im using do while the menu will appear again after the result is calculated until the user picks choice 5 but if i choose 5, program does not exit but insted continues on. This is my code:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
//initialize scanner
Scanner sc = new Scanner(System.in);
//initialize to get user input
int choice, firstNum, secondNum, result = 0;
//reiterate menu after result if choice 5 not chosen
do{
//print out menu
System.out.println("Operations:\n");
System.out.println("1. Addition");
System.out.println("2. Subtraction");
System.out.println("3. Multiplication");
System.out.println("4. Division");
System.out.println("5. Exit\n");
System.out.println("Enter your choice : ");
choice = sc.nextInt();
System.out.println("Enter first operand : ");
firstNum = sc.nextInt();
System.out.println("Enter second opernad : ");
secondNum = sc.nextInt();
switch(choice){
case 1 : result = firstNum + secondNum;
break;
case 2 :result = firstNum - secondNum;
break;
case 3 :result = firstNum * secondNum;
break;
case 4 :result = firstNum / secondNum;
break;
case 5 : System.exit(0);
default : System.out.println("Please choose between 1 - 5 only.");
}
System.out.println("Result : " + result);
}while(choice!= 5);
}
}
Thanks in advance.