Infinite Looping when creating menu in Java - java

Im starting to learn Java on my own and wanted to see if i could create a basic menu, but i keep getting an infinite loop after picking an option. Any suggestions?
Scanner menu = new Scanner(System.in);
System.out.println("1. Print Name");
System.out.println("2. Print Age");
System.out.println("3. Print City");
System.out.println("4. Quit");
int choice = menu.nextInt();
do {
if (choice == 1) {
System.out.println("Saleh Kaddoura");
}
else if (choice == 2) {
System.out.println("20");
}
else if (choice == 3) {
System.out.println("Santa Clara");
}
else {
System.out.println("That is not a Valid Option!");
}
} while(choice != 4);
menu.close();
When i pick 1 it'll get stuck in an infinite loop printing my name. I have the conditional statements in a do while loop so the menu doesn't exit unless the quit option is picked.

The line that updates the choice variable should be inside the loop:
int choice;
do {
choice = menu.nextInt();
// ...
} while(choice != 4);
Otherwise, menu.nextInt() will only run once, no more numbers will be read after the first one and the value of choice won't change, so choice != 4 will always be true (unless you pick 4 the first time).

Related

Java Wrong User Input Loop until correct

I have a problem validating the program. I have tried using, While/Switch but it is all the same. The issue is when a user enters the wrong input for example 5, it shows the error and then it lets them type it in again, but if they type in the wrong number again, the program does not validate. I can definitely copy the code again and again within it, but there should be an easier way.
I hope you understand what I am trying to achieve.
How could I make it so it is a continues loop?
// Choosing the right room
public static int rooms () {
int room;
// Creating a new keyboard input
Scanner scanner = new Scanner(System.in);
// Displaying a message on the screen
System.out.println("What room are you in? ");
// Input
room = scanner.nextInt();
if (room==1) {
roomOne();
} else if (room==2) {
roomTwo();
} else if (room==3) {
roomThree();
} else if (room==4) {
roomFour();
} else {
System.out.println("Wrong room number, please enter the room number.");
room = scanner.nextInt();
}
//System.out.println("Sorry but you entered the wrong room number " + room + " Enter the correct room number 1-4 ");
return room;
} // End Rooms
You are looking for a while loop, something like this.
I use a do ... while to execute the line at least once.
The methods check the value and print a message if this is not correct. Return false will prevent the code to exit the loop and read again.
{
// Creating a new keyboard input
Scanner scanner = new Scanner(System.in);
int room;
do {
// Displaying a message on the screen
System.out.println("What room are you in? ");
room = scanner.nextInt();
} while( !isValid(room) );
... //if else or switch
}
private boolean isValid(int room){
if(room > 4 || room < 1){
System.out.println("Try again ;)" );
return false;
} else return true;
}
This is a quick code note even test.
while (true) {
int room = scanner.nextInt();
if(room < 1 || room > 4) {
System.out.println("Wrong room number, please enter the room number.");
continue;
}
break;
}
if (room == 1)
roomOne();
else if (room == 2)
roomTwo();
else if (room == 3)
roomThree();
else if (room == 4)
roomFour();
Hope it helps, nevertheless you should read a little more about loops.
This is how you should set up a loop for input cleaning:
Define a boolean value and assign a true or false value
Make the while loop run on the boolean value
When input is "clean", set the boolean value to true

while loop not working in Java

I am trying to get this to ask the question over and over again while the user inputs a 'Y'. and stop and return the Event.displayFinalResults(); when the user inputs a 'N'
i am getting a continuous loop right now. I am missing something or my layout it wrong. Any help would be great.
System.out.println("Is there anymore amounts you want to add?(Y/N): ");
Scanner keyboard = new Scanner(System.in);
char choice = keyboard.next().charAt(0);
choice = Character.toUpperCase(choice);
if(choice == 'Y')
{
do
{
System.out.println("Is there anymore amounts you want to add?(Y/N): ");
choice = keyboard.next().charAt(0);
choice = Character.toUpperCase(choice);
readValidateAmountType();
readValidateAmount();
}
while(choice =='Y');
}
else
{
Event.displayFinalResults();
}
thanks again.
You program asks a Yes/No question, then if you answer Yes, it enter a loop which starts by asking the same question again, before asking for the amount value.
You might want to ask for the amount value before asking the Yes/No question again.
If user answer No, the loop will exit (after asking for one more amount value), but Event.displayFinalResults() will not be executed. Drop the else clause, so Event.displayFinalResults() whether it entered the if statement or not.
System.out.println("Is there anymore amounts you want to add?(Y/N): ");
Scanner keyboard = new Scanner(System.in);
char choice = keyboard.next().charAt(0);
choice = Character.toUpperCase(choice);
if (choice == 'Y')
{
do
{
readValidateAmountType();
readValidateAmount();
System.out.println("Is there anymore amounts you want to add?(Y/N): ");
choice = keyboard.next().charAt(0);
choice = Character.toUpperCase(choice);
}
while(choice =='Y');
}
Event.displayFinalResults();
You could do this using break; as follows:
do {
System.out.println("Is there anymore amounts you want to add?(Y/N): ");
choice = keyboard.next().charAt(0);
choice = Character.toUpperCase(choice);
if (choice !='Y') {
break;
}
readValidateAmountType();
readValidateAmount();
} while(true);
Event.displayFinalResults();
One problem I see with this is, your while loop is inside the if statement. Once you exit the while loop, it's NOT going to run the code inside the else block because the if condition was already true.
So try removing the else block. This will make sure the Event.displayFinalResults method is called once the while loop exits.
System.out.println("Is there anymore amounts you want to add?(Y/N): ");
Scanner keyboard = new Scanner(System.in);
char choice = keyboard.next().charAt(0);
choice = Character.toUpperCase(choice);
if(choice == 'Y')
{
do
{
System.out.println("Is there anymore amounts you want to add?(Y/N): ");
choice = keyboard.next().charAt(0);
choice = Character.toUpperCase(choice);
readValidateAmountType();
readValidateAmount();
}
while(choice =='Y');
}
Event.displayFinalResults();
Clear code and compact:
Scanner keyboard = new Scanner(System.in);
char choice;
do {
System.out.println("Is there anymore amounts you want to add?(Y/N): ");
choice = keyboard.next().charAt(0);
choice = Character.toUpperCase(choice);
if(choice == 'Y') {
readValidateAmountType();
readValidateAmount();
}
} while(choice == 'Y');
Event.displayFinalResults();
Try the following out:
public void answering(char answer){
if(answer == 'Y' || answer == 'y'){
System.out.println("Answering");
} else if(answer == 'N' || answer == 'n'){
System.out.println("Not answering");
}
Instead of looping, call this method when you want to ask...

Issue with logic and Loop in Java

I started coding small program in Java. I wanted to exercise try-catch block, but i did not even come to that part and got stuck on loop part. I know this is very basic loop issue, but i guess i caught myself in a very simple logical problem. What I need from this program is if a user press 1, then to jump to switch statement and execute proper case. If a user press anything but 1 or 2, to go back to the MenuLoop function and execute it again until pressed correct number (1 or 2). I used While loop for control. Here is the code.
import java.util.Scanner;
public class TryCatchExercise {
public static void MenuLoop() {
Scanner input = new Scanner(System.in);
int choice;
System.out.println("1. Check for Number 1");
System.out.println("2. Check for Number 2");
System.out.print("Please enter your choice... ");
choice = input.nextInt();
while (choice != 1 || choice != 2) {
System.out.println("Invalid entry, press 1 or 2");
MenuLoop();
} //Isn't it logical at this point for loop to be skipped and
// go to Switch if a user pressed 1 or 2.??
switch (choice) {
case 1:
System.out.println("Pressed 1");
break;
case 2:
System.out.println("Pressed 2");
break;
default:
System.out.println("Invalid number");
}
}
public static void main(String[] args) {
MenuLoop();
}
}
OUTPUT
1. Check for Number 1
2. Check for Number 2
Please enter your choice... 1
Invalid entry, press 1 or 2
1. Check for Number 1
2. Check for Number 2
Please enter your choice... 2
Invalid entry, press 1 or 2
1. Check for Number 1
2. Check for Number 2
Please enter your choice... 5
Invalid entry, press 1 or 2
1. Check for Number 1
2. Check for Number 2
Please enter your choice...
You need a logical and (not or) here
while (choice != 1 || choice != 2) {
System.out.println("Invalid entry, press 1 or 2");
MenuLoop();
}
should be something like
while (choice != 1 && choice != 2) {
System.out.println("Invalid entry, press 1 or 2");
MenuLoop();
}
or (using De Morgan's laws) like
while (!(choice == 1 || choice == 2)) {
System.out.println("Invalid entry, press 1 or 2");
MenuLoop();
}
Maybe you can try the following code. In your code , it's not need to use iteration.
choice = input.nextInt();
while (choice != 1 && choice != 2) {
System.out.println("Invalid entry, press 1 or 2");
choice = input.nextInt();
}
Part of the problem is that you are recursively calling menuLoop from within menuLoop
If you had a while loop within main then you could just do a return if the proper keys is not pressed.
so main would be something like
while (!menuLoop () {
System.out.println("Invalid entry, press 1 or 2");
}
and menuLoop would return a boolean
public static boolean MenuLoop() {
....
System.out.println("1. Check for Number 1");
System.out.println("2. Check for Number 2");
System.out.print("Please enter your choice... ");
choice = input.nextInt();
if(choice != 1 && choice != 2) { // and NOT or
return false;
}
switch (choice) {
case 1:
System.out.println("Pressed 1");
break;
case 2:
System.out.println("Pressed 2");
break;
default:
System.out.println("Invalid number");
}
return true;
Also please remember that the scanner.nextInt will not swallow up the Enter that may or may not be pressed.
This is a logical problem, the "choice" value should be either 1 or 2.
In your (while) statement you are checking that "choice" is not different from 1
but also that "choice" is not different from 2. This condition is never reached because "choice" can be either 1 or 2 but not both values at the same time. This is only an explanation of the situation.

JAVA: Creating a Menu Loop

My program contains a few options that the user can select via the input of a number which allows them to complete a specific task. Currently, my code is set up with if and else if loops to complete task if a certain number of input. However, at the minute the program terminates after one task. I want the user to be able to input another number to complete another task. I have tried surrounding the code with a while loop and an exit option to allow the user to escape the loop and end the program, but this is not working and results in a "java.util.NoSuchElementException". The program works fine without the while loop.
This is an example of the current code which hopefully conveys what I mean:
System.out.println("Enter one of the following commands:");
System.out.println("1 - something..");
System.out.println("2 - something else..");
System.out.println("3 - exit");
Scanner scanchoice = new Scanner(System.in);
System.out.println();
System.out.println("Enter \"1\", \"2\" or \"3\"");
int choiceentry = scanchoice.nextInt();
while (choiceentry != 3) {
if (choiceentry < 1 || choiceentry > 3) {
System.out.println("Enter \"1\", \"2\", \"3\" or \"4\"");
choiceentry = scanchoice.nextInt();
}
else if(choiceentry == 1) {
// ..do something
}
else if(choiceentry == 2) {
//..something else
}
else if(choiceentry == 3) {
//...exit program
}
}
So I want to get into this loop, and only exit to terminate the program. I'm hoping that the while loop would take the user back to a menu, allowing you to select another option, however this is not working. What is wrong with this code? And how can I implement this idea?
Thanks in advance!
Use Scanner#hasNextInt() before you call Scanner.nextInt() to get rid of the NoSuchElementException
if(scanchoice.hasNextInt())
choiceentry = scanchoice.nextInt();
hasNextInt() returns true only if the next token is a valid int
You can do like this
//set choiceentry to -1, this will make it to enter while loop
int choiceentry = -1
while(choiceentry < 1 || choiceentry > 3){
System.out.println("Enter \"1\", \"2\", \"3\" or \"4\"");
if(scanchoice.hasNextInt())
choiceentry = scanchoice.nextInt();
}
switch(choiceentry){
case 1:
//do logic
break;
case 2:
//do logic
break;
case 3:
//do logic
break;
}
I have changed it to use switch statements, since they come handy in getting input data
You are only asking the user to pick another menu item if choice is < 1 or > 3
you have to set this code in an else statement`:
while (choiceentry != 3) {
else if(choiceentry == 1) {
// ..do something
}
else if(choiceentry == 2) {
//..something else
}
else if(choiceentry == 3) {
//...exit program
}
else{
System.out.println("Enter \"1\", \"2\", \"3\" or \"4\"");
choiceentry = scanchoice.nextInt();
}
}
If you want your program to continue prompting the user to select a task you'll need to move that prompt as well as your nextInt() call to somewhere inside your loop yet outside of an if statement so that it will always be invoked on each iteration.
As Mr Phi suggested in the comments, a switch statement would be a better alternative to your current if-else structure. It'll make your code cleaner to read and a default case is pretty nice for catching unexpected values.
I'd also add that a do-while might be more suitable for this task. This way you won't need to code your prompt for a choice twice.
int choiceentry;
do {
System.out.println("Enter \"1\", \"2\" or \"3\"");
choiceentry = scanchoice.nextInt();
switch (choiceentry)
{
case 1:
// do something
break;
case 2:
// ..something else
break;
case 3:
// .. exit program
break;
default:
System.out.println("Choice must be a value between 1 and 3.");
}
} while (choiceentry != 3);

Checking if a User's Input is in Range and is an Integer (Java) [duplicate]

This question already has answers here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Validating input using java.util.Scanner [duplicate]
(6 answers)
Closed 7 years ago.
I am working on a project (a game) and one of the requirements is to have warnings if they enter an option outside of the range (1-8) and if they enter a character. If the user enters an invalid number, the menu appears and asks them again which option they would like. If they enter a character, the program should ask them to enter an integer and ask for input again. This is what I have so far. It correctly identifies a number out of range and recalls the menu. It also identifies a character (invalid input), but does open input for the user to enter a correct option. How can I check both conditions?
Thanks,
Tyler
int userChoice = scnr.nextInt();//<-- use this variable
if (userChoice.hasNextInt() == false)
{
System.out.println("Error: Menu selection must be an integer! Please try again:");
}
// Variable used for storing what the user's main menu choice
if (0 > userChoice || userChoice > 8)
{
System.out.println("Error: Invalid Menu Selection.");
System.out.println("");
System.out.println("Available Actions:");
System.out.println("(1) Print Market Prices");
System.out.println("(2) Print Detailed Statistics");
System.out.println("(3) Buy Some Sheep");
System.out.println("(4) Buy a Guard Dog");
System.out.println("(5) Sell a Sheep");
System.out.println("(6) Sell a Guard Dog");
System.out.println("(7) Enter Night Phase");
System.out.println("(8) Quit");
System.out.println("What would you like to do?");
userChoice = scnr.nextInt();
}
you are using the hasNextInt() method on primitive int to see if the input is interger. instead use this:
int userChoice ;
try{
userChoice =scnr.nextInt();//<-- use this variable
}
catch(InputMismatchException ime){
System.out.println("Error: Menu selection must be an integer! Please try again:");
}
likewise use the same logic inside the if condition also
Better to go with Switch-Case statement within a loop.
Java JDK 1.7 also supports 'string' in switch-case now.
try{
int userChoice = scnr.nextInt();
if(userChoice > 0 && userChoice <9){
// your logic
}else{
System.out.println("Invalid choice");
showMenu();
}
}catch(Exception e){
System.out.println("Invalid choice");
showMenu();
}
public void showMenu(){
System.out.println("Available Actions:");
System.out.println("(1) Print Market Prices");
System.out.println("(2) Print Detailed Statistics");
System.out.println("(3) Buy Some Sheep");
System.out.println("(4) Buy a Guard Dog");
System.out.println("(5) Sell a Sheep");
System.out.println("(6) Sell a Guard Dog");
System.out.println("(7) Enter Night Phase");
System.out.println("(8) Quit");
System.out.println("What would you like to do?");
}
First of all there is correction to be made on the sequence nextInt() and hasNextInt() is invoked. First one is used to read the value from input, and second is used to see whether the value type is int. So you have to invoke hasNext[Type]() followed by `next[Type].
Secondly, since nextInt() is returning an int, so it is incorrect to invoke hasNextInt() on the userChoice variable.
Let's correct those two first as below.
if (scnr.hasNextInt()) {
int userChoice = scnr.nextInt();
} else {
// input is not an int
}
Now let's correct your code to get a valid int, also to print the instructions and ask for the input again for invalid inputs.
Scanner scnr = new Scanner(System.in);
boolean incorrectInput = true;
int userChoice = -1;
while (incorrectInput) {
if (scnr.hasNextInt()) {
userChoice = scnr.nextInt();
// Variable used for storing what the user's main menu choice
if (0 >= userChoice || userChoice > 8) {
System.out.println("Error: Invalid Menu Selection.");
System.out.println("");
System.out.println("Available Actions:");
System.out.println("(1) Print Market Prices");
System.out.println("(2) Print Detailed Statistics");
System.out.println("(3) Buy Some Sheep");
System.out.println("(4) Buy a Guard Dog");
System.out.println("(5) Sell a Sheep");
System.out.println("(6) Sell a Guard Dog");
System.out.println("(7) Enter Night Phase");
System.out.println("(8) Quit");
System.out.println("What would you like to do?");
} else {
incorrectInput = false;
}
} else {
scnr.next();
System.out.println("Error: Menu selection must be an integer! Please try again:");
}
}
System.out.println("userChoice = " + userChoice);
Or, you can use the powerful IntegerValidator from Apache Commons Validator:
if (new IntegerValidator().isInRange(Integer value, int min, int max)) {
// value is in range ...
}

Categories