make a basic calculator [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
So I am new to Java and to practice my skills I decided to make a basic calculator. So this is my code:
/*Basic calculator.*/
package calculator;
import java.util.Scanner;
public class no_gui {
public static void main(String[] args) {
System.out.println("What math operation do you want to do?");
System.out.println("1. Addition, 2. Subtraction, 3. Multipilcation, 4. Division");
System.out.println("Enter number to corresponding math operation.");
Scanner calc = new Scanner(System.in);
double choice = calc.nextDouble();
double add1, add2, addAnswer, sub1, sub2, subAnswer, mult1, mult2, multAnswer, div1, div2, divAnswer;
if (choice == 1){
System.out.println("Addition");
System.out.println("Enter first number: ");
add1 = calc.nextDouble();
System.out.println("Enter second number: ");
add2 = calc.nextDouble();
addAnswer = add1 + add2;
System.out.println("Your answer is " + addAnswer);
if(choice == 2){
System.out.println("Subtraction");
System.out.println("Enter first number: ");
sub1 = calc.nextDouble();
System.out.println("Enter second number: ");
sub2 = calc.nextDouble();
subAnswer = sub1 + sub2;
System.out.println("Your answer is " + subAnswer);
if(choice == 3){
System.out.println("Multipilcation");
System.out.println("Enter first number: ");
mult1 = calc.nextDouble();
System.out.println("Enter second number: ");
mult2 = calc.nextDouble();
multAnswer = mult1 + mult2;
System.out.println("Your answer is " + multAnswer);
if(choice == 4){
System.out.println("Divsion");
System.out.println("Enter first number: ");
div1 = calc.nextDouble();
System.out.println("Enter second number: ");
div2 = calc.nextDouble();
divAnswer = div1 + div2;
System.out.println("Your answer is " + divAnswer);
}else{
System.out.println("Re-run to use again.");
}
}
}
}
}
}
Every time I run it and choose addition it'll do what ever is inside the if statement. But when I try subtraction it just prints out 2 and terminates the program. It worked before but today it stopped. I even tried a different method of coding and it still doesn't work.
EDIT: Thanks to everyone who responded. My main issue was resolved. But I also have this issue with switch statements and I forgot to mention that in my main question. Do I have to space everything? Does that cause the problem?

You have nested if clauses. Look at your code and think about it logically.
if (choice == 1) {
//add
if (choice == 2) {
//subtract
}
}
You will never enter subtract or any other option for that matter because the outer choice == 1 will never be true. Use this structure instead.
if (choice == 1) {
//add
}else if (choice == 2) {
//subtract
}
Or better, use switch statment. An example is given below:
int month = 8;
String monthString;
switch (month) {
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
case 3: monthString = "March";
break;
case 4: monthString = "April";
break;
case 5: monthString = "May";
break;
case 6: monthString = "June";
break;
case 7: monthString = "July";
break;
case 8: monthString = "August";
break;
case 9: monthString = "September";
break;
case 10: monthString = "October";
break;
case 11: monthString = "November";
break;
case 12: monthString = "December";
break;
default: monthString = "Invalid month";
break;
}
Example source : http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

Your problem is that your checks of choice are all nested:
if (choice == 1){
// ...
if(choice == 2){
// ...
if(choice == 3){
// ...
if(choice == 4){
// ...
}else{
System.out.println("Re-run to use again.");
}
}
}
}
If choice is 1, then that block will be executed. If it's not 1, then the blocks that should be executed are all unreachable.
Try re-arranging your program like this instead:
if (choice == 1){
// ...
} else if(choice == 2){
// ...
} else if(choice == 3){
// ...
} else if(choice == 4){
// ...
} else {
System.out.println("Re-run to use again.");
}

Your problem would be self-evident if you clicked "format code" in your IDE...
You have (inappropriately) nested your if blocks, like this:
if (choice == 1) {
// do addition
if (choice == 2) {
// etc
Clearly, if choice is anything other than 1, the corresponding if block(s) will never get entered.
Instead, make the if blocks siblings:
if (choice == 1) {
// do addition
} else if (choice == 2) {
// etc

Because you are not closing your if blocks properly. you should:
if (choice == 1) {
System.out.println("Addition");
System.out.println("Enter first number: ");
add1 = calc.nextDouble();
System.out.println("Enter second number: ");
add2 = calc.nextDouble();
addAnswer = add1 + add2;
System.out.println("Your answer is " + addAnswer);
} else if (choice == 2) {
System.out.println("Subtraction");
System.out.println("Enter first number: ");
sub1 = calc.nextDouble();
System.out.println("Enter second number: ");
sub2 = calc.nextDouble();
subAnswer = sub1 + sub2;
System.out.println("Your answer is " + subAnswer);
} else if (choice == 3) {
System.out.println("Multipilcation");
System.out.println("Enter first number: ");
mult1 = calc.nextDouble();
System.out.println("Enter second number: ");
mult2 = calc.nextDouble();
multAnswer = mult1 + mult2;
System.out.println("Your answer is " + multAnswer);
} else if (choice == 4) {
System.out.println("Divsion");
System.out.println("Enter first number: ");
div1 = calc.nextDouble();
System.out.println("Enter second number: ");
div2 = calc.nextDouble();
divAnswer = div1 + div2;
System.out.println("Your answer is " + divAnswer);
} else {
System.out.println("Re-run to use again.");
}

It is better in this case to use a switch/case:
import java.util.Scanner;
public class no_gui {
public static void main(String[] args) {
Scanner calc = new Scanner(System.in);
//double choice = calc.nextDouble();
int choice = 0;
boolean getOut=false;
double add1, add2, addAnswer, sub1, sub2, subAnswer, mult1, mult2, multAnswer, div1, div2, divAnswer;
while(!getOut)
{
System.out.println("What math operation do you want to do?");
System.out.println("1. Addition, 2. Subtraction, 3. Multipilcation, 4. Division, else: stop");
System.out.println("Enter number to corresponding math operation:");
choice = 0;
choice = calc.nextInt();
switch(choice)
{
case 1:
System.out.println("Addition");
System.out.println("Enter first number: ");
add1 = calc.nextDouble();
System.out.println("Enter second number: ");
add2 = calc.nextDouble();
addAnswer = add1 + add2;
System.out.println("Your answer is " + addAnswer);break;
case 2:
System.out.println("Subtraction");
System.out.println("Enter first number: ");
sub1 = calc.nextDouble();
System.out.println("Enter second number: ");
sub2 = calc.nextDouble();
subAnswer = sub1 - sub2;
System.out.println("Your answer is " + subAnswer);break;
case 3:
System.out.println("Multipilcation");
System.out.println("Enter first number: ");
mult1 = calc.nextDouble();
System.out.println("Enter second number: ");
mult2 = calc.nextDouble();
multAnswer = mult1 + mult2;
System.out.println("Your answer is " + multAnswer);break;
case 4:
System.out.println("Divsion");
System.out.println("Enter first number: ");
div1 = calc.nextDouble();
System.out.println("Enter second number: ");
div2 = calc.nextDouble();
divAnswer = div1 + div2;
System.out.println("Your answer is " + divAnswer);break;
default:System.out.println("Good Bye");getOut = true;break;
}
}
}}

Related

Continuity Issue in Java Calculator

I am new to Java, and I'm doing a calculator APP.
I'm trying to get my calculator to keep prompting the user for the correct answer (typing Y or N) after the else statement following 'Invalid Input'.
I want the program to continue with the calculations after the correct input is finally entered.
I have played around with an embedded while loop, but ended up with an infinite loop or a loop that terminates with no resolution. The code is below.
import java.util.Scanner;
class Calculate {
public static void.main(String[] args) {
System.out.println("Welcome To Calculator!");
System.out.println("*************************************************************************");
Scanner userinput = new Scanner(System.in);
double num1, num2;
String choice;
boolean youDecide = true;
while(youDecide == true) {
System.out.println("Please enter a number: ");
num1 = userinput.nextDouble();
System.out.println("Please enter an available operator (+, -, *, /): ");
char operator = userinput.next().charAt(0);
System.out.println("Please enter another number: ");
num2 = userinput.nextDouble();
double output;
switch(operator)
{
case '+':
output = num1 + num2;
break;
case '-':
output = num1 - num2;
break;
case '*':
output = num1 * num2;
break;
case '/':
output = num1 / num2;
if(num2 == 0)
System.out.println("Math error! A number cannot be divided by zero.");
break;
default:
System.out.println("Invalid input. Please enter an available operator, i.e (+, -, *, /): ");
return;
}
System.out.println("*************************************************************************");
System.out.println("The answer is: " + "\n" + output);
System.out.println("*************************************************************************");
System.out.println("Would you like to calculate again?");
System.out.println("Please enter Y for yes, or N for no");
choice = userinput.next();
if(choice.equalsIgnoreCase("Y")) {
System.out.println("Okay. Let's continue!");
System.out.println("*************************************************************************");
youDecide = true;
}
else if(choice.equalsIgnoreCase("N")) {
System.out.println("*************************************************************************");
System.out.println("Okay. Thanks for using Calculator. Goodbye!");
System.exit(0);
}
else {
System.out.println("Invalid input. Please try again...");
System.out.println("*************************************************************************");
youDecide = false;
}
}
}
}
I've made some changes and comments to your code
import java.util.Scanner;
class Calculator {
public static void main(String[] args) {
System.out.println("Welcome To Calculator!");
System.out.println("*************************************************************************");
Scanner userinput = new Scanner(System.in);
double num1, num2;
String choice;
//the "youDecide" variable is not needed at all
while (true) {
System.out.println("Please enter a number: ");
num1 = userinput.nextDouble();
System.out.println("Please enter an available operator (+, -, *, /): ");
char operator = userinput.next().charAt(0);
System.out.println("Please enter another number: ");
num2 = userinput.nextDouble();
double output;
switch (operator) {
case '+':
output = num1 + num2;
break;
case '-':
output = num1 - num2;
break;
case '*':
output = num1 * num2;
break;
case '/':
output = num1 / num2;
if (num2 == 0) {
System.out.println("Math error! A number cannot be divided by zero.");
}
break;
default:
System.out.println("Invalid input. Please enter an available operator, i.e (+, -, *, /): ");
continue; //changed from "return" you don't want to exit, just to skip to the next execution of the loop
}
System.out.println("*************************************************************************");
System.out.println("The answer is: " + "\n" + output);
System.out.println("*************************************************************************");
System.out.println("Would you like to calculate again?");
System.out.println("Please enter Y for yes, or N for no");
choice = userinput.next();
if (choice.equalsIgnoreCase("Y")) {
System.out.println("Okay. Let's continue!");
System.out.println("*************************************************************************");
} else if (choice.equalsIgnoreCase("N")) {
System.out.println("*************************************************************************");
System.out.println("Okay. Thanks for using Calculator. Goodbye!");
System.exit(0);
} else {
System.out.println("Invalid input. Please try again...");
System.out.println("*************************************************************************");
}
}
}
}
You need a while loop to ensure the value is correct.
Due the logic into your code you need to do when the user type the char, otherwise you have to change many lines of code, or ask for all values again.
I think for a begginer the easiest way is using this loop:
char operator;
while(true) {
operator = userinput.next().charAt(0);
if(operator=='+' || operator == '-' || operator == '*' || operator == '/') {
break;
}else {
System.out.println("Please enter a valid operator: ");
}
}
Exists many ways more elegant to do this. But I think for a begginer is the easiest way to understand and implement the code.
This loop is only to ensure the user type a valid character. While the character is not one of them, the loop will be iterating.
You have to place this code just below this line where you ask for a valid operator.
After adding the edits suggested by J.F. and Javaman along with some research, I was able to solve the problem by adding the following lines to my code:
import java.util.InputMismatchException;
import java.util.Scanner;
class Calculator {
public static void main(String[] args) {
System.out.println("Welcome To Calculator!");
System.out.println("*************************************************************************");
Scanner userinput = new Scanner(System.in);
char operator;
double num1, num2;
String choice;
while(true) {
System.out.println("Please enter a number: ");
num1 = userinput.nextDouble();
System.out.println("Please enter an available operator (+, -, *, /): ");
while(true) {
operator = userinput.next().charAt(0);
if(operator == '+' || operator == '-' || operator == '*' || operator == '/') {
break;
}else {
System.out.println("Invalid input. Please enter an available operator, i.e (+, -, *, /): ");
}
}
System.out.println("Please enter another number: ");
num2 = userinput.nextDouble();
double output;
switch(operator) {
case '+':
output = num1 + num2;
break;
case '-':
output = num1 - num2;
break;
case '*':
output = num1 * num2;
break;
case '/':
output = num1 / num2;
break;
default:
System.out.println("Invalid input. Please enter an available operator, i.e (+, -, *, /): ");
continue;
}
System.out.println("*************************************************************************");
if(num2 == 0) {
System.out.println("Math error! A number cannot be divided by zero.");
}else {
System.out.println("The answer is: " + "\n" + output);
}
System.out.println("*************************************************************************");
System.out.println("Would you like to calculate again?");
System.out.println("Please enter Y for yes, or N for no");
choice = userinput.next();
if(choice.equalsIgnoreCase("Y")) {
System.out.println("Okay. Let's continue!");
System.out.println("*************************************************************************");
}else if(choice.equalsIgnoreCase("N")) {
System.out.println("*************************************************************************");
System.out.println("Okay. Thanks for using Calculator. Goodbye!");
System.exit(0);
}else {
System.out.println("Invalid input. Please try again...");
System.out.println("*************************************************************************");
**while (!("Y").equalsIgnoreCase(choice) && !("N").equalsIgnoreCase(choice)) {
System.out.println("Invalid input. Please try again...");
System.out.println("*************************************************************************");
System.out.println("Please enter Y for yes, or N for no");
choice = userinput.next();
if(choice.equalsIgnoreCase("Y")) {
System.out.println("Okay. Let's continue!");
System.out.println("*************************************************************************");
}else if(choice.equalsIgnoreCase("N")) {
System.out.println("*************************************************************************");
System.out.println("Okay. Thanks for using Calculator. Goodbye!");
System.exit(0);**
}
}
}
}
}
}

How can I get a calculation in this Calculation Code?

I need a little help here. The question is the output (PS! the last output line).The program only prints only number 2 on the last line. How can I get the calculation. Thank You!
Output is here:
Choose from the following calculations:
1: subtraction
2: addition
3: multiplication
4: division
5: remainder
Make your choice: 1
Type in the first number: 9
Type in the second number: 7
9 - 7 = 2
import java.util.Scanner;
public class Calculation
{
public static void main(String[] args)
{
System.out.println("Choose from the following calculations:");
System.out.println("1: subtraction");
System.out.println("2: addition");
System.out.println("3: multiplication");
System.out.println("4: division");
System.out.println("5: remainder");
Scanner input = new Scanner(System.in);
System.out.print("\nMake your choice:");
int choice = input.nextInt();
if( 1 <= choice && choice <= 5 )
{
System.out.print("\nType the first number: ");
int first = input.nextInt();
System.out.print("Type the second number: ");
int second = input.nextInt();
switch (choice)
{
case 1:
System.out.println(+ (first - second));
break;
case 2:
System.out.println(+ (first + second));
break;
case 3:
System.out.println(+ (first * second));
break;
case 4:
System.out.println(+ ((double)first / (double)second));
break;
case 5:
System.out.println(+ (first % second));
break;
default:
break;
}
}
else
{
System.out.println("Invalid choice");
}
}
}
try this
System.out.println(first+"-"+second+"="+(first-second));
System.out.println(first+"+"+second+"="+(first+second));
System.out.println(first+"*"+second+"="+(first*second));
System.out.println(first+"/"+second+"="+((double)first / (double)second));
System.out.println(first+"%"+second+"="+(first%second));
P.S you are not considering Divide by zero error for your division.

How do I get the menu program to restart after completing a selection?

My program is stuck in an infinite loop after a selection is made and completed. It needs to restart and go through the menu options again. Any help would be greatly appreciated.
public static void main(String[] args) {
// TODO Auto-generated method stub
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
System.out.println("Menu");
System.out.println("1. Add");
System.out.println("2. Subtract");
System.out.println("3. Multiply");
System.out.println("4. Divide");
System.out.println("5. Generate a random number");
System.out.println("6. Quit\n");
System.out.print("What would you like to do? ");
int choice = input.nextInt();
int count = 0;
while (choice < 1 || choice > 6){
count ++;
System.out.println("I'm sorry, " +choice+ " is not a valid option.\n");
System.out.println("Menu");
System.out.println("1. Add");
System.out.println("2. Subtract");
System.out.println("3. Multiply");
System.out.println("4. Divide");
System.out.println("5. Generate a random number");
System.out.println("6. Quit\n");
System.out.print("What would you like to do? ");
choice = input.nextInt();
if (choice >= 1 && choice <= 6){
continue;
}
else if (count == 2){
System.out.println("Please try again later.");
System.exit(0);
return;
}
}
do
{
switch (choice)
{
case 1: choice = 1;
System.out.print("What is the first number? ");
int firstAdd = input.nextInt();
System.out.print("What is the second number? ");
int secondAdd = input.nextInt();
System.out.println("Answer: " +(firstAdd + secondAdd));
break;
case 2: choice = 2;
System.out.print("What is the first number? ");
int firstSub = input.nextInt();
System.out.print("What is the second nubmer? ");
int secondSub = input.nextInt();
System.out.println("Answer: " +(firstSub - secondSub));
break;
case 3: choice = 3;
System.out.print("What is the first number?" );
int firstMult = input.nextInt();
System.out.print("What is the second number? ");
int secondMult = input.nextInt();
System.out.println("Answer: " +(firstMult * secondMult));
break;
case 4: choice = 4;
System.out.print("What is the first number? ");
double firstDiv = input.nextInt();
System.out.print("What is the second number? ");
double secondDiv = input.nextInt();
while (secondDiv == 0){
System.out.println("I'm sorry, you can't divide by zero.");
break;}
{
System.out.println("Answer: " +(firstDiv / secondDiv));
break;
}
case 5: choice = 5;
System.out.println(Math.random() * 10 + 1);
break;
case 6: choice = 6;
System.out.println("Goodbye!");
System.exit(0);
return;
}
}while (choice >=1 && choice <= 6);
}
I've tried a few different options that I found in my book, but they seem to cause more errors in other areas. I don't know if there is a different statement than "break;" to use to restart the menu because this is my first time using cases.
Enclose everything after the scanner instantiation in a while loop.
Specifically,
while (true) {
// your code
if (choice == 6)
break;
}
FIXED: Also remove the do {} while() loop. Your loop is infinite because "choice" does not change in the loop.

Calculator in Java: How to return to the main menu?

I've writter a calculator program in Java, after a user is done with work,
I want this to happen:
i'll ask if he wants to do more operations, if yes, the program should return to choice input. If no, break the program.
What lines should I add to the code? This is my calc program:
import java.util.*;
class calc
{
public static void main(String ar[])
{
char choice;
Scanner in = new Scanner(System.in);
System.out.println("WELCOME TO SHREYDAN'S CALC 1.0");
System.out.println(" ");
System.out.println("YOU CAN DO THE FOLLOWING:");
System.out.println("+: ADDITION");
System.out.println("-: SUBTRACTION");
System.out.println("*: PRODUCT");
System.out.println("/: QUOTIENT");
System.out.println("#: SQUARE ROOT");
System.out.println("^: POWER");
System.out.println("$: ROUND OFF");
System.out.println("!: FACTORIAL");
System.out.println(" ");
System.out.println("ENTER CHOICE");
choice=in.next().charAt(0);
switch(choice)
{
case '+':
System.out.println("ENTER 2 NUMBERS, USER");
double a=in.nextDouble();
double b=in.nextDouble();
System.out.println("SUM = "+(a+b));
break;
case '-':
System.out.println("ENTER 2 NUMBERS, USER");
double c=in.nextDouble();
double d=in.nextDouble();
System.out.println("SUBTRACTING "+d+" FROM "+c+" ... DIFFERENCE = "+(c-d));
break;
case '*':
System.out.println("ENTER 2 NUMBERS, USER");
double e=in.nextDouble();
double f=in.nextDouble();
System.out.println("PRODUCT = "+(e*f));
break;
case '/':
System.out.println("ENTER 2 NUMBERS, USER");
double g=in.nextDouble();
double h=in.nextDouble();
System.out.println("DIVIDING "+g+" BY "+h+" = "+(g/h));
break;
case '#':
System.out.println("ENTER NO. FOR SQAURE ROOT:");
double sqrt=in.nextDouble();
System.out.println("SQUARE ROOT OF "+sqrt+" = "+Math.sqrt(sqrt));
break;
case '^':
System.out.println("ENTER BASE, USER");
double base=in.nextDouble();
System.out.println("ENTER POWER, USER");
double power=in.nextDouble();
System.out.println(base+" RAISED TO POWER "+power+" = "+Math.pow(base,power));
break;
case '$':
System.out.println("ENTER DECIMAL VALUES TO ROUND OFF");
double deci=in.nextDouble();
System.out.println("THE NEAREST ROUND OFF = "+Math.round(deci));
break;
case '!':
System.out.println("ENTER A NO. FOR FACTORIAL:");
int fact=in.nextInt();
int factorial=1;
for(int i=fact; i>=1;i--)
factorial=factorial*i;
System.out.println(fact+"! = "+factorial);
break;
default:
System.out.println("WRONG CHOICE USER");
}
}
}
while loops are your best bet for this type of problem, just think of a condition which the user can choose to toggle the boolean condition.
for example if the user chooses no on the "continuing of operations" choice, then toggle the boolean to false and exit the while loop to end the program.
You need to wrap the program logic in a loop.
Try using a while loop
public static void main(String args[])
{
boolean doContinue = true;
while(doContinue){
char choice;
Scanner in = new Scanner(System.in);
//program logic
//when the user enters a command to end
// set continue=false
}
}
Maybe put the entire program inside a while loop with a continue to run bool condition which could be set false when they want to quit
You can try the following:
import java.util.*;
class calc {
public static void main(String ar[]) {
char choice;
Scanner in = new Scanner(System.in);
System.out.println("WELCOME TO SHREYDAN'S CALC 1.0");
System.out.println(" ");
boolean loop = true;
while (loop) {
System.out.println("YOU CAN DO THE FOLLOWING:");
System.out.println("+: ADDITION");
System.out.println("-: SUBTRACTION");
System.out.println("*: PRODUCT");
System.out.println("/: QUOTIENT");
System.out.println("#: SQUARE ROOT");
System.out.println("^: POWER");
System.out.println("$: ROUND OFF");
System.out.println("!: FACTORIAL");
System.out.println(" ");
System.out.println("ENTER CHOICE");
choice = in.next().charAt(0);
switch (choice) {
case '+':
System.out.println("ENTER 2 NUMBERS, USER");
double a = in.nextDouble();
double b = in.nextDouble();
System.out.println("SUM = " + (a + b));
break;
case '-':
System.out.println("ENTER 2 NUMBERS, USER");
double c = in.nextDouble();
double d = in.nextDouble();
System.out.println("SUBTRACTING " + d + " FROM " + c + " ... DIFFERENCE = " + (c - d));
break;
case '*':
System.out.println("ENTER 2 NUMBERS, USER");
double e = in.nextDouble();
double f = in.nextDouble();
System.out.println("PRODUCT = " + (e * f));
break;
case '/':
System.out.println("ENTER 2 NUMBERS, USER");
double g = in.nextDouble();
double h = in.nextDouble();
System.out.println("DIVIDING " + g + " BY " + h + " = " + (g / h));
break;
case '#':
System.out.println("ENTER NO. FOR SQAURE ROOT:");
double sqrt = in.nextDouble();
System.out.println("SQUARE ROOT OF " + sqrt + " = " + Math.sqrt(sqrt));
break;
case '^':
System.out.println("ENTER BASE, USER");
double base = in.nextDouble();
System.out.println("ENTER POWER, USER");
double power = in.nextDouble();
System.out.println(base + " RAISED TO POWER " + power + " = " + Math.pow(base, power));
break;
case '$':
System.out.println("ENTER DECIMAL VALUES TO ROUND OFF");
double deci = in.nextDouble();
System.out.println("THE NEAREST ROUND OFF = " + Math.round(deci));
break;
case '!':
System.out.println("ENTER A NO. FOR FACTORIAL:");
int fact = in.nextInt();
int factorial = 1;
for (int i = fact; i >= 1; i--)
factorial = factorial * i;
System.out.println(fact + "! = " + factorial);
break;
default:
System.out.println("WRONG CHOICE USER");
}
System.out.println("Want to calculate more?Y/N");
loop = in.next().charAt(0) == 'Y';
}
}
}

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