Update
The first time the user makes a choice such as "1" the menu is displayed again. The next time a selection is made the payment information begins to cycle. After the cycling is complete and the menu is displayed again, it works as it should. Also, the first two years are output instead of just the first when a selection begins to cycle, but then outputs one year at a time as intended.
//create scanner object for choosing a loan, then prompt for and accept input
Scanner choose = new Scanner(System.in);
String choice;
System.out.println("\nType 1, 2, or 3 and press enter to see the monthly payment information for the respective loan. To end the program type \"end\".");
choice = choose.next();
//cycle loan 1 payment information
//create scanner object to advance to the next year's payments
//loop for cycling payment information
//initialize loan principal to variable
while (!"end".equals(choice)) {
System.out.println("\nType 1, 2, or 3 and press enter to see the monthly payment information for the respective loan. To end the program type \"end\".");
choice = null;
choice = choose.next();
if ("1".equals(choice)) {
//calculation code
}
if (j < 6) {
System.out.println("Press enter to get the mortgage information for year " + (j + 2));
choice = choose.nextLine();
} else {
System.out.println("Congratulations, your mortgage has been paid off.");
}
}
choice = null;
}
if ("2".equals(choice)) {
//calculation code
}
if (j < 14) {
System.out.println("Press enter to get the mortgage information for year " + (j + 2));
choice = choose.nextLine();
} else {
System.out.println("Congratulations, your mortgage has been paid off.");
}
}
choice = null;
}
if ("3".equals(choice)) {
//calculation code
}
if (j < 29) {
System.out.println("Press enter to get the mortgage information for year " + (j + 2));
choice = next.nextLine();
} else {
System.out.println("Congratulations, your mortgage has been paid off.");
}
}
choice = null;
}
}
choose.close();
}
}
I can see three issues upfront:
You don't need two scanners for System.in stream. Remove this statement Scanner next = new Scanner(System.in); and use the choose instance.
If you close your input scanner as next.close();, it closes your input stream System.in as well and you may not be able read the stream again. Make sure you close the stream only when you are completely done with your program.
Use equals method to compare the condition in while as while(!"end".equals(choice)). Put the literal "end" as first argument will take care of the null value of choice.
EDIT:
Your modified code at high level:
Scanner choose = new Scanner(System.in);
String choice= null;
int j = 0;
while (!"end".equals(choice)) {
System.out.println("\nType 1, 2, or 3 and press enter to see the monthly payment information for the respective loan. To end the program type \"end\".");
choice = choose.nextLine();
if ("1".equals(choice)) {
//calculation code
if (j < 6) {
System.out.println("Press enter to get the mortgage information for year " + (j + 2));
choice = choose.nextLine();
} else {
System.out.println("Congratulations, your mortgage has been paid off.");
}
choice = null;
}
if ("2".equals(choice)) {
if (j < 14) {
System.out.println("Press enter to get the mortgage information for year " + (j + 2));
choice = choose.nextLine();
} else {
System.out.println("Congratulations, your mortgage has been paid off.");
}
choice = null;
}
if ("3".equals(choice)) {
if (j < 29) {
System.out.println("Press enter to get the mortgage information for year " + (j + 2));
choice = choose.nextLine();
} else {
System.out.println("Congratulations, your mortgage has been paid off.");
}
choice = null;
}
}
choose.close();
One bug is that String equality isn't the same as ==. You should use .equals():
while (!choice.equals("end")) {
Hope that helps!
You're setting choice to null, so choice != "end" is always true.
Move the next.close(); choice = null to outside the while loop.
Also, what weolfe91 said.
import java.util.Scanner;
class Main
{
public static void main(String [] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter no.1:");
int a=sc.nextInt();
System.out.println("Enter no.2:");
int b=sc.nextInt();
boolean exit=false;
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.exit");
System.out.println("choose one!");
Scanner sd=new Scanner(System.in);
System.out.println("enter your choice");
int num=sd.nextInt();
switch(num)
{
case 1:
int add=a+b;
System.out.println("addition="+add);
System.out.println("\n");
break;
case 2:
int sub=a-b;
System.out.println("subtraction="+sub);
System.out.println("\n");
break;
case 3:
int mul=a*b;
System.out.println("multilpication="+mul);
System.out.println("\n");
break;
case 4:
int div=a/b;
System.out.println("division="+div);
System.out.println("\n");
break;
case 5:
exit=true;
break;
}
}while(!exit);
}
}
Related
Hello there fellow coders. Just a noob here that is currently stuck in a pickle.
I am coding a math training program, and am needing to loop back to my main menu.
There is an infinite loop i am having trouble getting out of. If the user keeps answering the correct answer, it just keeps on asking for another problem. Selecting yes will generate a new answer and will keep doing so (infinite). Selecting no will terminate the program.
How do i make is so if they select no, it takes the user back to the main menu?
Also, how to make it so if they select yes, the problem only loops a new equation at max 10 times before taking the user back to my main menu.
This is my Code:
import java.util.Scanner;
import java.util.Random;
public class MathPracticeProgram
{
public static void main(String[] args)
{
//Scenario: Make a practice program for Addition, Subtraction, Multiplication, and Division. Include exit option as well.
Random rand = new Random ();
Scanner scan = new Scanner (System.in);
int menu = (5);
int num1, num2, user_answer, total;
System.out.println("Math Practice Porgram");
System.out.println("Please Input Your Choice via the number\n");
System.out.println("1. Addition\n2. Subtraction\n 3. Multiplication\n 4. Division\n Exit Program by entering 0");
System.out.println("\nYour choice:");
menu = scan.nextInt();
System.out.println("\n");
//Menu Selection
if (menu <= 5 || menu > 0)
{
switch(menu)
{
//Exit
case 0:
{
System.out.println("Thank you for using my math practice program.");
}
break;
//Addition
case 1:
{
System.out.println("You have selected Addition");
String user_again;
do
{
num1 = rand.nextInt(99);
num2 = rand.nextInt(99);
int counter = 0;
do
{
System.out.println("New solution to solve: ");
System.out.println(num1 + " + " + num2 + " = ");
user_answer = scan.nextInt();
System.out.println("\n");
total = num1 + num2;
if(user_answer != total)
{
System.out.println("Incorrect...");
counter++;
}
}while (user_answer != total && counter < 3);
System.out.println("Correct! Do you want another problem? yes or no: ");
user_again = scan.next();
}while(user_again.equalsIgnoreCase("yes"));
System.out.println("\nChanging to Main Menu\n");
}
break;
//Subtraction
case 2:
{
}
break;
//Multiplication
case 3:
{
System.out.println("Multiplication");
}
break;
//Division
case 4:
{
System.out.println("Division");
}
break;
}
}
}
}
Stacktrace Here
import java.util.*;
public class AccountClient {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean infiniteLoop = true;
boolean invalidInput;
int id;
// Create array of different accounts
Account[] accountArray = new Account[10];
//Initialize each account array with its own unique id and a starting account balance of $100
for (int i = 0; i < accountArray.length; i++) {
accountArray[i] = new Account(i, 100);
}
do {
try {
//inner loop to detect invalid Input
do {
invalidInput = false;
System.out.print("Enter an id: ");
id = input.nextInt();
if (id < 0 || id > 9) {
System.out.println("Try again. Id not registered in system. Please enter an id between 0 and 9 (inclusive).");
invalidInput = true;
input.nextLine();
}
} while (invalidInput);
boolean exit;
do {
exit = false;
boolean notAnOption;
int choice;
do {
notAnOption = false;
System.out.print("\nMain Menu\n1: check balance\n2: withdraw\n3: deposit\n4: exit\nEnter a choice: ");
choice = input.nextInt();
if (choice < 1 || choice > 4) {
System.out.println("Sorry, " + choice + " is not an option. Please try again and enter a number between 1 and 4 (inclusive).");
notAnOption = true;
}
} while(notAnOption);
switch (choice) {
case 1: System.out.println("The balance for your account is $" + accountArray[id].getBalance());
break;
case 2: {
boolean withdrawFlag;
do {
System.out.print("Enter the amount you would like to withdraw: ");
double withdrawAmount = input.nextInt();
if (withdrawAmount > accountArray[id].getBalance()) {
System.out.println("Sorry, you only have an account balance of $" + accountArray[id].getBalance() + ". Please try again and enter a number at or below this amount.");
withdrawFlag = true;
}
else {
accountArray[id].withdraw(withdrawAmount);
System.out.println("Thank you. Your withdraw has been completed.");
withdrawFlag = false;
}
} while (withdrawFlag);
}
break;
case 3: {
System.out.print("Enter the amount you would like to deposit: ");
double depositAmount = input.nextInt();
accountArray[id].deposit(depositAmount);
System.out.println("Thank you. You have successfully deposited $" + depositAmount + " into your account.");
}
break;
case 4: {
System.out.println("returning to the login screen...\n");
exit = true;
}
break;
}
} while (exit == false);
}
catch (InputMismatchException ex) {
System.out.println("Sorry, invalid input. Please enter a number, no letters or symbols.");
}
finally {
input.close();
}
} while (infiniteLoop);
}
}
The exception code:
Exception in thread "main" java.lang.IllegalStateException: Scanner closed
at java.util.Scanner.ensureOpen(Scanner.java:1070)
at java.util.Scanner.next(Scanner.java:1465)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at playground.test.main.Main.main(Main.java:47)
Hello, I made a basic program that uses a class called account to simulate an ATM machine. I wanted to throw an exception if the user didn't type in a letter. This worked fine, however I needed to make it loop so the program didn't terminate after it threw the exception. To do this I just put the try catch in the do while loop I had previously. When I did this though, it's throwing an IllegalStateException every time I type in a letter or choose to exit an inner loop I have which takes the user back to the loop of asking them to enter their id. What is an IllegalStateException, what is causing it in my case, and how would I fix this? Thanks.
It's fairly simple, after you catch the exception the finally clause gets executed. Unfortunately you're closing the scanner within this clause and Scanner.close() closes the underlying input stream (System.in in this case).
The standard input stream System.in once closed can't be opened again.
To fix this you have to omit the finally clause and close the scanner when your program needs to terminate and not earlier.
The question is this:
Simulate an ATM machine.
Create ten accounts in an array with id 0, 1, . . . , 9, and initial balance $100. The system prompts the user to enter an id. If the ID is entered incorrectly, ask the user to enter a correct id. Once an ID is accepted, the main menu is displayed as shown in the sample run. You can enter a choice 1 for viewing the current balance, 2 for withdrawing money, 3 for depositing money, and 4 for exiting the main menu. Once you exit, the system will prompt for an id again. Thus, once the system starts, it will not stop.
My code is this:
public static void main (String [] args)
{
Scanner input = new Scanner(System.in);
Account9_07 test = new Account9_07();
test.setBalance(100.00);
int [] account = new int [9];
for( ; ;) {
System.out.print("Enter an ID # (0-9): ");
int IDinput = input.nextInt();
if( IDinput <10 && IDinput > 0)
break;
System.out.println("The ID entered is incorrect. Please enter the correct ID \n");
}
for( ; ; ) {
System.out.println("\n Main Menu " + "\n 1: check balance " + " \n 2: withdraw" + "\n 3: deposit" + "\n 4: exit" );
System.out.print(" Enter a choice: ");
int choice = input.nextInt();
if(choice == 1) {
System.out.print("\n The balance is " + test.getBalance());
}
else if(choice == 2) {
System.out.print("How much would you like to withdraw: ");
double withdraw = input.nextDouble();
test.withdraw(withdraw);
}
else if(choice == 3) {
System.out.print("How much would you like to deposit: ");
double deposit = input.nextDouble();
test.deposit(deposit);
}
if( choice == 4)
break;
}
//4 is not looping back to enter an ID
}
EDIT: I've added some changes to the code itself, so please check it out again.
So what I've done, is place both for loops in an infinite while loop.
boolean CO = true;
while(true)
{
for( ; ;) {
System.out.print("Enter an ID # (0-9): ");
int IDinput = input.nextInt();
if( IDinput <10 && IDinput > 0)
break;
System.out.println("The ID entered is incorrect. Please enter the correct ID \n");
}
for( ; ; ) {
System.out.println("\n Main Menu " + "\n 1: check balance " + " \n 2: withdraw" + "\n 3: deposit" + "\n 4: go back to ID" + "\n 5: terminate program");
System.out.print(" Enter a choice: ");
int choice = input.nextInt();
if(choice == 1) {
System.out.print("\n The balance is " + test.getBalance());
continue;
}
else if(choice == 2) {
System.out.print("How much would you like to withdraw: ");
double withdraw = input.nextDouble();
test.withdraw(withdraw);
continue;
}
else if(choice == 3) {
System.out.print("How much would you like to deposit: ");
double deposit = input.nextDouble();
test.deposit(deposit);
continue;
}
else if( choice == 4)
{
break;
}
else if(choice == 5)
{
CO = false;
break;
}
}
if(CO == true)
{
continue;
}
break;
}
According to the code you posted, the program keeps running forever, so read the comments in the code. I've taken the liberty of giving another choice to the user, to enter 5 if he wants to stop the program.
CO stands for "Continue Outer".
By default, CO remains true. So when the user enters 4, then the second loop breaks. Since CO is still true, the outermost loop continues.
If the user enters 5, then CO becomes false, and the second loop breaks.
Now, because CO is false, the outermost loop breaks, and the program stops.
#pablo
I seem to be stuck in this loop :
do{
System.out.println("Voulez-vous saisir d'autres parties? (o/n)");
reponse = niveau.nextLine(); // extraction de la dernière ligne
if (reponse.toLowerCase().equals("o") == false || reponse.toUpperCase().equals("O") == false || reponse.toLowerCase().equals("n") == false || reponse.toUpperCase().equals("N") == false) {
System.out.println("R\u00C9PONSE INVALIDE ! VEUILLEZ ENTRER O OU N.");
} else {
validationReponse = true;
}
}while(!validationReponse);
Thank you all for your help ! I was able to get the validation working for questions with numeric answers but now I don't know how to get it working for questions with a "y or n" answer. I tried this but it's not working :
do{
System.out.println("Do you want to enter more game scores ? (y/n)");
reponse = niveau.nextLine();
if (reponse != o || reponse != n) {
System.out.println("Answer is invalid! Please enter y or n.");
} else {
validationReponse = true;
}
}while(!validationReponse);
I am a beginner. I am taking my first java class. In my code, I would like to add a validation for the questions : Please choose a game level, Have you won the game and Do you want to enter more games, I need to make sure that the input is valid and if an invalid answer is provided, it needs to loop back to the question. I am not sure how to do that.
No advanced coding in your answers please. I am in a beginners class. It needs to be simple.
String reponse="O";
while (reponse.toLowerCase().equals("o"))
{
System.out.println("Please choose your game level :");
System.out.println (" ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
System.out.println (" For Beginner press 1");
System.out.println (" For Advanced press 2");
System.out.println (" For Expert press 3");
System.out.println (" ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
System.out.print (" My choice is : ");
Niveau = niveau.nextInt();
if(Niveau == 1){
int choix1 = 0;
nbParties_Facile++;
System.out.println("Have you won the game ?");
System.out.println(" Press 1 for YES ");
System.out.println(" Press 2 for NO ");
choix1 = niveau.nextInt();
niveau.nextLine();
if (choix1 == 1){
nbPartiesFaciles_Finies++;
tauxReussite_Facile = nbPartiesFaciles_Finies / nbParties_Facile * 100;
System.out.println("How many times did you take to complete the grid ?");
System.out.println(" Please enter the time in minutes");
String afficheur5 = niveau.nextLine();
tempsResolution_Facile = (nbPartiesFaciles_Finies * tempsResolution_Facile) + Integer.parseInt(afficheur5) / (nbPartiesFaciles_Finies);
}
else if (choix1 == 2){
tauxReussite_Facile = nbPartiesFaciles_Finies - 1 / nbParties_Facile * 100;
}
else {
//default
}
}
if(Niveau == 2){
int choix2 = 0;
nbParties_Intermediaire++;
System.out.println("Have you won the game ?");
System.out.println(" Press 1 for YES ");
System.out.println(" Press 2 for NO ");
choix2 = niveau.nextInt();
niveau.nextLine();
if (choix2 == 1){
nbPartiesIntermediaires_Finies++;
tauxReussite_Intermediaire = nbPartiesIntermediaires_Finies / nbParties_Intermediaire * 100;
System.out.println("How many times did you take to complete the grid ?");
System.out.println(" Please enter the time in minutes");
String afficheur7 = niveau.nextLine();
tempsResolution_Intermediaire = (nbPartiesIntermediaires_Finies * tempsResolution_Intermediaire) + Integer.parseInt(afficheur7) / (nbPartiesIntermediaires_Finies);
}
else if (choix2 == 2){
tauxReussite_Intermediaire = nbPartiesIntermediaires_Finies - 1 / nbParties_Intermediaire * 100;
}
else {
//default
}
}
if(Niveau == 3){
int choix3 = 0;
nbParties_Expert++;
System.out.println("Have you won the game ?");
System.out.println(" Press 1 for YES ");
System.out.println(" Press 2 for NO ");
choix3 = niveau.nextInt();
niveau.nextLine();
if (choix3 == 1){
nbPartiesExpertes_Finies++;
tauxReussite_Expert = nbPartiesExpertes_Finies / nbParties_Expert * 100;
System.out.println("How many times did you take to complete the grid ?");
System.out.println(" Please enter the time in minutes");
String afficheur9 = niveau.nextLine();
tempsResolution_Expert = (nbPartiesExpertes_Finies * tempsResolution_Expert) + Integer.parseInt(afficheur9) / (nbPartiesExpertes_Finies);
}
else if (choix3 == 2){
tauxReussite_Expert = nbPartiesExpertes_Finies - 1 / nbParties_Expert * 100;
}
else {
//default
}
}
System.out.println("Do you want to enter more games ? (o/n)");
reponse = niveau.nextLine();
}
niveau.close();
Let's use as an example Please choose a game level question
So you there are many ways to do this, I will try to keep it as simple as possible since you are a beginner to the language, but the goal is always to stick to object orientated programming. However, we can accomplish this with a a simple method
. So you could have a simple method like this:
private static boolean askForLevel() {
System.out.println("What is the level you want?");
String response = scanner.nextLine();
if (!response.equals("something")) {
return false;
}
askForLevel();
// More stuff
return true;
}
Do somwething as Below,
do {
System.out.println("Please choose your game level :");
System.out.println (" ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
System.out.println (" For Beginner press 1");
System.out.println (" For Advanced press 2");
System.out.println (" For Expert press 3");
System.out.println (" ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
System.out.print (" My choice is : ");
while (!sc.hasNextInt()) {
System.out.println("That's not a number, Please choose a Number !");
sc.next();
}
number = sc.nextInt();
} while (number<=3);
inside if(number==1) do the thing same as above.
I would use JOptionPane instead of scanner...but that's a matter of opinion. Since you are new, your teacher is probably not going to jump right into object-oriented programming, which is ok because you need to understand the basics, so with a minimal use of object-oriented programming:
//user input
int level = 0;
do{
level = Integer.parseInt(JOptionPane.showInputDialog("Choose the level :").trim());
}while(level < 1 || level > 3);
if (level == 1) {
//your code
}
else if(level == 2){
//your code
}
else if(level == 3){
//your code
}
You could build this in a private method like Pablo suggested.
So, the user has to choose a number between 1 and 3. Otherwise, they're told to try again. If the user tries a number less than 1 or greater than 3, whatever number they chose gets stored in the "choice" variable and causes the program to continue to run when it should just stop. I assumed there would be an easy solution, but apparently it's beyond me as a beginner. The obvious thing to me would be to somehow clear or empty the value that has been assigned to "choice" after the unsuccessful user input. Is that possible?
import java.util.Scanner;
public class Furniture2Test {
public static void main(String[] args) {
wood();
} // end main
public static void wood() {
int choice;
int pine = 1;
int oak = 2;
int mahogany = 3;
int pineCost = 100;
int oakCost = 225;
int mahoganyCost = 310;
Scanner keyboard = new Scanner(System.in);
System.out.println("What type of table would you like?");
System.out.println("1. pine");
System.out.println("2. oak");
System.out.println("3. mahogany");
choice = keyboard.nextInt();
if (choice == 1) {
choice = pineCost;
} else if (choice == 2) {
choice = oakCost;
} else if (choice == 3) {
choice = mahoganyCost;
} else if (choice > 3 || choice < 1) {
System.out.println("Try again.");
choice = -1;
wood();
}
System.out.println("That will be $" + choice + ".");
size(choice);
} // end wood
public static void size(int choice) {
int sizeChoice;
int large = 35;
Scanner keyboard = new Scanner(System.in);
System.out.println("What size will that be?");
System.out.println("1. large");
System.out.println("2. small");
sizeChoice = keyboard.nextInt();
if (sizeChoice == 1)
System.out.println("That will be $" + (choice + large) + ".");
else if (sizeChoice == 2)
System.out.println("That will be $" + choice);
else
System.out.println("Please, enter either a 1 or a 2.");
} // end size
}
Your requirement can be done easily with do...while loop. Sample code is as follows:
do{
System.out.println("Choose option between 1 and 3");
choice = keyboard.nextInt();
}while(!(choice > 3 || choice < 1));
if (choice == 1) {
choice = pineCost;
} else if (choice == 2) {
choice = oakCost;
} else if (choice == 3) {
choice = mahoganyCost;
}
Hope this helps.
//put the menu logic
while(choice > 3 || choice < 1) {
//put your try again logic.
}
//can only exit the while loop if the number is 1, 2, or 3, so put your output statement down here after the while loop
import java.util.Scanner;
public class Furniture2Test
{
public static void main(String[] args)
{
wood();
} // end main
public static void wood()
{
int choice;
int pine = 1;
int oak = 2;
int mahogany = 3;
int pineCost = 100;
int oakCost = 225;
int mahoganyCost = 310;
Scanner keyboard = new Scanner(System.in);
System.out.println("What type of table would you like?");
System.out.println("1. pine");
System.out.println("2. oak");
System.out.println("3. mahogany");
choice = read_range(keyboard, 1, 3);
if(choice == 1)
{
choice = pineCost;
}
else
if(choice == 2)
{
choice = oakCost;
}
else
if(choice == 3)
{
choice = mahoganyCost;
}
else
if(choice > 3 || choice < 1)
{
System.out.println("Try again.");
choice = -1;
wood();
}
System.out.println("That will be $" + choice + ".");
size(choice);
} // end wood
public static void size(int choice)
{
int sizeChoice;
int large = 35;
Scanner keyboard = new Scanner(System.in);
System.out.println("What size will that be?");
System.out.println("1. large");
System.out.println("2. small");
sizeChoice = read_range(keyboard, 1, 2);
if(sizeChoice == 1)
System.out.println("That will be $" + (choice + large) + ".");
else
if(sizeChoice == 2)
System.out.println("That will be $" + choice);
else
System.out.println("Please, enter either a 1 or a 2.");
} // end size
private static int read_range (Scanner scanner, int low, int high) {
int value;
value = scanner.nextInt();
while (value < low || value > high) {
System.out.print("Please enter a value between " + low + " and " + high + ": ");
value = scanner.nextInt();
}
return value;
}
} // end class
whatever number they chose gets stored in the "choice" variable and causes the program to continue to run when it should just stop//
the program is contining to run because you are calling wood() if(choice > 3 || choice < 1)
if you want it to stop remove the wood() call
if you also want to clear the value for choice(instead of -1) you can assign it to null
choice is a local variable to the method wood, you are making a recursive call to wood when the user makes a wrong choice. This is an interesting design choice and probably not the best in this case.
When you call wood again, choice is rest (in this to unknown value until it is assigned value from the user).
Now the problem occurs when the wood method exists...each time it returns to the caller, it will call size(choice), where choice is -1 (because that's what you set it to before calling wood again).
You should be using a while-loop instead of recursive calls
You should never call size(choice) with anything other then a valid choice
Take a look at The while and do-while statement for more details