The code will compile, but there seems to be an error with my menu. The user will select one of the choices and the program should execute, but When choosing a selection nothing happens. Here is the code:
import java.util.Scanner;
class Tutorial{
public static void main(String args[]){
Geek myGeek = new Geek("Geek");
System.out.println("Command Options: ");
System.out.println("a: Geek's Name");
System.out.println("b: Num Questions Asked");
System.out.println("c: All Numbers Are the Same");
System.out.println("d: Sum Between Two Integers");
System.out.println("e: Repeat the String");
System.out.println("f: It is Palindrome");
System.out.println("?: Display");
System.out.println("q: Quit");
Scanner scan = new Scanner(System.in);
String choice = scan.nextLine();
do {
switch (choice){
case "a":
myGeek.getName();
break;
case "b":
myGeek.getnumberofQuestions();
break;
case "c":
System.out.println("Enter the first number");
int input1 = scan.nextInt();
System.out.println("Enter the second number");
int input2 = scan.nextInt();
System.out.println("Enter the third number");
int input3 = scan.nextInt();
myGeek.allTheSame(input1, input2, input3);
break;
case "d":
System.out.println("Enter the first number");
int num1 = scan.nextInt();
System.out.println("Enter the second number");
int num2 = scan.nextInt();
myGeek.sum(num1, num2);
break;
case "e":
System.out.println("Enter a string: ");
String word1 = scan.nextLine();
System.out.println("Enter an integer: ");
int numberOfTimes = scan.nextInt();
System.out.println("Enter the third number");
myGeek.repeat(word1, numberOfTimes);
break;
case "f":
System.out.println("Enter a string: ");
String word2 = scan.nextLine();
myGeek.isPalindrome(word2);
break;
case "?":
System.out.println("Command Options: ");
System.out.println("a: Geek's Name");
System.out.println("b: Num Questions Asked");
System.out.println("c: All Numbers Are the Same");
System.out.println("d: Sum Between Two Integers");
System.out.println("e: Repeat the String");
System.out.println("f: It is Palindrome");
System.out.println("?: Display");
System.out.println("q: Quit");
break;
} }while (choice != "q");
}
}
Here is the what it looks like when run:
http://i.imgur.com/O6SgyH1.png
Well, you definitely need to move code which gets input inside the loop :
String choice = null;
Scanner scan = new Scanner(System.in);
do {
choice = scan.nextLine();
switch (choice) {
case "a":
.........
} // end of switch
} while (!choice.equals("q")); // end of loop
Otherwise, you input once and switch on that input indefinitely (unless it is "q")
Edit :
You also need to change terminating condition to while (!choice.equals("q"));
for it to work.
This also depends on which version of the JDK they're using.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
http://java.dzone.com/articles/new-java-7-feature-string
Few things:
You read input only once - outside of do..while - probably not what you want (otherwise you'd be stuck in infinite loop).
most likely the intent was this: while ((choice = scan.nextLine()) != "q");
As far as why you don't see anything when running, it depends on what myGeek.getName() does.
As name suggests its a simple getter, if this is a case then it returns the name but it does not print anything on the screen.
i think you want something like this:
....
System.out.println("d: Sum Between Two Integers");
System.out.println("e: Repeat the String");
System.out.println("f: It is Palindrome");
System.out.println("?: Display");
System.out.println("q: Quit");
String choice;
do {
System.out.println("Select something: ");
Scanner scan = new Scanner(System.in);
choice = scan.nextLine();
switch (choice){
case "a":
myGeek.getName();
break;
case "b":
myGeek.getnumberofQuestions();
break;
case "c":
System.out.println("Enter the first number");
int input1 = scan.nextInt();
System.out.println("Enter the second number");
....
if not --->>>> for what you need do -> while??
and check, if your java is 7 or heighter, and check your getMethods() -> if thay return anything
One issue you have, as mentioned by #rgettman, is that comparing Strings in Java using == or != will compare the Object reference of the String not the value; basically are the two Strings the same Object? In this case (and most cases) you want to compare the value.
Change while (choice != "q"); to while (!choice.equals("q")); to compare the values.
A slightly different explanation:
Right now you are entering a character, say "a", matching your case for "a" and breaking from the switch/case. However when your program gets to the while it basically checks whether choice is "q" so your program goes back into the do/while loop.
Your loop (do {} while(condition)) will loop infinite when you enter some string different "q" because condition always is true.
try with :
while (!choice.equals("q")) {
switch (choice) {
case "a":
myGeek.getName();
break;
case "b":
myGeek.getnumberofQuestions();
break;
case "c":
System.out.println("Enter the first number");
int input1 = scan.nextInt();
System.out.println("Enter the second number");
int input2 = scan.nextInt();
System.out.println("Enter the third number");
int input3 = scan.nextInt();
myGeek.allTheSame(input1, input2, input3);
break;
case "d":
System.out.println("Enter the first number");
int num1 = scan.nextInt();
System.out.println("Enter the second number");
int num2 = scan.nextInt();
myGeek.sum(num1, num2);
break;
case "e":
System.out.println("Enter a string: ");
String word1 = scan.nextLine();
System.out.println("Enter an integer: ");
int numberOfTimes = scan.nextInt();
System.out.println("Enter the third number");
myGeek.repeat(word1, numberOfTimes);
break;
case "f":
System.out.println("Enter a string: ");
String word2 = scan.nextLine();
myGeek.isPalindrome(word2);
break;
case "?":
System.out.println("Command Options: ");
System.out.println("a: Geek's Name");
System.out.println("b: Num Questions Asked");
System.out.println("c: All Numbers Are the Same");
System.out.println("d: Sum Between Two Integers");
System.out.println("e: Repeat the String");
System.out.println("f: It is Palindrome");
System.out.println("?: Display");
System.out.println("q: Quit");
break;
}
}
Related
Somehow I got operator looping till I get correct input. When i try to put num1 or num2 in "if" statement, It says that I cannot convert "int" to "boolean". Please help
public class main {
public static void main(String[] args) {
int num1;
int num2;
String operator;
Scanner scan = new Scanner(System.in);
System.out.print("tell me first number: ");
num1 = scan.nextInt(); //<--input only numbers, loop if not
System.out.print("tell me second number: ");
num2 = scan.nextInt(); //<--input only numbers, loop if not
//////////////////operator////////////////////////
System.out.print("tell me operator: ");
operator = scan.next();
while(true) {
if(operator.equals("+")) {
System.out.println("answer is: " +(num1 + num2));
break;
}
else if(operator.equals("-")) {
System.out.println("answer is: " +(num1 - num2));
break;
}
else if(operator.equals("*")) {
System.out.println("answer is: " +(num1 * num2));
break;
}
else if(operator.equals("/")) {
System.out.println("answer is: " +(num1 / num2));
break;
}
else {
System.out.print("wrong input! try again!: ");
operator = scan.next();
}
}
}
}
Try this.
System.out.print("tell me first number: ");
while (!scan.hasNextInt()) scan.next();
num1 = scan.nextInt();
System.out.print("tell me second number: ");
while (!scan.hasNextInt()) scan.next();
num2 = scan.nextInt();
System.out.print("tell me first number: ");
while (!scan.hasNextInt()) scan.next();
num1 = scan.nextInt();
System.out.print("tell me second number: ");
while (!scan.hasNextInt()) scan.next();
num2 = scan.nextInt();
With this, wrong answer was looping till i got correct input, but I could not get it to print me "Wrong Input! Try again!: " with wrong input without starting to loop infinitely, so i tried to edit and came up with this.
//////////////////first number////////////////////
System.out.print("tell me first number: ");
while(!scan.hasNextInt()) {
System.out.print("Wrong Input! Try again!: "); scan.next();
if(scan.hasNextInt() == true) {
}
}
num1 = scan.nextInt();
//////////////////second number///////////////////
System.out.print("tell me second number: ");
while(!scan.hasNextInt()) {
System.out.print("Wrong input! Try again!: "); scan.next();
if(scan.hasNextInt() == true) {
}
}
num2 = scan.nextInt();
Somehow it helped lol.
Thanks #英語は苦手 for help.
The goal is if the user puts an invalid option in three times, the program will tell the user to try again later and end the program. The code I have is below, I hope this makes sense, I am sorry if it doesn't. If you have any questions please let me know. I've also never asked a question here before so it may not be uploaded correctly.
public static void main(String[] args) {
int num1 = 0, num2 = 0, total = 0, option = 0, ex; // Creates integer variables
do {
Scanner sc = new Scanner(System.in);
System.out.println("\tBasic Math Calculator");// Title
System.out.println("\t---------------------");
System.out.println("\tEnter your choice from the following menu:");
System.out.println("\t------------------------------------------");
System.out.println("1.\tAddition");// All the menu options
System.out.println("2.\tSubtraction");
System.out.println("3.\tMultiplication");
System.out.println("4.\tDivision");
System.out.println("5.\tGenerate Random number");
System.out.println("6.\tQuit");
boolean valid;
do {
valid = true;
try {
option = Integer.parseInt(sc.nextLine());// Stores the users answers
if (option < 1 || option > 6) {
System.out.println("Invalid input. Please try again.");
valid = false;
}
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please try again.");
valid = false;
}
} while (!valid);
switch (option) {// The math and titles for every option
case 1:
System.out.println("You chose to add two numbers: ");
System.out.println("Enter your first number:");
num1 = sc.nextInt();
System.out.println("Enter your second number:");
num2 = sc.nextInt();
total = num1 + num2;
System.out.println("The two numbers you chose added together is " + total);
break;
case 2:
System.out.println("You chose to subtract two numbers: ");
System.out.println("Enter your first number:");
num1 = sc.nextInt();
System.out.println("Enter your second number:");
num2 = sc.nextInt();
total = num1 - num2;
System.out.println("The two numbers you chose subtracted together is " + total);
break;
case 3:
System.out.println("You chose to multiply two numbers: ");
System.out.println("Enter your first number:");
num1 = sc.nextInt();
System.out.println("Enter your second number:");
num2 = sc.nextInt();
total = num1 * num2;
System.out.println("The two numbers you chose multiplied together is " + total);
break;
case 4:
System.out.println("You chose to divide two numbers: ");
System.out.println("Enter your first number:");
num1 = sc.nextInt();
System.out.println("Enter your second number:");
num2 = sc.nextInt();
total = num1 / num2;
if (num2 == 0) {
System.out.println("You can't divide by 0");
} else {
System.out.println("The two numbers you chose divided together is " + total + "with a quotient of "
+ (num1 % num2));
}
break;
case 5:
System.out.println("You chose to get two random numbers: ");
System.out.println("Enter your lower limit:");
num1 = sc.nextInt();
System.out.println("Enter your upper limit:");
num2 = sc.nextInt();
total = num1 + num2;
Random rand = new Random();
int rand_int1 = rand.nextInt(num1 + num2);
System.out.println("The random intigers is: " + rand_int1);
break;
case 6:// If the user wants to quit
ex = 2;
break;
default:// Tells their option was incorrect
System.out.println("Invalid choice, choice " + option + " was not an option");
}
System.out.println("Do you want to continue?1.Yes 2.No");// Asks the user if they want to proceed
ex = sc.nextInt(); // A thank you message for the user for running the program
} while (ex == 1);
System.out.println("-----------------------------------------");
System.out.println("Thank you for using the basic calculator!");
}
You can do so by creating a nested loop before the start if switch statement:
//...
System.out.println("6.\tQuit");
boolean valid;
do {
valid = true;
try {
option = Integer.parseInt(sc.nextLine());// Stores the users answers
if (option < 1 || option > 6) {
System.out.println("Invalid input. Please try again.");
valid = false;
}
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please try again.");
valid = false;
}
} while (!valid);
switch (option) {// The math and titles for every option
//...
A sample run after this change:
Basic Math Calculator
---------------------
Enter your choice from the following menu:
------------------------------------------
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Generate Random number
6. Quit
a
Invalid input. Please try again.
9
Invalid input. Please try again.
4
You chose to divide two numbers:
Enter your first number:
Check the full code at ideone.
You don't have to use the valid and do-while for checking times of invalid input
If you want to quit the program after 3 invalid option entered by user , you have to increment the count of ex and change the condition at while loop.
Initialize ex=1
Change case 6 and default as below
case 6:// If the user wants to quit
System.exit(0);
break;
default:
ex = ex+1;
break;
and
while condition as below
while (ex <4); //
Following is the full code
public static void main(String[] args) {
int num1 = 0, num2 = 0, total = 0, ex= 1; // Creates integer variables
do {
Scanner sc = new Scanner(System.in);
System.out.println("\tBasic Math Calculator");// Title
System.out.println("\t---------------------");
System.out.println("\tEnter your choice from the following menu:");
System.out.println("\t------------------------------------------");
System.out.println("1.\tAddition");// All the menu options
System.out.println("2.\tSubtraction");
System.out.println("3.\tMultiplication");
System.out.println("4.\tDivision");
System.out.println("5.\tGenerate Random number");
System.out.println("6.\tQuit");
switch (option) {// The math and titles for every option
case 1:
System.out.println("You chose to add two numbers: ");
System.out.println("Enter your first number:");
num1 = sc.nextInt();
System.out.println("Enter your second number:");
num2 = sc.nextInt();
total = num1 + num2;
System.out.println("The two numbers you chose added together is " + total);
break;
case 2:
System.out.println("You chose to subtract two numbers: ");
System.out.println("Enter your first number:");
num1 = sc.nextInt();
System.out.println("Enter your second number:");
num2 = sc.nextInt();
total = num1 - num2;
System.out.println("The two numbers you chose subtracted together is " + total);
break;
case 3:
System.out.println("You chose to multiply two numbers: ");
System.out.println("Enter your first number:");
num1 = sc.nextInt();
System.out.println("Enter your second number:");
num2 = sc.nextInt();
total = num1 * num2;
System.out.println("The two numbers you chose multiplied together is " + total);
break;
case 4:
System.out.println("You chose to divide two numbers: ");
System.out.println("Enter your first number:");
num1 = sc.nextInt();
System.out.println("Enter your second number:");
num2 = sc.nextInt();
total = num1 / num2;
if (num2 == 0) {
System.out.println("You can't divide by 0");
} else {
System.out.println("The two numbers you chose divided together is " + total + "with a quotient of "
+ (num1 % num2));
}
break;
case 5:
System.out.println("You chose to get two random numbers: ");
System.out.println("Enter your lower limit:");
num1 = sc.nextInt();
System.out.println("Enter your upper limit:");
num2 = sc.nextInt();
total = num1 + num2;
Random rand = new Random();
int rand_int1 = rand.nextInt(num1 + num2);
System.out.println("The random intigers is: " + rand_int1);
break;
case 6:// If the user wants to quit
System.out.println("Thank you for using the basic calculator!");
System.exit(0);
break;
default:// Tells their option was incorrect
ex=ex+1;
System.out.println("Invalid choice, choice " + option + " was not an option");
}
System.out.println("Do you want to continue?1.Yes 2.No");// Asks the user if they want to proceed
//ex = sc.nextInt(); // A thank you message for the user for running the program
} while (ex<4);
System.out.println("-----------------------------------------");
System.out.println("Thank you for using the basic calculator!");
}
Edited
Below is the sample output
Basic Math Calculator
---------------------
Enter your choice from the following menu:
------------------------------------------
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Generate Random number
6. Quit
7
Invalid choice, choice 7 was not an option
Please try again
Basic Math Calculator
---------------------
Enter your choice from the following menu:
------------------------------------------
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Generate Random number
6. Quit
7
Invalid choice, choice 7 was not an option
Please try again
Basic Math Calculator
---------------------
Enter your choice from the following menu:
------------------------------------------
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Generate Random number
6. Quit
7
Invalid choice, choice 7 was not an option
Please try again
-----------------------------------------
Thank you for using the basic calculator!
Desired output: Hello, I am trying to make a program that does addition, subtraction, multiplication, and division and loops until you press 'e' to exit the loop.
So, I want it to look something like this:
A. Addition
B. Subtraction
C. Multiplication
D. Division
E. Exit
Please enter your selection, enter E to end:
//let's say they enter a, and want to add 5 plus 5
Enter your first number:
Enter your second number:
5 + 5 = 10.0
Please enter your selection, enter E to end:
//This looping part is what I want to happen! But my program just ends, and I'm not
sure how to fix it
Issue: My problem is that once you enter what operation you want, it only does the arithmetic once and then it displays my exit message and ends, but that is only supposed to happen when the user enters 'e' but the rest works, I think!
Here is my code
import java.util.Scanner;
public class Calculator_Loop {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
char selection;
char choice = 'E';
double num_1;
double num_2;
double result;
System.out.println("A. Addition\nB. Subtraction\nC. Multiplication\nD. Division \n\nE. Exit");
//System.out.println("\nPlease enter your selection, enter E to end:");
//selection = input.next().charAt(0);
//choice = Character.toUpperCase(selection);
while(choice != 'E')
System.out.println("\nPlease enter your selection, enter E to end:");
selection = input.next().charAt(0);
choice = Character.toUpperCase(selection);
if(choice == 'A') {
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 + num_2;
System.out.println(result);
}
if(choice == 'B'){
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 - num_2;
System.out.println(result);
}
if(choice == 'C'){
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 * num_2;
System.out.println(result);
}
if(choice == 'D'){
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 / num_2;
System.out.println(result);
}
System.out.println("Thank you, have a nice day!");
}
}
Am I doing something wrong with the brackets? Or is there something I'm missing for the loop to work? Any help is appreciated, thanks!
Welcome to SO.
Problem is (as far as I can see) that you have nothing/only the print line in your while loop.
while(true) {
do things
}
Java allows while loops without brackets, but at maximum one line (and I recommend doing them for one line too, but that is debattable), as soon as you need several lines, you need brackets and should have according indentation.
You need to surround your intended while loop with brackets to make it work the way you want:
while (choice != 'E') {
System.out.println("\nPlease enter your selection, enter E to end:");
selection = input.next().charAt(0);
choice = Character.toUpperCase(selection);
switch (choice) {
case 'A':
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 + num_2;
System.out.println(result);
break;
case 'B':
// ...
}
}
System.out.println("Thank you, have a nice day!");
Currently, your while loop will spin forever (I think), because the seed value for choice is being set to E.
Side note: Consider using a switch statement to handle the various case values for the choice.
Instead of using the if conditions, please use the while loop and switch condition. if the input value is other than the A, B, C or D then exit from the code.
Code takes only the first character of your input and enters into switch case, where it will compare the input with the required conditions.
public class Calculator_Loop {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String choice = "";
double num_1;
double num_2;
double result;
System.out.println("A. Addition\nB. Subtraction\nC. Multiplication\nD. Division \n\nE. Exit");
/*System.out.println("\nPlease enter your selection, enter E to end:");
selection = input.next().charAt(0);
choice = input.next().substring(0, 1).toUpperCase();*/
outer: while (true) {
System.out.println("\nPlease enter your selection, enter E to end:");
choice = input.next();
choice = choice.substring(0, 1).toUpperCase();
switch (choice) {
case "A":
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 + num_2;
System.out.println(result);
break;
case "B":
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 - num_2;
System.out.println(result);
break;
case "C":
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 * num_2;
System.out.println(result);
break;
case "D":
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 / num_2;
System.out.println(result);
break;
default:
System.out.println("Thank you, have a nice day!");
break outer;
}
}
}
}
You class has two problems.
One is the missing brace that others metioned.
The other is that it will never enter the loop as the condition is allways false.
So to make sure that the loop is entered at least once you need an endcondition. a do-while construct instead of your startcondition.
So I changed your while loop into a do-while. By that I added the missing curly.
I also changed your if's to a switch as a choice calls for it.
And I moved the question into the loop, so the user gets the information in every iteration.
import java.util.Scanner;
public class Calculator_Loop {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
char selection;
char choice = 'E';
double num_1;
double num_2;
double result;
do {
System.out.println("A. Addition\nB. Subtraction\nC. Multiplication\nD. Division \n\nE. Exit");
//System.out.println("\nPlease enter your selection, enter E to end:");
//selection = input.next().charAt(0);
//choice = Character.toUpperCase(selection);
System.out.println("\nPlease enter your selection, enter E to end:");
selection = input.next().charAt(0);
choice = Character.toUpperCase(selection);
switch (choice) {
case 'A':
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 + num_2;
System.out.println(result);
break;
case 'B':
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 - num_2;
System.out.println(result);
break;
case 'C':
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 * num_2;
System.out.println(result);
break;
case 'D':
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 / num_2;
System.out.println(result);
break;
}
} while (choice != 'E');
System.out.println("Thank you, have a nice day!");
}
}
I'm trying to code simple calculator (all in one) using Switch cases in java. I came up with following code so far. However I'm stuck with while loop. I want to keep showing main menu after each case execution until user decides to exit the program.
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("Main Menu:");
System.out.println("1. Addition");
System.out.println("2. Substraction");
System.out.println("3. Multipication");
System.out.println("4. Division");
System.out.println("Enter your choice: ");
int i=s.nextInt();
System.out.println("ENTER FIRST NUMBER ");
int a=s.nextInt();
System.out.println("ENTER SECOND NUMBER ");
int b=s.nextInt();
int result=0;
switch(i)
{
case 1:
result=a+b;
break;
case 2:
result=a-b;
break;
case 3:
result=a*b;
break;
case 4:
result=a/b;
break;
default:
System.out.println("Wrong Choice.");
}
System.out.println("Answer is "+result);
}
}
Above code works fine. Program ends itself after execution of user selected choice. I want to put main menu on a repeat.
Add a while loop like this:
public static void main(String[] args) {
// Moved this outside the while loop as davidxxx pointed out +1
Scanner s = new Scanner(System.in);
while (true) {
System.out.println("Main Menu:");
System.out.println("1. Addition");
System.out.println("2. Substraction");
System.out.println("3. Multipication");
System.out.println("4. Division");
System.out.println("Enter your choice: ");
int i = s.nextInt();
System.out.println("ENTER FIRST NUMBER ");
int a = s.nextInt();
System.out.println("ENTER SECOND NUMBER ");
int b = s.nextInt();
int result = 0;//'result' will store the result of operation
switch (i) {
case 1:
result = a + b;
break;
case 2:
result = a - b;
break;
case 3:
result = a * b;
break;
case 4:
result = a / b;
break;
default:
System.out.println("Wrong Choice.");
}
System.out.println("Answer is " + result);
System.out.println("Go again?");
String goAgain = s.next();
if (!goAgain.equals("y")) {
break;
}
}
}
Try this:
import java.util.Scanner;
public class Calculator {
private static final String EXIT = "EXIT";
public static void main(String[] args) {
Calculator calc = new Calculator();
Scanner s = new Scanner(System.in);
while (true) {
String res = calc.runCalc(s);
if (res.equals(EXIT)) {
break;
} else {
System.out.println(res);
}
}
}
private String runCalc(Scanner s) {
System.out.println("Main Menu:");
System.out.println("1. Addition");
System.out.println("2. Substraction");
System.out.println("3. Multipication");
System.out.println("4. Division");
System.out.println("5. Exit");
System.out.println("Enter your choice: ");
int i = s.nextInt();
if (i == 5) {
return EXIT;
}
System.out.println("ENTER FIRST NUMBER ");
int a = s.nextInt();
System.out.println("ENTER SECOND NUMBER ");
int b = s.nextInt();
int result = 0;// 'result' will store the result of operation
switch (i) {
case 1:
result = a + b;
break;
case 2:
result = a - b;
break;
case 3:
result = a * b;
break;
case 4:
result = a / b;
break;
default:
return "Wrong Choice.";
}
return "Answer is " + result;
}
}
There is more than one way to achieve this, you can use
while loop.
do-while loop.
for loop.
I think do-while loop is better for your situation. Because either user wants to continue or not you have to proceed one time(before loop false). And you do not want to use another variable for quit the loop.
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
int result=0;
do{
System.out.println("Main Menu:");
System.out.println("-1. complete and calculate");
System.out.println("1. Addition");
System.out.println("2. Substraction");
System.out.println("3. Multipication");
System.out.println("4. Division");
System.out.println("Enter your choice: ");
int i=s.nextInt();
if(i ==-1){
System.out.println("Answer is "+result);
return;
}
System.out.println("ENTER FIRST NUMBER ");
int a=s.nextInt();
System.out.println("ENTER SECOND NUMBER ");
int b=s.nextInt();
switch(i)
{
case 1:
result=a+b;
break;
case 2:
result=a-b;
break;
case 3:
result=a*b;
break;
case 4:
result=a/b;
break;
default:
System.out.println("Wrong Choice.");
break;
}
}while(true);
}
I have a switch menu and I want it to loop the entire menu including the directions but it just keeps looping the operation i select. How do I change it? I switched from a do/while to just a while loop.
int count = 0;
String first;
String last;
String num;
Contact person;
System.out.println("What would you like to do?");
System.out.println("Type c to create");
System.out.println("Tpe e to edit");
System.out.println("Tpe d to delete");
System.out.println("Type q to quit");
Scanner input = new Scanner(System.in);
char choice = input.next().charAt(0);
AddressBook addressBook = new AddressBook();
while ('q' != choice) {
switch (choice) {
case 'c':
System.out.println("Enter first name, last name and phone number");
addressBook.addContact();
count++;
System.out.println("Total number of contact: " + count);
break;
case 'e':
System.out.println("Enter name to be edited");
first = input.next();
last = input.next();
num = null;
person = new Contact(first, last, num);
addressBook.edit(person);
break;
case 'd':
System.out.println("Enter name to be deleted");
first = input.next();
last = input.next();
num = null;
person = new Contact(first, last, num);
addressBook.removeContact(person);
break;
default:
System.out.println("Operation does not exist");
}
}
}
}
Initialize char choice to a default char:
char choice = 'a';
Then move all of this:
System.out.println("What would you like to do?");
System.out.println("Type c to create");
System.out.println("Tpe e to edit");
System.out.println("Tpe d to delete");
System.out.println("Type q to quit");
choice = input.next().charAt(0);
Inside your while loop:
while ('q' != choice) {
//show menu options
//allow user to select a menu option
//use switch to operate based on user decision
//once the operation is complete, as long as the user didn't select q,
//the menu options show once more and allow another selection
}
No need to use choice.
1.Change while ('q' != choice) to while (true)
2.Move below code inside while
System.out.println("What would you like to do?");
System.out.println("Type c to create");
System.out.println("Tpe e to edit");
System.out.println("Tpe d to delete");
System.out.println("Type q to quit");
3. Add one extra case
case 'q':
break;