I am working on project for class, where we were tasked to design a calculator program with a menu containing 5 options. I am facing an issue when I am trying to code to catch if the user inputs a choice that is not between 1 and 5. Currently if the user inputs a number between 6 to 9. The exception will be caught the first time and an error message which says to enter a choice between 1 and 5 will be displayed and a message to re enter will appear. However if the user continues to enter a number between 6 to 9, the error message is not displayed and the main menu appears. I am also trying to catch when a string is entered as input instead of a choice between 1 and 5 and display a different error message saying the user has entered an invalid input and then ask the user to re enter, however when a string is entered as the choice I get an input mismatch exception error but when a string is entered instead of a float after the operation has been chosen, then the correct error message is displayed.
I am a beginner to Java and am open to all suggestions but if it is possible I would like to keep my code somewhat similar to way it is written currently.
static void promptEnterKey() {
System.out.println("Press enter key to continue ...");
Scanner scanner = new Scanner(System.in);
scanner.nextLine();
}
public static void main(String[] args) {
float Firstnum, Secondnum, Solution;
int choice;
Scanner scan = new Scanner(System.in);
do {
System.out.printf("Welcome to Paul's Handy Calculator\n\n (1) Addition\n "
+ "(2) Subtraction\n (3) Multiplication\n (4) Division\n (5) Exit\n\n");
System.out.printf("What would you like to do? ");
choice = scan.nextInt();
try {
if (choice < 1 || choice > 5) {
System.out.printf("You have not entered a number between 1 and 5. "
+ "Try again.\n");
System.out.printf("Enter your choice between 1 and 5 only: \n");
choice = scan.nextInt();
continue;
}
switch (choice) {
case 1:
System.out.print("Please enter two floats to add, "
+ "separated by a space: ");
Firstnum = scan.nextFloat();
Secondnum = scan.nextFloat();
Solution = Firstnum + Secondnum;
System.out.println("Result of adding " + Firstnum + " and "
+ Secondnum + " is " + Solution + "\n");
promptEnterKey();
break;
case 2:
System.out.println("Please enter two floats to subtract, "
+ "separated by a space: ");
Firstnum = scan.nextFloat();
Secondnum = scan.nextFloat();
Solution = Firstnum - Secondnum;
System.out.println("Result of subtracting " + Firstnum
+ " and " + Secondnum + " is " + Solution + "\n");
promptEnterKey();
break;
case 3:
System.out.print("Please enter two floats to multiply, "
+ "separated by a space: ");
Firstnum = scan.nextFloat();
Secondnum = scan.nextFloat();
Solution = Firstnum * Secondnum;
System.out.print("Result of multiplying " + Firstnum + " and "
+ Secondnum + " is " + Solution + "\n");
promptEnterKey();
break;
case 4:
System.out.print("Please enter two floats to divide, "
+ "separated by a space: ");
Firstnum = scan.nextFloat();
Secondnum = scan.nextFloat();
if (Secondnum == 0) {
System.out.println("You cannot divide by zero, "
+ "please enter another number to divide by");
Secondnum = scan.nextFloat();
}
Solution = Firstnum / Secondnum;
System.out.println("Result of dividing " + Firstnum + " and "
+ Secondnum + " is " + Solution + "\n");
promptEnterKey();
break;
case 5:
System.out.println("Thank You for using Paul's Handy Calculator");
System.exit(0);
break;
default:
}
} catch (InputMismatchException ex) {
System.out.println("You have entered an invalid choice. Try again. ");
String flush =scan.next();
}
} while (choice != 5);
}
You just need to move your welcome message outside of the do-while, move your initial scan.nextInt() call inside the try block, and remove your scan.nextInt() call inside your if statement:
// Moved welcome message outside of do-while
System.out.printf("Welcome to Paul's Handy Calculator\n\n (1) Addition\n "
+ "(2) Subtraction\n (3) Multiplication\n (4) Division\n (5) Exit\n\n");
System.out.printf("What would you like to do? ");
do {
try {
// Moved scan.nextInt inside of try block
choice = scan.nextInt();
if (choice < 1 || choice > 5) {
System.out.printf("You have not entered a number between 1 and 5. " + "Try again.\n");
System.out.printf("Enter your choice between 1 and 5 only: \n");
// Removed nextInt call
continue;
}
...
Related
I am working on a simple/scientific calculator in java, and I am having trouble putting this in a while loop so the user can continuously use the calculator. I've tried putting it in different places in the code, but it either repeats the input section or doesn't repeat anything. Any tips? Here is my code below:
static Scanner s1 = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Welcome to my calculator:");
String operator = "";
Scanner op = new Scanner(System.in);
System.out.println("Type 1 if you wish to use the Standard calculator, 2 for the Scientific calculator, or QUIT if you wish to quit the program.");
operator = op.nextLine();
if (operator.equals("1")) {
System.out.println(standard());
}
if (operator.equals("2")) {
System.out.println(scientific());
}
if (operator.equals("QUIT")) {
System.out.print("System quit");
}
}
public static int standard() {
//The system will print 0 at the end to show that it's working
System.out.println("Standard Calculator chosen.");
System.out.println("Type 1 if you wish to use addition, 2 for subtraction, 3 for multiplication, 4 for exponent, 5 for division, or 6 for mod.");
int input2 = s1.nextInt();
int num1 = 0;
int num2 = 0;
//String loop = "";
switch (input2) {
case 1:
System.out.println("(Add chosen) Please enter the first value: ");
num1 = s1.nextInt();
System.out.println("Please enter the second value: ");
num2 = s1.nextInt();
System.out.println("Addition - (" + num1 + "+" + num2 + ") = " + addExact(num1, num2));
break;
case 2:
System.out.println("(Sub chosen) Please enter the first value: ");
num1 = s1.nextInt();
System.out.println("Please enter the second value: ");
num2 = s1.nextInt();
System.out.println("Subtration - (" + num1 + "-" + num2 + ") = " + subtractExact(num1, num2));
break;
case 3:
System.out.println("(Multi chosen) Please enter the first value: ");
num1 = s1.nextInt();
System.out.println("Please enter the second value: ");
num2 = s1.nextInt();
System.out.println("Multiplication - (" + num1 + "*" + num2 + ") = " + multiplyExact(num1, num2));
break;
case 4:
System.out.println("(Exp chosen) Please enter the first value: ");
num1 = s1.nextInt();
System.out.println("Please enter the exponent: ");
num2 = s1.nextInt();
System.out.println("Exponent - (" + num1 + "^" + num2 + ") = " + Math.pow(num1, num2));
break;
case 5:
System.out.println("(Div chosen) Please enter the first value: ");
num1 = s1.nextInt();
System.out.println("Please enter the second value: ");
num2 = s1.nextInt();
System.out.println("Division - (" + num1 + "/" + num2 + ") = " + floorDiv(num1, num2));
break;
case 6:
System.out.println("(Mod chosen) Please enter the first value: ");
num1 = s1.nextInt();
System.out.println("Please enter the second value: ");
num2 = s1.nextInt();
System.out.println("Mod - (" + num1 + "%" + num2 + ") = " + floorMod(num1, num2));
break;
}
return (0);
}
public static double scientific() {
//The system will print 0.0 at the end to show that it's working
System.out.println("Scientific Calculator chosen.");
System.out.println("Type 1 for sin, 2 for cos, 3 for tan, 4 for floor, 5 for ceil, 6 for square root, 7 for cube root, 8 for rounding, 9 for min, 10 for max.");
int input2 = s1.nextInt();
double val1 = 0.0;
double val2 = 0.0;
switch (input2) {
case 1:
System.out.println("(Sin chosen) Please enter the value :");
val1 = s1.nextDouble();
System.out.println("Sin - (" + val1 + ") = " + sin(val1));
break;
case 2:
System.out.println("(Cos chosen) Please enter the value :");
val1 = s1.nextDouble();
System.out.println("Cos - (" + val1 + ") = " + cos(val1));
break;
case 3:
System.out.println("(Tan chosen) Please enter the value :");
val1 = s1.nextDouble();
System.out.println("Tan - (" + val1 + ") = " + tan(val1));
break;
case 4:
System.out.println("(Floor chosen) Please enter the value :");
val1 = s1.nextDouble();
System.out.println("Floor - (" + val1 + ") = " + Math.floor(val1));
break;
case 5:
System.out.println("(Ceil chosen) Please enter the value :");
val1 = s1.nextDouble();
System.out.println("Ceil - (" + val1 + ") = " + Math.ceil(val1));
break;
case 6:
System.out.println("(Square root chosen) Please enter the value :");
val1 = s1.nextDouble();
System.out.println("Square root - (" + val1 + ") = " + sqrt(val1));
break;
case 7:
System.out.println("(Cube root chosen) Please enter the value :");
val1 = s1.nextDouble();
System.out.println("Cube root - (" + val1 + ") = " + cbrt(val1));
break;
case 8:
System.out.println("(Round chosen) Please enter the value :");
val1 = s1.nextDouble();
System.out.println("Round - (" + val1 + ") = " + round(val1));
break;
case 9:
System.out.println("(Min chosen) Please enter the 1st value :");
val1 = s1.nextDouble();
System.out.println("Enter the 2nd value: ");
val2 = s1.nextDouble();
System.out.println("Minimum - (" + val1 + "," + val2 + ") = " + min(val1,val2));
break;
case 10:
System.out.println("(Max chosen) Please enter the 1st value :");
val1 = s1.nextDouble();
System.out.println("Enter the 2nd value: ");
val2 = s1.nextDouble();
System.out.println("Maximum - (" + val1 + "," + val2 + ") = " + max(val1,val2));
break;
}
return val2;
}
}
}
You need to do something as follows, as you want to repeat all the process until the user choose to QUIT the calculator app:
public static void main(String[] args) {
System.out.println("Welcome to my calculator:");
String operator = "";
while (!operator.equals("QUIT")) {
Scanner op = new Scanner(System.in);
System.out.println("Type 1 if you wish to use the Standard calculator, 2 for the Scientific calculator, or QUIT if you wish to quit the program.");
operator = op.nextLine();
if (operator.equals("1")) {
System.out.println(standard());
}
if (operator.equals("2")) {
System.out.println(scientific());
}
if (operator.equals("QUIT")) {
System.out.print("System quit");
}
}
}
output:
Welcome to my calculator:
Type 1 if you wish to use the Standard calculator, 2 for the Scientific calculator, or QUIT if you wish to quit the program.
1
Standard Calculator chosen.
Type 1 if you wish to use addition, 2 for subtraction, 3 for multiplication, 4 for exponent, 5 for division, or 6 for mod.
1
(Add chosen) Please enter the first value:
1
Please enter the second value:
2
Addition - (1+2) = 3
0
Type 1 if you wish to use the Standard calculator, 2 for the Scientific calculator, or QUIT if you wish to quit the program.
Here's a solution for your "main" method that:
uses a "while" loop and a boolean value "keepGoing" to decide if it should loop again (or exit)
uses a "switch" statement to handle calling different functions based on input
if "QUIT" input, it sets "keepGoing = false" so that the "while" loop will exit
defines one Scanner, and names it clearly ("scanner")
passes that single Scanner object to the methods which need it (standard and scientific)
Two other changes worth making:
remove the global static Scanner s1 – don't use global variables, it will lead to hard-to-find problems in your code
edit those method signatures to accept a Scanner parameter:
public static int standard(Scanner s1)`
public static double scientific(Scanner s1)
Here's the code:
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to my calculator:");
String prompt = "Type 1 if you wish to use the Standard calculator, " +
"2 for the Scientific calculator, or " +
"QUIT if you wish to quit the program.";
boolean keepGoing = true;
while (keepGoing) {
System.out.println(prompt);
switch (scanner.nextLine()) {
case "1" -> System.out.println(standard(scanner));
case "2" -> System.out.println(scientific(scanner));
case "QUIT" -> {
System.out.print("System quit");
keepGoing = false; // this ejects from the while loop
}
}
}
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!
I am getting user inputs do some calculation and then repeatedly ask the user to take repeatedly until a Sentinel value (3 in my case) entered.
I am using do-while loop and it does not give my desired output as shown below,
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("1: Addition");
System.out.println("2: Multiplication");
System.out.println("3: Exit");
System.out.print("Please choose a number: ");
int userinput = input.nextInt();
// Generate two random numbers
int number1 = (int)(Math.random() * 10);
int number2 = (int)(Math.random() * 10);
do {
if (userinput == 1) {
System.out.print("What is " + number1 + " + " + number2);
int answer = input.nextInt();
int tureanswer = number1 + number2;
if (answer == tureanswer){
System.out.println("You're correct");
}
else
System.out.println("Wrong,correct answer is " + tureanswer);
}
if (userinput == 2) {
System.out.print("What is " + number1 + " * " + number2 + " : ");
int answer = input.nextInt();
int tureanswer = number1 * number2;
if (answer == tureanswer){
System.out.println("Correct");
}
else
System.out.println("Wrong. The correct answer is "+ tureanswer);
}
}while(userinput !=3);
}
}
I am getting the following output,
1: Multiplication
2: Addition
3: Exit
Please choose a number: 1
What is 9 + 1 12
Wrong,correct answer is 10
What is 9 + 1
However, I need something like this,(prompts the user to select the number not what is 9 + 1)
1: Addition
2: Multiplication
3: Exit
Please choose a number: 1
What is 9 + 1 12
Wrong,correct answer is 10
1: Addition
2: Multiplication
3: Exit
Please choose a number:
What am I doing wrong in my do statement? Any thought would be appreciated!
It looks to me like you need to move do { up a few lines.
Only the part between do { and while gets repeated, and you need that to include asking the user for which type of problem they want, and generating the random numbers.
However, you will need to declare userInput before do if you want to use it as the while condition.
int userInput;
do {
System.out.print("Please choose a number: ");
userinput = input.nextInt();
// Generate two random numbers
int number1 = (int)(Math.random() * 10);
int number2 = (int)(Math.random() * 10);
if (userinput == 1) {
// and so on ...
Add following lines in your do while
System.out.println("1: Multiplication");
System.out.println("2: Addition");
System.out.println("3: Exit");
System.out.print("Please choose a number: ");
int userinput = input.nextInt();
int number1 = (int)(Math.random() * 10);
int number2 = (int)(Math.random() * 10);
I also suggest you to use switch in do while because it's more practical than if else
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
int operator;
double number1, number2, result;
boolean ask = true;
while (ask) {
System.out.println("please select your operator:\n"
+ "1 for +\n" +
"2 for -\n" +
"3 for *\n" +
"4 for %\n" +
"");
operator = myScanner.nextInt();
System.out.println("you chose " + operator + " operator babe");
System.out.println("please enter your first number");
Scanner numberScanner = new Scanner(System.in);
number1 = numberScanner.nextDouble();
System.out.println("please enter your second number");
Scanner numberScanner2 = new Scanner(System.in);
number2 = numberScanner2.nextDouble();
switch (operator) {
case 1:
result = number1 + number2;
System.out.println("result is:" + result);
break;
case 2:
result = number1 - number2;
System.out.println("result is:" + result);
break;
case 3:
result = number1 * number2;
System.out.println("result is:" + result);
break;
case 4:
result = number1 / number2;
System.out.println("result is:" + result);
break;
default:
System.out.println("you chosen the wrong operator babe :)");
break;
}
System.out.println("do yo want to continue?\n" +
"y for yes\n" +
"n for no\n");
char askInput = myScanner.next().charAt(0);
if (askInput=='n') ask=false;
}
}
}
i got trouble in my switch case
if i press any number or letter somthing like 5 or 6 or... it should print you chose wrong operator.
i think problem is in my default but i don't know where is it?
Just reorder your code like this
`public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
int operator;
double number1, number2, result;
boolean ask = true;
while (ask) {
System.out.println("please enter your first number");
Scanner numberScanner = new Scanner(System.in);
number1 = numberScanner.nextDouble();
System.out.println("please enter your second number");
Scanner numberScanner2 = new Scanner(System.in);
number2 = numberScanner2.nextDouble();
System.out.println("please select your operator:\n"
+ "1 for +\n"
+ "2 for -\n"
+ "3 for *\n"
+ "4 for %\n"
+ "");
operator = myScanner.nextInt();
switch (operator) {
case 1:
result = number1 + number2;
System.out.println("result is:" + result);
break;
case 2:
result = number1 - number2;
System.out.println("result is:" + result);
break;
case 3:
result = number1 * number2;
System.out.println("result is:" + result);
break;
case 4:
result = number1 / number2;
System.out.println("result is:" + result);
break;
default:
System.out.println("you chosen the wrong operator babe :)");
break;
}
System.out.println("you chose " + operator + " operator babe");
System.out.println("do yo want to continue?\n"
+ "y for yes\n"
+ "n for no\n");
char askInput = myScanner.next().charAt(0);
if (askInput == 'n') {
ask = false;
}
}
}`
and you'll be fine
as for my comment, if you want to validate the input the user does (for the option) before having the user input another 2 numbers, than, yeah you should actually programm it that way that the validation goes RIGHT AFTER the first userinput. Here´s a slightly corrected version of your code.
public static void main(String[] args) {
int operator;
double result;
boolean ask = true;
Scanner numberScanner = new Scanner(System.in);
while (ask) {
System.out.println(
"please select your operator:\n" + "1 for +\n" + "2 for -\n" + "3 for *\n" + "4 for %\n" + "");
operator = numberScanner.nextInt();
System.out.println("you chose " + operator + " operator babe");
// Here was your "Mistake". You instantly started asking the user for another input,
// but actually wanted to ahve the switch statment here
switch (operator) {
case 1:
result = get_num1(numberScanner) + get_num2(numberScanner);
System.out.println("result is:" + result);
break;
case 2:
result = get_num1(numberScanner) - get_num2(numberScanner);
System.out.println("result is:" + result);
break;
case 3:
result = get_num1(numberScanner) * get_num2(numberScanner);
System.out.println("result is:" + result);
break;
case 4:
result = get_num1(numberScanner) % get_num2(numberScanner);
System.out.println("result is:" + result);
break;
default:
System.out.println("you chosen the wrong operator babe :)");
break;
}
System.out.println("do yo want to continue?\n" + "y for yes\n" + "n for no\n");
char askInput = numberScanner.next().charAt(0);
if (askInput == 'n')
ask = false;
}
}
public static double get_num1(Scanner scanner) {
System.out.println("please enter your first number");
return scanner.nextDouble();
}
public static double get_num2(Scanner scanner) {
System.out.println("please enter your second number");
return scanner.nextDouble();
}
simply you could validate the operator while you assign it with the input.
for example use if condition and check whether its between 1 and 5 and if not print whatever you want
2 things:
you dont need 2 scanners using only one will be enough
the code is behaving so because you go into the switch case AFTER asking the numbers you want to operate...
some condition like:
operator = myScanner.nextInt();
if (operator < 1 || operator > 4) {
}
may help....
I cannot figure this out, I have created a switch in Java for a user to enter specific details. I have created a print statement inside the case to print the result that has been entered. What I want to happen is for a separate print statement to display the combined details of the values entered (after say a few loops). Any help will be greatly appreciated.
Thanks in advance.
Here is my code
import java.util.Scanner;
public class Stage3Check {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Setup an exit statement
boolean quit = false;
while (!quit){
System.out.println("Enter one of the following commands:");
System.out.println("1 - Damage Repair");
System.out.println("2 - Traffic Infringement");
System.out.println("3 - Exit Menu");
int choiceEntry = Integer.parseInt(input.nextLine());
//Create switch
if (choiceEntry <1){
System.out.println("Please enter a valid menu command (1-3)");
}
else if (choiceEntry >3){
System.out.println("Please enter a valid menu command (1-3)");
}
double damageCost = 0;
switch (choiceEntry){
case 1: System.out.print("Enter a description of the damage:");
String damageDetail = input.nextLine();
System.out.print("Enter the damage cost:");
damageCost = Integer.parseInt(input.nextLine());
System.out.print("The damage is: " + damageDetail + "\n");
System.out.print("The damage cost is: " + "$" + damageCost + "\n");
break;
case 2: System.out.print("Enter a description of the traffic infringement:");
String trafficDetail = input.nextLine();
System.out.print("Enter the traffic infringement cost:");
double trafficCost = Integer.parseInt(input.nextLine());
break;
case 3: quit = true;
System.out.println("Menu entry has been terminated.");
break;
}
System.out.print("The damage cost is: " + "$" + damageCost + "\n");
}
}
}
You could try adding the option to an arraylist.
List<String> listOfEntries=new ArrayList<String>(); // Add strings like damage repair,etc
//Or you could try
List<Integer> listOfOptions=new ArrayList<Integer>();// Add option here, like 1,2
You can add the user chosen options and at any point of time, you can retreive the options chosen by the user and display the values to the user.
Hope this helps!
This would work:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Setup an exit statement
boolean quit = false;
double dCost=0;
double tCost=0;
StringBuilder dDetail= new StringBuilder("The Damage Details are :" );
StringBuilder tDetail= new StringBuilder("The Traffic details are: " );
while (!quit){
System.out.println("Enter one of the following commands:");
System.out.println("1 - Damage Repair");
System.out.println("2 - Traffic Infringement");
System.out.println("3 - Exit Menu");
int choiceEntry = Integer.parseInt(input.nextLine());
//Create switch
if (choiceEntry <1){
System.out.println("Please enter a valid menu command (1-3)");
}
else if (choiceEntry >3){
System.out.println("Please enter a valid menu command (1-3)");
}
double damageCost = 0;
switch (choiceEntry){
case 1: System.out.print("Enter a description of the damage:");
String damageDetail = input.nextLine();
System.out.print("Enter the damage cost:");
damageCost = Integer.parseInt(input.nextLine());
System.out.print("The damage is: " + damageDetail + "\n");
System.out.print("The damage cost is: " + "$" + damageCost + "\n");
dDetail.append(damageDetail+"\n");
dCost=dCost+damageCost;
break;
case 2: System.out.print("Enter a description of the traffic infringement:");
String trafficDetail = input.nextLine();
System.out.print("Enter the traffic infringement cost:");
double trafficCost = Integer.parseInt(input.nextLine());
tDetail.append( trafficDetail+"\n");
tCost=tCost+trafficCost;
break;
case 3: quit = true;
System.out.println("Menu entry has been terminated.");
System.out.println("the Total traffic cost is "+tCost);
System.out.println("the Total Damage cost is "+dCost);
System.out.println(tDetail);
System.out.println(dDetail);
break;
}
}
}
Use StringBuilder to append your data. PFB updated code :
import java.util.Scanner;
public class Stage3Check {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Setup an exit statement
boolean quit = false;
StringBuilder sb = new StringBuilder();
outer: while (!quit) {
System.out.println("Enter one of the following commands:");
System.out.println("1 - Damage Repair");
System.out.println("2 - Traffic Infringement");
System.out.println("3 - Exit Menu");
int choiceEntry = Integer.parseInt(input.nextLine());
// Create switch
if (choiceEntry < 1 || choiceEntry > 3)
continue outer;
double damageCost = 0;
switch (choiceEntry) {
case 1:
System.out.print("Enter a description of the damage:");
String damageDetail = input.nextLine();
System.out.print("Enter the damage cost:");
damageCost = Integer.parseInt(input.nextLine());
sb.append("The damage is: " + damageDetail + "\n");
sb.append("The damage cost is: " + "$" + damageCost + "\n");
break;
case 2:
System.out
.print("Enter a description of the traffic infringement:");
String trafficDetail = input.nextLine();
System.out.print("Enter the traffic infringement cost:");
double trafficCost = Integer.parseInt(input.nextLine());
sb.append("The traffic infringement is: " + trafficDetail
+ "\n");
sb.append("The traffic infringement cost is: " + "$"
+ trafficCost + "\n");
break;
default:
quit = true;
System.out.println("Menu entry has been terminated.");
break;
}
}
System.out.println(sb.toString());
}
}
1- The print statement should be placed outside the while loop:
System.out.print("The damage cost is: " + "$" + damageCost + "\n");
2- Declare the damageCost variable globally i.e outside the while loop.
3- Change the statement:
double trafficCost = Integer.parseInt(input.nextLine());
to
damageCost = damageCost + Integer.parseInt(input.nextLine());