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().
Related
I'm trying to create a hotel menu in Java (I'm still learning the language) and I've run into an issue. I can make the menu open a new menu, but when I make a choice from that second menu, it constantly loops. I think it's the for loop that is causing the issue. Can anyone advise how I get the second menu entry to stop looping? Methods below:
Menu class method:
public void getMenu()
{
Floor floor = new Floor();
Scanner kboard = new Scanner(System.in);
int choice = 0;
System.out.println("Booking Menu");
System.out.println("Select from the options below");
System.out.println("1. Check room availability");
System.out.println("2. Display floor");
System.out.println("3. Display all availability");
System.out.println("4. Cancel Booking");
System.out.println("Please enter choice (press 8 to continue)");
choice=kboard.nextInt();
do
{
switch(choice)
{
case 1: room.getRoomMenu();
break;
case 2:
break;
case 3:
break;
}
}
while (choice !=8);
}
That menu opens a second menu in this method:
public void getRoomMenu()
{
Floor f1 = new Floor(1);
Floor f2 = new Floor(2);
Floor f3 = new Floor(3);
Floor f4 = new Floor(4);
boolean check = false;
Scanner kboard = new Scanner(System.in);
int choice = 0;
System.out.println("Which Floor?");
System.out.println("1");
System.out.println("2");
System.out.println("3");
System.out.println("4");
choice=kboard.nextInt();
do
{
switch(choice)
{
case 1: f1.displayFloor();
break;
case 2: f2.displayFloor();
break;
case 3: f3.displayFloor();
break;
case 4: f4.displayFloor();
break;
}
}
while(choice !=8);
kboard.close();
}
The second menu option should display the chosen floor which displays all rooms on that floor. This is the displayFloor method:
public void displayFloor()
{
/**
* Displays floor number and room display method
*/
System.out.println("Floor: "+floorNumber);
for(int counter=0;counter<rooms.length;counter++)
{
rooms[counter].display();
}
}
Both your while loops continue looping as long as choice != 8. And since you never modify the choice inside the loop, it will just continue looping (unless 8 was input by the user).
Also note that the break; you added are breaks for the switch-case, not to stop the do-while-loop. To have a break within the switch-case stop the entire do-while-loop, you should use a label to give the loop a name, and break that one. In addition, you should ask the user to give a new input if it didn't came into one of the switch-cases, otherwise it will still loop forever. So something like this:
choice = kboard.nextInt();
myLoop: do {
switch(choice) {
case 1:
f1.displayFloor();
break myLoop;
case 2:
f2.displayFloor();
break myLoop;
case 3:
f3.displayFloor();
break myLoop;
case 4:
f4.displayFloor();
break myLoop;
default: // Not one of the above
System.out.println(choice + " is an unknown choice. Please choose again.");
choice = kboard.nextInt(); // Ask the user for a new input
break; // <- This break only breaks the switch, not the loop
}
} while(choice !=8);
If your intention was to continue looping until the user input 8, it should be something like this instead:
choice = kboard.nextInt();
do {
switch(choice) {
case 1:
f1.displayFloor();
break;
case 2:
f2.displayFloor();
break;
case 3:
f3.displayFloor();
break;
case 4:
f4.displayFloor();
break;
default: // Not one of the above
System.out.println(choice + " is an unknown choice. Please choose again.");
}
choice = kboard.nextInt(); // Ask the user for a new input for the next iteration
} while(choice !=8);
The loop is occurring here:
while(choice !=8);
You need to make sure that the ending condition is always satisfied at some point to avoid unwanted infinite loops.
Maybe you meant if(choice != 8) rather than a do/while loop (which will keep running until choice is 8, which will only occur if the user inputs 8).
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();
}
}
I have to get 1 to 3 answer if user puts invalid option do while should re run but problem is its re running three times. like if I put answer in 1 to 3 its giving correct result on other number it reprint loop three times.
char choice;
public void mainMartfunc() throws java.io.IOException{
do{
System.out.println("Login as:");
System.out.println(" 1. Customer");
System.out.println(" 2. Employee");
System.out.println(" 3. Owner");
choice = (char) System.in.read();
} while(choice < '1' || choice>'3');
switch(choice){
case '1':
System.out.println("\tCustomer Menu:");
break;
case '2':
System.out.println("\tEmployee Menu:");
break;
case '3':
System.out.println("\tOwner Menu:");
break;
}
}
When you press the enter key, two characters are generated: a carriage return '\r' and a line feed '\n'. And System.in.read() takes each character from the input, so you get three characters including the digit.
Trying using a Scanner instead. It will tokenize your input so you don't receive those whitespace characters.
java.util.Scanner input = new java.util.Scanner(System.in);
then change your choice assignment to something like this:
choice = input.next().charAt(0);
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);
This is a small part of my program that I am working on. I'm trying to check if the user enters the correct number.
They have five choices to choose from so they can either hit 1, 2, 3, 4, or 5. Then press enter.
So I want to check to make sure the user doesn't type anything in < 1 or > 5. I got that part to work... But I just want to know if there is a easier way to do it then from what I did in code below.
The next part is that I also want to make sure the user doesn't type in letters. like "gfgfadggdagdsg" for a choice.
Here is my code of the part I am working on....
public void businessAccount()
{
int selection;
System.out.println("\nATM main menu:");
System.out.println("1 - View account balance");
System.out.println("2 - Withdraw funds");
System.out.println("3 - Add funds");
System.out.println("4 - Back to Account Menu");
System.out.println("5 - Terminate transaction");
System.out.print("Choice: ");
selection = input.nextInt();
if (selection > 5){
System.out.println("Invalid choice.");
businessAccount();
}
else if (selection < 1){
System.out.println("Invalid choice.");
businessAccount();
}
else {
switch(selection)
{
case 1:
viewAccountInfo3();
break;
case 2:
withdraw3();
break;
case 3:
addFunds3();
break;
case 4:
AccountMain.selectAccount();
break;
case 5:
System.out.println("Thank you for using this ATM!!! goodbye");
}
}
}
You may get rid of checking < 1 and > 5 by adding a default case.
try{
selection = input.nextInt();
switch(selection){
case 1:
viewAccountInfo3();
break;
case 2:
withdraw3();
break;
case 3:
addFunds3();
break;
case 4:
AccountMain.selectAccount();
break;
case 5:
System.out.println("Thank you for using this ATM!!! goodbye");
break;
default:
System.out.println("Invalid choice.");
businessAccount();
}
}catch(InputMismatchException e){
//do whatever you wanted to do in case input is not an int
}
Using BufferedReader you can do something like this:
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
int selection = 0;
try{
selection = Integer.parseInt(s);
if(selection > 5 || selection < 1){
System.out.println("Invalid choice.");
businessAccount();
}else{
// your switch code here
}
// you can use #Nishant's switch code here. it is obviously better: using switch's default case.
}catch(NumberFormatException ex){
// throw new Exception("This is invalid input"); // or something like that..
System.out.println("Invalid choice.");
businessAccount();
}
Hope that helps.
Note: you must import java.lang.NumberFormatException import java.io.InputStreamReader and import java.io.BufferedReader
Use the switch case it's better and more speed the if statement when you check selection from a Specific.
an alternative would to use regular expressions to get it work.
Say you have a string x then
String x = "something";
if(x.matches("regex")){
}
Another way to do this is surround with try catch.