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
}
}
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'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';
}
}
}
So this is my code for a simple calculator. It works for the most part, and I'm trying to create a loop at the end of the operation to allow a user the chance to choose to do another operation or exit. So far I've tried adding a nested if loop but I keep getting an error. Any help would be helpful. I'm fairly new.
import java.util.Scanner;
public class SimpleCalculator {
public static void main(String[] args) {
// Introduction to Calculator providing instructions to user
Scanner input = new Scanner(System.in);
int num1, num2, ans, Y, N;
System.out.println("Welcome to Simple Calculator: Please enter \n" +
"which mathimatical operation you would like to \n "
+ "accomplish by imputing 1-addition, 2-subtraction \n"
+ "3-multiplication, 4-division, 5-modulo");
int Operation = input.nextInt();
//Operation sequence for user to input which operation they would like to accomplish
if (Operation == 1) {
System.out.println("You have Choosen Addition");
System.out.print("Enter your First number: ");
num1 = (int) input.nextDouble();
System.out.print("Enter your second number: ");
num2 = (int) input.nextDouble();
ans = num1 + num2;
System.out.print("Answer is: " + ans);
/*
* Right here in the following I want to put something in to make this loop
* so the user can make multiple calculation.
* So far nothing has worked.
*/
System.out.println("Would you like to do another calculation?\n " +
"Enter Y for Yes or N to Exit");
}else if (Operation == 2){
System.out.println("You have Choosen Subtraction");
System.out.print("Enter your First number: ");
num1 = (int) input.nextDouble();
System.out.print("Enter your second number: ");
num2 = (int) input.nextDouble();
ans = num1 - num2;
System.out.print("Answer is: " + ans);
}else if (Operation == 3){
System.out.println("You have Choosen Multiplication");
System.out.print("Enter your First number: ");
num1 = (int) input.nextDouble();
System.out.print("Enter your second number: ");
num2 = (int) input.nextDouble();
ans = num1 * num2;
System.out.print("Answer is: " + ans);
}else if (Operation == 4){
System.out.println("You have Choosen Division");
System.out.print("Enter your First number: ");
num1 = (int) input.nextDouble();
System.out.print("Enter your second number: ");
num2 = (int) input.nextDouble();
ans = num1 / num2;
System.out.print("Answer is: " + ans);
}else if (Operation == 5){
System.out.println("You have Choosen Modulo");
System.out.print("Enter your First number: ");
num1 = (int) input.nextDouble();
System.out.print("Enter your second number: ");
num2 = (int) input.nextDouble();
ans = num1 % num2;
System.out.print("Answer is: " + ans);
}else{
System.out.print("Invalid Operation, please try again.");
}
}
}
You're on the right track here. I would suggest using a do-while loop. So encase the entire part beginning with if (Operation == 1) { all the way down to your final else statement like this:
do {
/*
if (Operation == 1) {
...
...
...
else {
...
}
*/
System.out.print("Would you like to do another calculation? [Y/n] ");
} while (input.nextLine().toUpperCase().charAt(0) == 'Y');
I would put the entire thing in a while loop and at the end ask if they want to continue
yes - it goes back through the loop
no - you have it break out of the loop
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;
}
}
}}