How to make a loop for this script? - java

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
}
}
}

Related

Java use user input from other methods

I visited other questions similar to mine but did not find the one that is applicable to me.
To lessen my line of codes instead of copy pasting that input process to my if else statement. I created a UInputs(); method that will get user inputs. So I can just call it whenever it is needed but i cant use the user inputted values inside UInputs().
import java.util.Scanner;
public class Calculator {
public static void UInputs(){
double num1, num2, num3, num4, num5;
Scanner scan = new Scanner(System.in);
System.out.print("1st Number: ");
num1 = scan.nextDouble();
System.out.print("2nd Number: ");
num2 = scan.nextDouble();
System.out.print("3rd Number: ");
num3 = scan.nextDouble();
System.out.print("4th Number: ");
num4 = scan.nextDouble();
System.out.print("5th Number: ");
num5 = scan.nextDouble();
}
public static void main (String[] args){
char Choice;
double num1, num2, num3, num4, num5;
System.out.println("\t_________________________________\n");
System.out.println("\t|\tMATH OPERATIONS\t\t|\n\t|\t[+]\tAddition\t|\n\t|\t[-]\tSubtraction\t|\n\t|\t[*]\tMultiplication\t|\n\t|\t[/]\tDivision\t|\n");
System.out.println("\t|_______________________________|\n");
System.out.print("\nEnter you Choice: ");
Scanner scan = new Scanner(System.in);
Choice = scan.nextLine().charAt(0);
if ( Choice == '+') {//ADDITION
System.out.println("================================\nAddition\n");
UInputs();
double answer = num1 + num2 + num3 + num4 + num5;
System.out.println("\nSum : " + answer );
System.out.println("================================\n");
}
else if (Choice == '-') {//SUBTRACTION
System.out.println("================================\nSubtraction\n");
System.out.print("1st Number: ");
num1 = scan.nextDouble();
System.out.print("2nd Number: ");
num2 = scan.nextDouble();
System.out.print("3rd Number: ");
num3 = scan.nextDouble();
System.out.print("4th Number: ");
num4 = scan.nextDouble();
System.out.print("5th Number: ");
num5 = scan.nextDouble();
double answer = num1 - num2 - num3 - num4 - num5;
System.out.println("\nDifference : " + answer );
System.out.println("================================\n");
}
Not the best answer I could have come up with but certainly some improvements to make the code easier to digest...
I changed UInputs to a method called calculate(). It now takes the function selected as input and then asks the user for 5 numbers. The function is then applied to the 5 numbers. Another way to perform this calculation would be to request a number from the user, return it, and sequentially apply the function to the returned number(s) to get a result... this would be nicer.
import java.util.Scanner;
public class Calculator {
private static final Scanner scan = new Scanner(System.in);
/**
* My initial thought here was that UInputs should return values
* and these should be cumulatively totalled.
* There's no need to hold the inputs in memory since
* once they're consumed, they're not longer needed.
*/
public static double calculate(char functionToApply) {
double[] inputs = new double[5];
// works for number of inputs up to 20 - could just print "number i: " here for simplicity.
for (int i=0; i<inputs.length; i++) {
String promptMessage = (i+1) + ""; // number
// postfixture (st, nd, rd, th)
switch (i+1) {
case 1: promptMessage = promptMessage+"st"; break;
case 2: promptMessage = promptMessage+"nd"; break;
case 3: promptMessage = promptMessage+"rd"; break;
default: promptMessage = promptMessage+"th"; break;
}
System.out.print(promptMessage + " Number: ");
inputs[i] = scan.nextDouble();
}
double result = 0;
for (int i=0; i<inputs.length; i++) {
switch (functionToApply) {
case '+': result = result + inputs[i]; break;
case '-': result = result - inputs[i]; break;
}
}
return result;
}
public static void main(String[] args) {
displayMenu();
char function;
System.out.print("\nEnter your Choice: ");
function = scan.nextLine().charAt(0);
String heading = "";
String lineLabel = "";
switch (function) {
case '+':
heading = "Addition";
lineLabel = "Sum";
break;
case '-':
heading = "Subtraction";
lineLabel = "Difference";
break;
}
System.out.println("================================\n" + heading + "\n");
System.out.println("\n" + lineLabel + " : " + calculate(function));
System.out.println("================================\n");
}
private static void displayMenu() {
System.out.println("\t_________________________");
System.out.println("\t|\tMATH OPERATIONS\t\t|");
System.out.println("\t|\t[+]\tAddition\t\t|");
System.out.println("\t|\t[-]\tSubtraction\t\t|");
System.out.println("\t|\t[*]\tMultiplication\t|");
System.out.println("\t|\t[/]\tDivision\t\t|");
System.out.println("\t|_______________________|\n");
}
}
This should be easier for you to extend/edit though.
Output:
_________________________
| MATH OPERATIONS |
| [+] Addition |
| [-] Subtraction |
| [*] Multiplication |
| [/] Division |
|_______________________|
Enter your Choice: +
================================
Addition
1st Number: 1
2nd Number: 2
3rd Number: 3
4th Number: 4
5th Number: 5
Sum : 15.0
================================
Process finished with exit code 0
Similarly for subtraction:
Enter your Choice: -
================================
Subtraction
1st Number: 10
2nd Number: 9
3rd Number: 1
4th Number: 0
5th Number: 0
Difference : -20.0
================================
you can create some kind of wrapper class
class MyNumberWrapper {
double num1;
double num2;
}
then UInput will look like this
public static MyNumberWrapper UInputs(){
MyNumberWrapper wrapper = new MyNumberWrapper();
Scanner scan = new Scanner(System.in);
System.out.print("1st Number: ");
wrapper.num1 = scan.nextDouble();
System.out.print("2nd Number: ");
wrapper.num2 = scan.nextDouble();
return wrapper;
}
then in your main function you can just use MyNumberWrapper wrapper = UInput() and access all variables with wrapper.num1, wrapper.num2 etc

How to fix exception handling issue in switch case statement?

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;
}
...

Repeat a set of instruction with while loop - Java

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

logical bug in my code in java... in switch case

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....

Java - Program not breaking out of loop?

while (choice != 7) {
System.out.println("--- Mathematical Calculator ---");
System.out.println("");
System.out.println("Pick an operation from the list - Use nos. 1 to 7");
System.out.println("1) Multiplication");
System.out.println("2) Division");
System.out.println("3) Addition");
System.out.println("4) Subtraction");
System.out.println("5) Find the area of a regular object");
System.out.println("6) Find the volume of a regular object");
System.out.println("7) Exit");
choice = userInput.nextInt();
switch (choice) {
case 1: {
System.out.println("");
System.out.println("You have chosen multiplication");
System.out.println("Enter a number");
double num1 = userInput.nextDouble();
System.out.println("Enter another number");
double num2 = userInput.nextDouble();
double num3 = num1 * num2;
System.out.println(num1 + " * " + num2 + " = " + num3);
num1 = num3;
while (choice2 != 5 || choice2 != 6) {
System.out.println(""); System.out.println("");
System.out.println("If you would like to build on the answer obtained - pick an operation from the list - Use nos. 1 to 4");
System.out.println("Else press 5 to return to the main menu");
System.out.println("1) Multiplication");
System.out.println("2) Division");
System.out.println("3) Addition");
System.out.println("4) Subtraction");
System.out.println("5) Start new calculation");
System.out.println("6) Exit");
choice2 = userInput.nextInt();
switch (choice2) {
case 1:
{
System.out.println("Enter number");
num2 = userInput.nextDouble();
num3 = num1 * num2;
System.out.println(num1 + " * " + num2 + " = " + num3);
num1 = num3;
break;
}
case 2:
{
System.out.println("Enter number");
num2 = userInput.nextDouble();
num3 = num1 / num2;
System.out.println(num1 + " / " + num2 + " = " + num3);
num1 = num3;
reak;
}
case 3:
{
System.out.println("Enter number");
num2 = userInput.nextDouble();
num3 = num1 + num2;
System.out.println(num1 + " + " + num2 + " = " + num3);
num1 = num3;
break;
}
case 4:
{
System.out.println("Enter number");
num2 = userInput.nextDouble();
num3 = num1 - num2;
System.out.println(num1 + " - " + num2 + " = " + num3);
num1 = num3;
break;
}
case 5: choice = 0; break;
case 6: choice = 7; break;
default: System.out.println("Invalid choice");
}
choice2 = 0;
}
break;
}
I've posted a short piece of my code. My issue is that, when I input 5 or 6 in the second query (choice2), my program continues to loop instead of breaking out of the loop and going back to the main menu/ terminating the program.
Would appreciate some feedback on what I'm doing wrong.
Your while (choice2 != 5 || choice2 != 6) is wrong, since it will always result in true. If choice2 is 5, then the second clause will be true.
Not to mention that you always set choice2 to 0 at the end of the loop, so the loop will continue forever even if you replace || with &&.
The condition choice2 != 5 || choice2 != 6 is always true, because there is no number that is equal to 5 and to 6 at the same time.
If you would like to break out of the loop when 5 or 6 is entered, use && instead:
while (choice2 != 5 && choice2 != 6)
Make sure that choice2 is set prior to continuing with the next iteration of the loop.
Note that you could break out of the loop from within your switch statement by using a labeled break construct:
calc: // Label the loop for using labeled break
while (true) {
...
switch(...) {
case 1:
break; // This will exit the switch
...
case 6: break calc; // This will exit the loop
}
}

Categories

Resources