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
Related
Somehow I got operator looping till I get correct input. When i try to put num1 or num2 in "if" statement, It says that I cannot convert "int" to "boolean". Please help
public class main {
public static void main(String[] args) {
int num1;
int num2;
String operator;
Scanner scan = new Scanner(System.in);
System.out.print("tell me first number: ");
num1 = scan.nextInt(); //<--input only numbers, loop if not
System.out.print("tell me second number: ");
num2 = scan.nextInt(); //<--input only numbers, loop if not
//////////////////operator////////////////////////
System.out.print("tell me operator: ");
operator = scan.next();
while(true) {
if(operator.equals("+")) {
System.out.println("answer is: " +(num1 + num2));
break;
}
else if(operator.equals("-")) {
System.out.println("answer is: " +(num1 - num2));
break;
}
else if(operator.equals("*")) {
System.out.println("answer is: " +(num1 * num2));
break;
}
else if(operator.equals("/")) {
System.out.println("answer is: " +(num1 / num2));
break;
}
else {
System.out.print("wrong input! try again!: ");
operator = scan.next();
}
}
}
}
Try this.
System.out.print("tell me first number: ");
while (!scan.hasNextInt()) scan.next();
num1 = scan.nextInt();
System.out.print("tell me second number: ");
while (!scan.hasNextInt()) scan.next();
num2 = scan.nextInt();
System.out.print("tell me first number: ");
while (!scan.hasNextInt()) scan.next();
num1 = scan.nextInt();
System.out.print("tell me second number: ");
while (!scan.hasNextInt()) scan.next();
num2 = scan.nextInt();
With this, wrong answer was looping till i got correct input, but I could not get it to print me "Wrong Input! Try again!: " with wrong input without starting to loop infinitely, so i tried to edit and came up with this.
//////////////////first number////////////////////
System.out.print("tell me first number: ");
while(!scan.hasNextInt()) {
System.out.print("Wrong Input! Try again!: "); scan.next();
if(scan.hasNextInt() == true) {
}
}
num1 = scan.nextInt();
//////////////////second number///////////////////
System.out.print("tell me second number: ");
while(!scan.hasNextInt()) {
System.out.print("Wrong input! Try again!: "); scan.next();
if(scan.hasNextInt() == true) {
}
}
num2 = scan.nextInt();
Somehow it helped lol.
Thanks #英語は苦手 for help.
The goal is if the user puts an invalid option in three times, the program will tell the user to try again later and end the program. The code I have is below, I hope this makes sense, I am sorry if it doesn't. If you have any questions please let me know. I've also never asked a question here before so it may not be uploaded correctly.
public static void main(String[] args) {
int num1 = 0, num2 = 0, total = 0, option = 0, ex; // Creates integer variables
do {
Scanner sc = new Scanner(System.in);
System.out.println("\tBasic Math Calculator");// Title
System.out.println("\t---------------------");
System.out.println("\tEnter your choice from the following menu:");
System.out.println("\t------------------------------------------");
System.out.println("1.\tAddition");// All the menu options
System.out.println("2.\tSubtraction");
System.out.println("3.\tMultiplication");
System.out.println("4.\tDivision");
System.out.println("5.\tGenerate Random number");
System.out.println("6.\tQuit");
boolean valid;
do {
valid = true;
try {
option = Integer.parseInt(sc.nextLine());// Stores the users answers
if (option < 1 || option > 6) {
System.out.println("Invalid input. Please try again.");
valid = false;
}
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please try again.");
valid = false;
}
} while (!valid);
switch (option) {// The math and titles for every option
case 1:
System.out.println("You chose to add two numbers: ");
System.out.println("Enter your first number:");
num1 = sc.nextInt();
System.out.println("Enter your second number:");
num2 = sc.nextInt();
total = num1 + num2;
System.out.println("The two numbers you chose added together is " + total);
break;
case 2:
System.out.println("You chose to subtract two numbers: ");
System.out.println("Enter your first number:");
num1 = sc.nextInt();
System.out.println("Enter your second number:");
num2 = sc.nextInt();
total = num1 - num2;
System.out.println("The two numbers you chose subtracted together is " + total);
break;
case 3:
System.out.println("You chose to multiply two numbers: ");
System.out.println("Enter your first number:");
num1 = sc.nextInt();
System.out.println("Enter your second number:");
num2 = sc.nextInt();
total = num1 * num2;
System.out.println("The two numbers you chose multiplied together is " + total);
break;
case 4:
System.out.println("You chose to divide two numbers: ");
System.out.println("Enter your first number:");
num1 = sc.nextInt();
System.out.println("Enter your second number:");
num2 = sc.nextInt();
total = num1 / num2;
if (num2 == 0) {
System.out.println("You can't divide by 0");
} else {
System.out.println("The two numbers you chose divided together is " + total + "with a quotient of "
+ (num1 % num2));
}
break;
case 5:
System.out.println("You chose to get two random numbers: ");
System.out.println("Enter your lower limit:");
num1 = sc.nextInt();
System.out.println("Enter your upper limit:");
num2 = sc.nextInt();
total = num1 + num2;
Random rand = new Random();
int rand_int1 = rand.nextInt(num1 + num2);
System.out.println("The random intigers is: " + rand_int1);
break;
case 6:// If the user wants to quit
ex = 2;
break;
default:// Tells their option was incorrect
System.out.println("Invalid choice, choice " + option + " was not an option");
}
System.out.println("Do you want to continue?1.Yes 2.No");// Asks the user if they want to proceed
ex = sc.nextInt(); // A thank you message for the user for running the program
} while (ex == 1);
System.out.println("-----------------------------------------");
System.out.println("Thank you for using the basic calculator!");
}
You can do so by creating a nested loop before the start if switch statement:
//...
System.out.println("6.\tQuit");
boolean valid;
do {
valid = true;
try {
option = Integer.parseInt(sc.nextLine());// Stores the users answers
if (option < 1 || option > 6) {
System.out.println("Invalid input. Please try again.");
valid = false;
}
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please try again.");
valid = false;
}
} while (!valid);
switch (option) {// The math and titles for every option
//...
A sample run after this change:
Basic Math Calculator
---------------------
Enter your choice from the following menu:
------------------------------------------
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Generate Random number
6. Quit
a
Invalid input. Please try again.
9
Invalid input. Please try again.
4
You chose to divide two numbers:
Enter your first number:
Check the full code at ideone.
You don't have to use the valid and do-while for checking times of invalid input
If you want to quit the program after 3 invalid option entered by user , you have to increment the count of ex and change the condition at while loop.
Initialize ex=1
Change case 6 and default as below
case 6:// If the user wants to quit
System.exit(0);
break;
default:
ex = ex+1;
break;
and
while condition as below
while (ex <4); //
Following is the full code
public static void main(String[] args) {
int num1 = 0, num2 = 0, total = 0, ex= 1; // Creates integer variables
do {
Scanner sc = new Scanner(System.in);
System.out.println("\tBasic Math Calculator");// Title
System.out.println("\t---------------------");
System.out.println("\tEnter your choice from the following menu:");
System.out.println("\t------------------------------------------");
System.out.println("1.\tAddition");// All the menu options
System.out.println("2.\tSubtraction");
System.out.println("3.\tMultiplication");
System.out.println("4.\tDivision");
System.out.println("5.\tGenerate Random number");
System.out.println("6.\tQuit");
switch (option) {// The math and titles for every option
case 1:
System.out.println("You chose to add two numbers: ");
System.out.println("Enter your first number:");
num1 = sc.nextInt();
System.out.println("Enter your second number:");
num2 = sc.nextInt();
total = num1 + num2;
System.out.println("The two numbers you chose added together is " + total);
break;
case 2:
System.out.println("You chose to subtract two numbers: ");
System.out.println("Enter your first number:");
num1 = sc.nextInt();
System.out.println("Enter your second number:");
num2 = sc.nextInt();
total = num1 - num2;
System.out.println("The two numbers you chose subtracted together is " + total);
break;
case 3:
System.out.println("You chose to multiply two numbers: ");
System.out.println("Enter your first number:");
num1 = sc.nextInt();
System.out.println("Enter your second number:");
num2 = sc.nextInt();
total = num1 * num2;
System.out.println("The two numbers you chose multiplied together is " + total);
break;
case 4:
System.out.println("You chose to divide two numbers: ");
System.out.println("Enter your first number:");
num1 = sc.nextInt();
System.out.println("Enter your second number:");
num2 = sc.nextInt();
total = num1 / num2;
if (num2 == 0) {
System.out.println("You can't divide by 0");
} else {
System.out.println("The two numbers you chose divided together is " + total + "with a quotient of "
+ (num1 % num2));
}
break;
case 5:
System.out.println("You chose to get two random numbers: ");
System.out.println("Enter your lower limit:");
num1 = sc.nextInt();
System.out.println("Enter your upper limit:");
num2 = sc.nextInt();
total = num1 + num2;
Random rand = new Random();
int rand_int1 = rand.nextInt(num1 + num2);
System.out.println("The random intigers is: " + rand_int1);
break;
case 6:// If the user wants to quit
System.out.println("Thank you for using the basic calculator!");
System.exit(0);
break;
default:// Tells their option was incorrect
ex=ex+1;
System.out.println("Invalid choice, choice " + option + " was not an option");
}
System.out.println("Do you want to continue?1.Yes 2.No");// Asks the user if they want to proceed
//ex = sc.nextInt(); // A thank you message for the user for running the program
} while (ex<4);
System.out.println("-----------------------------------------");
System.out.println("Thank you for using the basic calculator!");
}
Edited
Below is the sample output
Basic Math Calculator
---------------------
Enter your choice from the following menu:
------------------------------------------
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Generate Random number
6. Quit
7
Invalid choice, choice 7 was not an option
Please try again
Basic Math Calculator
---------------------
Enter your choice from the following menu:
------------------------------------------
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Generate Random number
6. Quit
7
Invalid choice, choice 7 was not an option
Please try again
Basic Math Calculator
---------------------
Enter your choice from the following menu:
------------------------------------------
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Generate Random number
6. Quit
7
Invalid choice, choice 7 was not an option
Please try again
-----------------------------------------
Thank you for using the basic calculator!
I am trying to create a Java program that reads a double value from the user, Printing the difference between these two numbers so that the difference is always positive. I need to display an Error message if anything other than a number is entered. Please help, thank you !!
When I run the program and enter the second double value nothing happens. I have also tried adding try and catch but I get errors saying num1 cannot be resolved to a variable :(
import java.util.Scanner;
public class Positive {
public static void main(String[] args) {
//Reads input
Scanner sc = new Scanner(System.in);
System.out.println ("Please enter a double vaule: ");
double num1 = Math.abs(sc.nextDouble());
System.out.println("Please enter a second double vaule: " );
double num2 = Math.abs(sc.nextDouble());
double total = 0;
double total2 = 0;
if (sc.hasNextDouble()) {
num1 = sc.nextDouble();
if (num1>num2) {
total = ((num1 - num2));
System.out.println("The difference is " + total);
}
if ((num1 < num2)); {
total2 = ((num2 - num1));
System.out.println("The difference is "+ total2);
}
}else {
System.out.println("Wrong vaule entered");
}
}
}
You have the right idea. You just need to remove the semicolon (;) after the last if and properly nest your conditions:
if (sc.hasNextDouble()) {
num1 = sc.nextDouble();
if (num1 > num2) {
total = (num1 - num2);
System.out.println("The difference is " + total);
}
else if (num1 < num2) {
total2 = (num2 - num1);
System.out.println("The difference is "+ total2);
}
} else {
System.out.println("Wrong vaule entered");
}
Try running your code and when you enter your first double, type in something random like "abc". What happens? In your console it should display an error named java.util.InputMismatchException. You can use a try catch block like so:
try {
//tries to get num1 and num2
double num1 = Math.abs(sc.nextDouble());
double num2 = Math.abs(sc.nextDouble());
} catch (java.util.InputMismatchException i){
//will only go here if either num1 or num2 isn't a double
System.out.println("error");
}
Basically, the code will try to get num1 and num2. However if you enter a non-double, it'll "catch" the java.util.InputMismatchException and go to the catchblock
I might've misinterpreted your question, but if you want to find the absolute value of the difference between num1 and num2, all you have to do is:
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
System.out.println("Please enter a double value: ");
double num1 = sc.nextDouble();
System.out.println("Please enter a double value: ");
double num2 = sc.nextDouble();
System.out.println("The difference is: " + Math.abs(num1 - num2));
} catch (java.util.InputMismatchException i) {
System.out.println("error");
}
}
}
To show error message until the user enters a double value I used a while loop for each value (num1 and num2).
If user enters a wrong value "Wrong vaule entered, Please enter again: " message will show and waits for the next input sc.next();
If user enters a double value check will be false and exits while loop
import java.util.Scanner;
public class Positive {
public static void main(String[] args) {
// Reads input
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a double vaule: ");
double num1 = 0;
double num2 = 0;
double total = 0;
double total2 = 0;
boolean check = true;
while (check) {
if (sc.hasNextDouble()) {
num1 = Math.abs(sc.nextDouble());
check = false;
} else {
System.out.println("Wrong vaule entered, Please enter again: ");
sc.next();
}
}
check = true; // that's for second control
System.out.println("Please enter a second double vaule: ");
while (check) {
if (sc.hasNextDouble()) {
num2 = Math.abs(sc.nextDouble());
check = false;
} else {
System.out.println("Wrong vaule entered, Please enter again: ");
sc.next();
}
}
if (num1 > num2) {
total = ((num1 - num2));
System.out.println("The difference is " + total);
} else if ((num1 < num2)) {
total2 = ((num2 - num1));
System.out.println("The difference is " + total2);
}
}
}
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
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
}
}