Issue with logic and Loop in Java - 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.

Related

Scanner needs inputs twice before continuing

Hey guys i have got a small weird problem here, i am asking the user to input their menu choice and depending on what they choose it calls a certain method.
I have used scanner.next() after some googling but for some reason only when i enter 1 or 2, i press enter and then press say 1 again and then it actually works. But what is weird that it calls options 3, 4, 5 and 6, immediately without me having to input the number twice.
I have tried with scanner.nextLine() after the scanner.nextInt() and that just leaves me having to put my option 1 or 2 in with no result.
while(exit == 0)
{
System.out.println("\n");
System.out.println("Menu 1: Display fullname of the user \n");
System.out.println("Menu 2: Display of user information \n");
System.out.println("Menu 3: Change password \n");
System.out.println("Menu 4: List all of users in the library full name\n");
System.out.println("Menu 5: Search for a book\n");
System.out.println("Press 6 to search for a books location in the library\n");
System.out.println("Press 0 to exit\n");
System.out.println("Enter choice: ");
int menuChoice = scanner.nextInt();
scanner.next();
if(menuChoice == 1)
{
displayUserFullName();
}
else if(menuChoice == 2)
{
displayUserInformation();
}
else if(menuChoice == 3)
{
menuForChangePassword();
}
else if(menuChoice == 4)
{
displayAllUserInSystem();
}
else if(menuChoice == 5)
{
searchBookByISBN();
}
else if(menuChoice == 6)
{
searchBookLocation();
}
else if(menuChoice == 0)
{
exit = 1;
}
}
Thank you in advance!
int menuChoice = scanner.nextInt();
scanner.next();
Read the javadoc for scanner. It waits for user input:
public String next(): [..] This method may block while waiting for input to scan
So in your program, you say: wait for user to type and int, then wait for user to type something.
Remove the scanner.next(); and it should work.
Scanner is a class parsing single tokens, like nextInt, nextDouble, nextToken (String). With corresponding testing methods: hasNextInt and so on.
All this parsing you do not need, so use nextLine for an entered line, or an other Reader class (InputStreamReader, BufferedReader).
Also you may utilize switch instead of if else if.
String menuChoice = scanner.nextLine();
switch (menuChoice) {
case "1":
displayUserFullName();
break;
case "2":
displayUserInformation();
break;
case "3":
menuForChangePassword();
break;
case "4":
displayAllUserInSystem();
break;
case "5":
searchBookByISBN();
break;
case "6":
searchBookLocation();
break;
case "0":
exit = 1;
break;
default:
System.out.printf("Unknown choice: '%s'%n", menuChoice);
}
menuChoice will contain the entire line, without line ending.
You might use an int with Integer.parseInt(menuChoice) but this would throw a NumberFormatException on wrong input, aborting your program. Scanner.nextInt would hang too, actually needing an hasNextInt().

What return statement should I utilize in order to use a Menu that throws an exception for non integer values?

I am working on a to do list and am currently stuck making a menu. The menu receives input from the user of the numbers 1-6 and carries out a specific task associated with that number(int). That's the perfect world scenario, so I need the menu to be able to take non integer values and not be bricked as well as display an error message to the user. I think I have created an efficient way of asking the user for integers without bricking the program but I cannot determine what my return statement should be in order to utilize the method in the main. I'll use it in a switch statement like this:
while (true) {
switch (getMenuOption()) {
case 1:
etc
This is the current method that I have for the getMenuOption. What return statement should I use, or is there a more efficient way to carry this out?
package project1_martinez_adriel;
import java.util.Scanner;
public class getMenuOption {
public static int getMenuOption() {
Scanner input = new Scanner(System.in);
System.out.println(" 1. Create a new item \n 2. Mark an item as in progress \n 3. Mark an item as completed \n 4. List all to do items \n 5. Remove completed items \n 6. Exit \n What would you like to do? \n ");
String value = input.nextLine();
int num;
try {
num = Integer.parseInt(value);
if (!(num == 1 || num == 2 || num == 3 || num == 4 || num == 5 || num == 6)) {
System.out.println("ERROR! Invalid choice! \nPlease enter a valid choice BETWEEN 1 & 6: ");
}else if (num == 6){
System.exit(0);
}
} catch (NumberFormatException e) {
System.out.println("ERROR! Please enter a valid INTEGER between 1 & 6.");
}
return //What do I put here!?
}
how about cleaning it up to be
if (num < 1 || num > 6) {
System.out.println("ERROR! Invalid choice!...");
}
then later
return num;
The code in your switch statement should process the options between 1 && 6 including 6 being System.exit (0);
I would even have the error messages in the switch default block
edit
num should also be initialized with a value, something like
int num = -1;
So after some clean up, frustration, & long hours I have come up with this, including the switch statements:
Scanner input = new Scanner(System.in);
boolean validInput = false;
do {
System.out.print("Enter an integer: ");
int num;
try {
num = input.nextInt();
switch (num) {
case 1:
case 2:
case 3:
case 4:
case 5:
case 6: // cascading case statement example
validInput = true;
break;
default:
System.out.println("ERROR! Please enter a valid choice BETWEEN 1 & 6 (inclusive): ");
num = input.nextInt();
break;
}
} catch (Exception e) {
/* input.next() to move the Scanner forward. */
System.out.println(input.next() + " was not valid input.");
System.out.println("ERROR! Please enter a valid INTEGER between 1 & 6.");
}
} while (!validInput);
input.close();
}
}

Infinite Looping when creating menu in 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).

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);

How would I create a "infinite" loops until the user decides to call it quits?

I'm having a slight problem.
I have a menu asking to:
reroll
get val
show max
show min
when the user chooses an option I want it to do one of them THEN re ask the menu in a sort of inifinite loop:
code:
import java.io.InputStream;
import java.util.Scanner;
class RecordDice {
public static void main(String[] args){
int dSides, Sides, Choice;
int max, min;
Scanner s = new Scanner(System.in);
Scanner c = new Scanner(System.in);
System.out.println("How many sides should the dice have?");
Sides = s.nextInt();
if(Sides == 4 || Sides == 6 || Sides == 12 || Sides == 20 || Sides == 100){
System.out.println("Please make a choice:\n" +
"1 - reroll the dice\n" +
"2 - get the value\n" +
"3 - show the maximum\n" +
"4 - show the minimum");
} else {
System.exit(-1);
}
Dice2 d = new Dice2(Sides);
int Choice = c.nextInt();
int Value = d.getValue();
switch(Choice){
case 1:
System.out.println();
d.reroll();
break;
case 2:
System.out.println("The current value is " + Value);
break;
case 3:
System.out.println("The maximum is " );
break;
case 4:
System.out.println("The minimun is ");
break;
}
}
}
Would putting the menu in a method and just calling the method every time a option is picked?
You can use a while loop to keep displaying it.
boolean keepGoing = true;
While(keepGoing)
{
//your code
}
Then to end it ask the user if they want to end it an set the boolean to false.
Add "5 - quit" to your menu.
Create a boolean, something like exit, initialized to false.
Add case 5: exit = true; break;
Then wrap the whole thing in while(!exit)
boolean exit = false;
while(!exit) {
//all the code you already have, starting with:
System.out.println("How many sides should the dice have?");
//and ending with the switch statement
//Plus the addition to the menu and addition to the switch statement
}
Ordinarily, I would do something like:
while(true) {
//do stuff
if(someExitCondition) {
break;
}
}
But seeing how as you're handling your user input with a switch statement, my above suggested method seems to be the cleanest way of handling it in this scenario.
Wrap it all in a do-while loop.
boolean userWantsToQuit = false;
do {
// code
// evaluate userWantsToQuit…
} while (!userWantsToQuit);
boolean keepGoing=true;
while(keepGoing)
{
//user input
if(user input to exit)
{
keepGoing=false;
}
}
or
while(true)
{
//user input
if(user input to exit)
{
break;
}
}
Assuming selection of dice sides you will allow only once, put code below that in do while loop.
You may prompt user "Do you wish to continue" after your switch block.
Get that value scanned
Condition in while loop will be something list while("YES".equals(userInput)).. assuming user will input YES or NO strings.

Categories