I have a little problem with this do while loop; when I run the program it is working, at least partially, what I mean is first you need to make a choice for convertion from C to F or from F to C and after you enter the values the program stops what I want to do is to keep asking for values until you enter 3. I tried to do it with a do while loop but it is not working so if someone has any ideas I would be grateful. Here is the code:
import java.util.Scanner;
public class DegreesInConversion2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Conversion table: ");
int choice = input.nextInt();
do {
System.out.println();
System.out.println("1 for convertion from Celsious to Fahrenhait: ");
System.out.println("2 for convertion froom Fahrenheit to Celsious: ");
System.out.println("3 for Exit: ");
System.out.println();
System.out.println("Make a choice between 1 - 3 ");
choice = input.nextInt();
System.out.println();
switch (choice) {
case 1:
System.out.println("Enter temperature in Celsious: ");
double cel = input.nextDouble();
if (cel < -273.15) {
System.out.println("Invalid values, please enter temperature greater than -273.15 in C:");
} else {
System.out.println("You enetered " + cel + "C " + "which is " + (((cel * 9) / 5) + 32) + "F");
}
break;
case 2:
System.out.println("Enter temperature in Farhneit: ");
double far = input.nextDouble();
if (far < -459.67) {
System.out.println("Invalid values, please enter temperature greater than -459.67 in F:");
} else {
System.out.println("You enetered " + far + "F " + "which is " + (((far - 32) * 5) / 9) + "C");
}
break;
case 3:
System.out.println("Goodbyu have a nice day: ");
break;
default:
System.out.println("Invalid entry: Please enter a number between 1-3:");
}
} while (choice != 3);
}
}
Like in your other question, here you're scanning for input before prompting the user for input.
You need to remove the second line below:
System.out.println("Conversion table: ");
int choice = input.nextInt();
do
With your code as is, it outputs
Conversion table:
and then blocks waiting for input. Whereas you want it instead to continue into the while loop and output
1 for convertion from Celsious to Fahrenhait:
2 for convertion froom Fahrenheit to Celsious:
3 for Exit:
Make a choice between 1 - 3
before blocking to scan for input.
As is, if you enter any number at the first block, your program enters the loop and behaves as you wanted. So you're nearly there!
The code does work. the problem is most likely the
int choice = input.nextInt();
before the do
Remove this, and change
choice = input.nextInt();
to
int choice = input.nextInt();
Besides the fact that you have: int choice = input.nextInt(); outside of the loop which is unnecessarily getting input before showing the menu, it seems to all work relatively fine. You can just declare int choice inside the loop where you have choice = input.nextInt(); (ie. just change that to intchoice = input.nextInt();).
I tested your code, and it works fine if you change the line int choice = input.nextInt(); (just before your do{} while() block) into int choice;.
As others have already mentioned, you should not read input before your do{} while() block, since the question has not been asked yet.
you forgot the break; after your default case
Related
I'm working on a project that calculates the value of a bank account based on starting balance(b), interest rate(IR), and quarters to display. My entire code works perfectly, but the very last portion is to make sure the variables like interest rate are within the confines of the boundaries my professor gave me. I do need to display an error message if the user enters a value outside the boundaries and ask for the value again.
For example, the number of quarters to display needs to be greater than zero, and less or equal to 10.
As you can see, pretty much all of my program is in a do-while loop. I know I can have nested loops, but what would I be able to put in my do-while loop that would work in this situation? An if-else statement? Try and catch block? Another while loop?
If I used a try-catch, then could anyone give me an example of how I could do that? Thank you very much for your time, and all help is appreciated! The below is my code for reference.
import java.util.Scanner;
public class InterestCalculator
{
public static void main(String[] args)
{
Scanner scannerObject = new Scanner(System.in);
Scanner input = new Scanner(System.in);
int quartersDisplayed;
double b, IR;
do
{
Scanner keyboard=new Scanner(System.in);
System.out.println("Enter the numbers of quarters you wish to display that is greater than zero and less or equal to 10: ");
quartersDisplayed = keyboard.nextInt();
System.out.println("Next enter the starting balance. ");
System.out.println("This input must be greater than zero: ");
b = keyboard.nextDouble();
System.out.println("Finally, enter the interest rate ");
System.out.println("which must be greater than zero and less than or equal to twenty percent: ");
IR = keyboard.nextDouble();
System.out.println("You have entered the following amount of quarters: " + quartersDisplayed);
System.out.println("You also entered the starting balance of: " + b);
System.out.println("Finally, you entered the following of interest rate: " + IR);
System.out.println("If this information is not correct, please exit the program and enter the correct information.");
double quarterlyEndingBalance = b + (b * IR/100 * .25);
System.out.println("Your ending balance for your quarters is " + quarterlyEndingBalance);
System.out.println("Do you want to continue?");
String yes=keyboard.next("yes");
if (yes.equals(yes))
continue;
else
break;
}
while(true);
}
}
So here's some code to answer your questions and help get you started. However, there are problems with your logic that do not pertain to your question which I will address afterward.
Note: I have added comments to your code. Most of them start with "EDIT:" so that you can tell what I changed. I didn't use this prefix in all cases because some of it is new code and it's obviously my comment
import java.util.Scanner;
public class InterestCalculator {
public static void main(String[] args) {
// EDIT: you already have a scanner defined below with a more meaningful name so I removed this one
// Scanner scannerObject = new Scanner(System.in);
Scanner input = new Scanner(System.in);
//EDIT: defining userResponse outside the loop so we can use it everywhere inside
String userResponse = null;
do {
//EDIT: moved the variables inside the loop so that they are reset each time we start over.
//EDIT: initialize your variable to a value that is invalid so that you can tell if it has been set or not.
int quartersDisplayed = -1;
//EDIT: gave your variables more meaningful names that conform to java standards
double startingBalance = -1, interestRate = -1;
//EDIT: you don't need a second Scanner, just use the one you already have.
// Scanner keyboard = new Scanner(System.in);
do{
System.out.println("Enter the numbers of quarters you wish to display that is greater than zero and less or equal to 10: ");
userResponse = input.next();
try{
quartersDisplayed = Integer.parseInt(userResponse);
}catch(NumberFormatException e){
//nothing to do here, error message handled below.
}
if(quartersDisplayed <= 0 || quartersDisplayed > 10){
System.out.println("Sorry, that value is not valid.");
}else{
break;
}
}while(true);
do{
System.out.println("Enter the starting balance (must be greater than zero): ");
userResponse = input.next();
try{
startingBalance = Double.parseDouble(userResponse);
}catch(NumberFormatException e){
//nothing to do here, error message handled below.
}
if(startingBalance <= 0){
System.out.println("Sorry, that value is not valid.");
}else{
break;
}
}while(true);
do{
System.out.println("Enter the interest rate (greater than zero less than twenty percent): ");
userResponse = input.next();
try{
interestRate = Double.parseDouble(userResponse);
}catch(NumberFormatException e){
//nothing to do here, error message handled below.
}
//Note: I assume twenty percent is represented as 20.0 here
if(interestRate <= 0 || interestRate > 20){
System.out.println("Sorry, that value is not valid.");
}else{
break;
}
}while(true);
System.out.println("You have entered the following amount of quarters: "
+ quartersDisplayed);
System.out.println("You also entered the starting balance of: " + startingBalance);
System.out.println("Finally, you entered the following of interest rate: "
+ interestRate);
System.out.println("If this information is not correct, please exit the program and enter the correct information.");
double quarterlyEndingBalance = startingBalance + (startingBalance * interestRate / 100 * .25);
System.out.println("Your ending balance for your quarters is "
+ quarterlyEndingBalance);
System.out.println("Do you want to continue?");
//EDIT: modified your variable name to be more meaningful since the user's response doesn't have to "yes" necessarily
userResponse = input.next();
// EDIT: modified the logic here to compare with "yes" or "y" case insensitively.
// if (userResponse.equals(userResponse))
if("y".equalsIgnoreCase(userResponse) || "yes".equalsIgnoreCase(userResponse))
continue;
else
break;
} while (true);
Now to address other issues - your interest calculation doesn't seem correct to me. Your formula does not make use of the quartersDisplayed variable at all. I assume you're compounding the interest quarterly so you will definitely need to make use of this when calculating your results.
This may be beyond the scope of your project, but you should not use double or float data types to represent money. There is a stackoverflow question about this topic that has good information.
Possible improvements - since you're asking the user for two values of type double you could create a method to ask for a double value and call it twice instead of repeating the code. This is a better approach because it helps reduce the chance of mistakes and makes testing and maintenance easier.
You can do something like this in your do/while loop:
do
{
Scanner keyboard = new Scanner(System.in);
do
{
System.out.println("Enter the numbers of quarters you wish to display that is greater than zero and less or equal to 10: ");
quartersDisplayed = keyboard.nextInt();
}
while (quartersDisplayed < 1 || quartersDisplayed > 10);
System.out.println("Next enter the starting balance. ");
do
{
System.out.println("This input must be greater than zero: ");
b = keyboard.nextDouble();
}
while (b < 1);
// rest of code ...
}
With the Scanner#hasNextInt (and the equivalent for double), you can avoid having exceptions thrown, and thus don't need try-catch clauses. I think in general if you can avoid try-catch, it's good, because they are clumsy - but I might be wrong.
However, my approach is like this. Inside your outer do-while, have three other do-while-loops to get the three values. The reason is that you want to keep looping until you get a correct value. The explanation of why keyboard.nextLine() is important is covered here.
I didn't include all of your code, only the part in question. Here's my take on it:
import java.util.Scanner;
public class InterestCalculator {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int quartersDisplayed = -1;
double b = -1.0;
double IR = -1.0;
do {
do {
System.out.println("Enter the number of quarters.");
if(keyboard.hasNextInt()) {
quartersDisplayed = keyboard.nextInt();
keyboard.nextLine(); //important
} else {
System.out.println("You need to enter an integer.");
continue;
}
} while(quartersDisplayed < 1 || quartersDisplayed > 10);
do {
System.out.println("Enter the starting balance.");
if(keyboard.hasNextDouble()) {
b = keyboard.nextDouble();
keyboard.nextLine();
} else {
System.out.println("You must enter a number.");
continue;
}
} while(b <= 0);
do {
System.out.println("Enter the interest rate.");
if(keyboard.hasNextDouble()) {
IR = keyboard.nextDouble();
keyboard.nextLine();
} else {
System.out.println("You must enter a number.");
continue;
}
} while(IR <= 0 || IR > 20.0);
//... rest of code
} while(true);
}
}
I have a prompt to "Write a program that performs the following operations: +, -, *, /, % (as defined by Java). Your program should first read the first number, then the operation, and then the second number. Both numbers are integers. If, for the operation, the user entered one of the symbols shown above, your program should perform the corresponding operation and compute the result. After that it should print the operation and the result. If the operation is not recognized, the program should display a message about it. You do not need to do any input validation for the integers."
An example output I'm given is:
Enter the first number: 6
Enter the operation: +
Enter the second number: 10
6 + 10 = 16
How can I get started on this? I'm super confused and really new to java! Any help is greatly appreciated.
You generally first want to start reading input from STDIN:
Scanner in = new Scanner(System.in);
Then, I would read all parameters and afterwards perform the computation:
System.out.print("Enter the first number: ");
int left = Integer.parseInt(in.nextLine());
System.out.print("Enter the operation: ");
String operation = in.nextLine();
System.out.print("Enter the second number: ");
int right = Integer.parseInt(in.nextLine());
Now that all input is collected, you can start acting.
int result;
switch(operation)
{
case "+": result = left + right; break;
case "-": result = left - right; break;
case "*": result = left * right; break;
case "/": result = left / right; break;
case "%": result = left % right; break;
default: throw new IllegalArgumentException("unsupported operation " + operation);
}
System.out.println(left + " " + operation + " " + right + " = " + result);
Sounds like we are doing your homework! :) Make sure you learn these things or else it will eventually bite you. You can only delay the inevitable. With that "fatherly advice", here ya go.
First, you need to be able to read input from the console so that you can get the input numbers and operation. Of course, there are whole answers on this already. One link:
Java: How to get input from System.console()
Once you have the input, then you can work with it.
You will need to look at the items entered. They say you don't need to validate the numbers but you need to validate the operation. So look at the operation String variable after you got it from the console and see if it is "equalsIgnoreCase" (or just equals since these symbols don't have uppercase) to each one of the accepted operations. If it isn't equal to any of them then you should print out a message as it says. (Again with System.out.println).
You can then go into some if conditions and actually do the math if the operation equals one of the items. For example:
if(inputOperation.equalsIgnoreCase("+")){
double solution = inputInt1 + inputInt2;
//Need to do for all other operations. I didn't do the WHOLE thing for you.
}else if(NEED_TO_FILL_IN_THIS){
//Need to fill in the operation.
//You will need to have more else if conditions below for every operation
}else{
System.out.println("Your operation of '"+inputOperation+"' did not match any accepted inputs. Accepted input operations are '+','-','%','/' and '*'. Please try again.");
}
System.out.println("Your answer to the equation '"+inputInt1+" "+inputOperation+" "+inputInt2+"' is the following:"+solution);
That should get you started. Let me know if you still need further direction.
I hope that helps!
And to end with some fatherly advice: Again, it sounds like you are doing homework. This is all pretty well documented if you just know how to google. "Java get input from console". Or "Java check if String is equal to another string". Learning how to fish is so much more important than getting the fish. I suggest you do some catchup because if this is your homework and you are unsure then it seems like you are a bit behind. I don't mean to be rude. I am just trying to help you longer term.
Enter the first number: 6
Enter the operation: +
Enter the second number: 10
6 + 10 = 16
Scanner f=new Scanner(System.in)
System.out.print("Enter the first number: ")
int firstNum=f.nextInt();
System.out.println();
System.out.print("Enter the operation: ")
String Op=f.nextLine();
System.out.println();
System.out.print("Enter the Second number: ")
int secNum=f.nextInt();
System.out.println();
int answ=0;
if(Op.equals("+"){
answ=firstNum+secNum;
}else if(.......){
}
hope it helps :)
To read the integers, use a Scanner
public static void main(String [] args)
{
Scanner stdin = new Scanner(System.in);
System.out.println("Enter the first number: ");
int firstNum = stdin.nextInt(); //first number
System.out.println("Enter the operation: ");
String operation = stdin.next(); //operation
System.out.println("Enter the second number: ");
int secondNum = stdin.nextInt(); //second number
doOperation(firstNum, secondNum, operation);
}
public static void doOperation(int firstNum, int secondNum, String operation)
{
if(operation.equals("+")
{
int result = firstNum + secondNum;
}
else if(...)
{
//etc
}
System.out.println(firstNum + " " + operation + " " + secondNum + " = " + result);
}
Here is My Solution
package com.company;
import com.sun.org.apache.regexp.internal.RE;
import java.util.Scanner;
public class Main {
private static Scanner scanner=new Scanner(System.in);
public static void main(String[] args) {
// write your code here
int First,Second,Resualt;
char operation;
System.out.println("Enter the first number: ");
First=scanner.nextInt();
System.out.println("Enter the operation:");
operation=scanner.next().charAt(0);
System.out.println("Enter the second number :");
Second=scanner.nextInt();
if (operation=='+'){
Resualt=First+Second;
System.out.println(First+" "+"+ "+Second+" = "+Resualt);
}
else if (operation=='-'){
Resualt=First-Second;
System.out.println(First+" "+"- "+Second+" = "+Resualt);
}
else if (operation=='*'){
Resualt=First*Second;
System.out.println(First+" "+"* "+Second+" = "+Resualt);
}
else if (operation=='%'){
Resualt=First%Second;
System.out.println(First+" "+"% "+Second+" = "+Resualt);
}
else {
System.out.println("Error");
}
}
}
Good Luck!!
I am trying my hand a few basic do-while codes, and am running into a couple of problems.
I want the code to ask the user to input 1 of 3 options (choosing which group they would like to add a number to, or to exit and total), give an error if they input an irrelevant option, and then total all ints at the end for each group.
public static void main(String[] args) {
String answer = "default";
int grp1 = 0;
int grp2 = 0;
int input1 = 0;
int input2 = 0;
do{
System.out.println("Make a selection:\n");
System.out.println("A: Enter a number for Group 1.");
System.out.println("B: Enter a number for Group 2.");
System.out.println("X: Exit and total the numbers for each group.\n");
System.out.println("Select your option: ");
answer = keyboard.next();
if (answer.equalsIgnoreCase("A")){
System.out.println("Enter int: ");
input1 = keyboard.nextInt(); // add an int to grp1
}
else if (answer.equalsIgnoreCase("B")){
System.out.println("Enter int: ");
input2 = keyboard.nextInt(); // add an int to grp2
}
else if (answer.equalsIgnoreCase("X")){
} // exit and total
else {
System.out.println("Invalid option - Try again.");
} // Invalid input - restart
}
while (answer.equals("A") || answer.equals("B"));
grp1 += input1;
grp2 += input2;
keyboard.close();
System.out.println("Group 1's total is: + grp1);
System.out.println("Group 2's total is: + grp2);
}
I need the to add a qualifier for if the user does not input a valid option, I tried using else:
else {
System.out.println("Invalid option - Try again.")
}
but this just skips to printing the totals, and does not ask the user for another input. How would I best achieve this?
Also,
grp1 += input1;
grp2 += input2;
Only counts the lasted entered int, is there a way to have it add all the entered ints?
Any help would be greatly appreciated, even outside of the questions I asked.
I think you have two confusions.
1) The "while" line in your code applies to the "do" block above it. That means that based on where the grp1 += and grp2 += lines are, they will only ever be run once. I suggest moving those calls to the end of the loop. You could move each line inside the relevant if block so that the code is run every time the user successfully enters a number after A or B.
2) The while condition is asking if the user entered "A" or "B". It's saying if they did, continue looping by going back to "do". If they entered literally anything else (any invalid answer), it will stop and run the code after the "while" line. I think what you really want is while (!answer.equals("X")), which will continue the loop until the user correctly enters an "X" character.
You'll also want to move those grp += lines up a bit.
Just change the condition inside while And also shift the totalling logic
do{
System.out.println("Make a selection:\n");
System.out.println("A: Enter a number for Group 1.");
System.out.println("B: Enter a number for Group 2.");
System.out.println("X: Exit and total the numbers for each group.\n");
System.out.println("Select your option: ");
answer = keyboard.next();
if (answer.equalsIgnoreCase("A")){
System.out.println("Enter int: ");
input1 = keyboard.nextInt(); // add an int to grp1
grp1 += input1;
}
else if (answer.equalsIgnoreCase("B")){
System.out.println("Enter int: ");
input2 = keyboard.nextInt(); // add an int to grp2
grp2 += input2;
}
else if (answer.equalsIgnoreCase("X")){
} // exit and total
else {
System.out.println("Invalid option - Try again.");
} // Invalid input - restart
}
while (!answer.equals("X"));
keyboard.close();
This will make your do while loop running i.e showing options to user until they wishes to exit. And also group total would be updated properly. I have updated answer based on answer by #Devin Howard
import java.util.Scanner;
public class Dice {
public static void main(String[] args) {
//I used 'print' instead of 'println' just to make it look a little cleaner in the console.
System.out.print("Input your first number: ");
Scanner sc1 = new Scanner(System.in);
double num1 = sc1.nextInt();
//I use doubles for my variables just in case the user wants to divide.
System.out.print("Input your second number: ");
Scanner sc2 = new Scanner(System.in);
double num2 = sc2.nextInt();
/* I used words rather than the actual symbols for my operators just to get practice using scanners for strings.
* Until now I'd solely been using them for int variables. And also due to the small detail that before programming,
* I had no idea what a modulo was and I felt that would be confusing to a random person.
*/
System.out.println("What would you like to do with these numbers?(Add, Subtract, Multiply, Divide, or Check Divisibility): ");
System.out.println("Simply type 'check' to check the divisibility of your two numbers.");
Scanner sc3 = new Scanner(System.in);
String str1 = sc3.nextLine().toUpperCase();
/* toUpperCase to prevent the user from creating an error by typing their in put in a 'unique' way.
*It took me several failures to finally look up toUpperCase.
*/
double num3;
switch(str1) {
case "ADD":
num3 = num1 + num2;
System.out.println("The sum is: " + num3);
break;
case "SUBTRACT":
num3 = num1 + num2;
System.out.println("The difference is: " + num3);
break;
case "MULTIPLY":
num3 = num1 * num2;
System.out.println("The product is: " + num3);
break;
case "DIVIDE":
num3 = num1 / num2;
System.out.println("The quotient is: " + num3);
break;
case "CHECK":
num3 = num1 % num2;
System.out.println("The remainder is: " + num3);
break;
default:
System.out.println("Invalid input. Please ensure that two numbers were entered and that you entered a valid math operation.");
break;
}//switch statement
}//main method
}//class
How would I get my code to run again if I wanted to maybe add another number to my answer? I'm just trying to get some practice in with my Java (I'm extremely green) and I apologize in advance if my question is too broad.
Consider the following small program
boolean quit = false;
while(!quit) {
System.out.print("Enter Something:");
Scanner sc1 = new Scanner(System.in);
String input = sc1.nextLine();
if(input.compareToIgnoreCase("quit") == 0) {
quit = true;
continue;
}
System.out.println("You entered " + input);
}
In this sample we keep asking them to enter something and print it out unless that input is "quit" in that case we use the continue statement to skip the rest of the loop and go back to the top of the while loop and re-evaluate the condition for another iteration. If you entered 'quit' this will evaluate to false and stop the loop and exit the program.
Heres a sample input/output from the program. Notice there is no "You entered quit", this is because the continue statement brought us back to the top of the while loop.
Enter Something:hello
You entered hello
Enter Something:quit
Now how can you adapt this to your program? Heres a small sample of how you can do one of your inputs
double num1 = 0;
String input1 = sc1.nextLine();
if(input1.compareToIgnoreCase("quit") == 0) {
// quit was entered, leave the loop
quit = true;
continue;
}
try {
num1 = Double.parseDouble(input1);
} catch(NumberFormatException e) {
// user entered something that isnt a number, quit the program for now
// you can change this to whatever behavior you like in the future
quit = true;
continue;
}
This will likely leave you with some validation questions like "I want to have my user try again if they input an invalid number" Those are all possible using this method and it leads you in the right direction.
Remember, main() is a callable method. Instead of using a while or for loop, you could just call it again at the end of the main method method.
// Put this at the end of your main method
System.out.print("Do you want to execute again? (yes/no)");
boolean repeat = sc1.nextLine().toUpperCase().equals("YES");
if (repeat) {
main(null); // You're not using any arguments in main()
}
On a separate note, you don't need all three of sc1, sc2, and sc3. They're basically the same. You could probably use sc1 everywhere and remove sc2 and sc3 completely.
// something like this then ask if to do another run if not set flag false
boolean flag = true;
while(flag)
{
System.out.print("Input your first number: ");
Scanner sc1 = new Scanner(System.in);
double num1 = sc1.nextInt();
You should put all your logic around a while loop which will grant to you to repeat your task until a condition is reached.
Maybe you can ask to the user to insert the string "EXIT" when he wants to exit from your program.
In your case I'll do something like this:
boolean exitFlag = false;
do {
// <put your logic here>
String answer = sc3.nextLine().toUpperCase();
if (answer.equals("EXIT")) {
exitFlag = true;
}
} while(!exitFlag);
I can't get this to work properly. It functions as it is supposed to, and does the math, but then it loops once, and ends. I need it to either loop until the users decides to end it, or only run once.
import java.util.Scanner;
public class java {
public static void main(String args[]) {
System.out.println("Welcome to the simple Calculator program");
System.out.println("Please type what type of math you would like to do: ");
System.out.println("1=Addition");
System.out.println("2=Subtraction");
System.out.println("3=Multiplication");
System.out.println("4=Division");
System.out.println("5=Sqrt");
Scanner input = new Scanner(System.in);
int math = input.nextInt();
if (math == 1) {
Scanner a = new Scanner(System.in);
int a1;
int a2;
int asum;
System.out.print("Please enter the first number: ");
a1 = a.nextInt();
System.out.print("Please enter the second number: ");
a2 = a.nextInt();
asum = a2 + a1;
System.out.print("The sum is: " + asum + "Thank You for using this program");
}
Scanner number = new Scanner(System.in);
int number1;
int number2;
int sum;
System.out.print("Enter first number: ");
number1 = number.nextInt();
System.out.print("Enter Second number: ");
number2 = number.nextInt();
sum = number1 + number2;
System.out.printf("Sum is %d\n", sum);
}
}
Use
do{
// do something.
} while(some condition);
And reapeat the same scanner to get input. You can also add one more option to your menu for repeating and evaluate that with while condition.
It is working as it should.
If you want it to loop as per some user input,you must use any looping construct like while.
Instead of if (math == 1) use
`while (math != exit)`
Make a new entry for exit like 0
Try using while loop. Give the user an option to quit the program.
import java.util.Scanner;
public class java
{
public static void main(String args[])
{
Scanner a = new Scanner(System.in);
System.out.println("Welcome to the simple Calculator program");
while(true)
{
System.out.println("Please type what type of math you would like to do: ");
System.out.println("1=Addition");
System.out.println("2=Subtraction");
System.out.println("3=Multiplication");
System.out.println("4=Division");
System.out.println("5=Sqrt");
System.out.println("6=Quit"); // added an option to quit the program
int math = a.nextInt();
if (math == 1)
{
int a1,a2,asum;
System.out.print("Please enter the first number: ");
a1 = a.nextInt();
System.out.print("Please enter the second number: ");
a2 = a.nextInt();
asum = a2 + a1;
System.out.println("The sum is: " + asum + "Thank You for using this program");
}
// Include actions for math = 2 to 5
if(math == 6)
{
System.out.println("Thank You for using this program");
System.exit(0);
}
}
}
}
The options are displayed again and again after each calculation until the user wants to exit the program by entering 6.
If you want the program to run only once, you should leave out the outer while loop. Everything else remains the same.
PS - You don't need to reopen Scanner again and again (at least not in this problem).
That is because you are only reading the input from the console once..you need to keep the console up with something like while(true) {} or monitor the console for an exit conditon like (" 0 = exit ") .
Also, I don''t think you will need to read two numbers again and again like you are doing right now.
1) You can use a do-while loop with a condition till which you wish to execute.
2) Use a switch case and perform the math operations inside the switch case with different operators. As of now you are trying to perform only addition. So you a switch case where you can perform all the operations.
3) In the switch case have an option which calls the exit(0) method. So that you can run the program until the user wish to exit.
4) By using a switch case you can make the user to choose his own option.
Your entire program is correct dude.
Just add
System.exit(0);
In every if(math==1) ,if(math==2)...before their statement ending.
like if(math==1)
{
...
System.exit(0);
}
You can fix your error...
Like me if your error is fixed. If not tell me the error