Boolean Menu Validation - java

I'm trying to make a menu to ask the user to input YES or NO, if none of their input is either that, I want to prompt the user the question again. I was wondering why the code needs another return statement.

You code is wrong
You need to prompt again within the loop, otherwise if you do not eneter Yes or No, it will just spin forever.
When getting the nextLine you need to assign to a variable ,else it is just lost.
The value for valid never changes
so you code should be something like
Scanner sc = new Scanner(System.in) ;
boolean yes = false;
while (true) {
System.out.println("enter yes or no");
String line = sc.nextLine();
if (line.equalsIgnoreCase("yes")) {
yes = true;
break;
}
if (line.equalsIgnoreCase("no")) {
break;
}
// else back to the top
}
return yes;

Related

Why does my if input.equals("Quit") not quit correctly?

public void addPizza() throws FileNotFoundException {
Menu menu = new Menu();
Map<Integer, Pizza> pizzaMenu = menu.getPizzaMenu();
boolean exit = false;
while (!exit) {
String input1;
String input2;
System.out.println("What pizza");
input1 = sc.nextLine();
System.out.println("How many pizzas");
input2 = sc.nextLine();
if (input1.equals("Quit") || input1.equals("quit") || input2.equals("Quit") || input2.equals("quit")) {
exit = true;
} else {
Pizza pizza = pizzaMenu.get(Integer.parseInt(input1));
Integer quantity = Integer.parseInt(input2);
OrderLineItem orderLine = new OrderLineItem(pizza,quantity,"");
listOfOrderLineItems.add(orderLine);
Hello. I've got the above code, however my loop will not exit correctly.
As it stands now, It'll ask you "What pizza" -> input Quit -> "How many pizzas" -> input Quit.
The idea is that it just quits the loop after typing Quit once, either in the What pizza or How many pizzas.
IMO it should exit after just one "Quit", since the if statement should set the boolean to true?
Hope anyone can help.
Kind regards
Of course it behaves like this. Your if to check for the input "quit" comes after the second question.
The easiest change for this program to behave like you want is to put the same quit-check again after the first question and then instead of using the exit-flag make a break statement.
The while could then be a "while(true)".
So in short it would look like this:
while (true) {
String input1 = readline("What pizza");
if (isQuit(input1)) {
break;
}
String input2 = readLine("How many pizzas");
if (isQuit(input2)) {
break;
}
// do your stuff
}
Instead of changing the value of variable
exit
you can just use the
break
command and keep the while-loop running until it breaks.

While loop with String comparing isn't working?

I just started learning Java... Sorry if this is just a way too dumb question.
I was trying to compare the user input. If the input is not either "Yes" or "No" then force the user to input either one of them... but my code don't work...
Compiling has no issue, but even if the input is "Yes" or "No" the while loop just keep looping.
Tried printing out the value of "userInput" within the loop but it shows "Yes" or "No" correctly when inputted, yet the loop just goes on.
protected static boolean askUser() {
String userInput = "x";
boolean userChoice;
System.out.println("Do you have a question you want to know the answer too? (Yes/No): ");
userInput = input.nextLine();
while (!userInput.equalsIgnoreCase("Yes") || !userInput.equalsIgnoreCase("No")) {
System.out.println("Please input only \"Yes\" or \"No\": ");
userInput = input.nextLine();
}
if (userInput.equalsIgnoreCase("Yes")) {
userChoice = true;
} else {
userChoice = false;
}
return userChoice;
}
Any idea on how to fix this code?
!userInput.equalsIgnoreCase("Yes") || !userInput.equalsIgnoreCase("No") is always true because Yes is not No and No is not Yes.
You will want to loop while the input is not Yes and not No, so the condition should be !userInput.equalsIgnoreCase("Yes") && !userInput.equalsIgnoreCase("No").

exit program do-while loop in java

I am working on a java program. Right now everything is totally working, and all my functionality is there. However, the part I am stuck on is how to exit out of the program in a do-while loop. I must be getting the syntax wrong.
Basically, I set a switch done which reacts to a user's input. Right now, it's working and loops through the program, but it does not exit if I say "no" to continuing.
Here is the part of the code this is happening:
public void main() {
String userInput;
boolean done = true;
Scanner keyboard = new Scanner(System.in);
do {
System.out.println("Welcome to Hangman!");
System.out.println("Do you want to play?");
userInput = keyboard.next();
if (userInput.equals("Yes") || userInput.equals("yes") || userInput.equals("y") || userInput.equals("Y")) {
done = false;
} else if (userInput.equals("n") || userInput.equals("no") || userInput.equals("NO") || userInput.equals("No")) {
done = true;
}
while (!done) {
System.out.println(getDisguisedWord());
System.out.println("Guess a letter: ");
String guess = keyboard.next();
makeGuess(guess);
if (gameOver()) {
String ui;
System.out.println("Do you want to play again?");
ui = keyboard.next();
if (ui.equals("Yes") || ui.equals("yes") || ui.equals("y") || ui.equals("Y")) {
done = false;
} else {
done = true;
}
}
}
} while(done);
}
any tips on how I could handle this better?
Your problem isn't what you think it is. To compare Strings, you need to use their built-in equals() method: ui.equals("Y"). Using == to compare them will always return false. For more information, see How do I compare strings in Java?.
Also, you need to flip your done = true and done = false statements (if the user says yes to playing again, they aren't done yet).
Finally, I would recommend changing your keyboard.next() calls to keyboard.nextLine() calls, or else you may run into weird issues, especially if the user enters input that includes whitespace.
EDIT: I noticed some more issues. You're while loop should be while(!done) instead of while(done). Also, I would get rid of your do-while loop, because the while loop is already allowing the user to play as many times as they want, so it is unnecessary.
boolean flag = true;
Scanner sc = new Scanner(System.in);
do{
System.out.println("***********************************************************");
System.out.println("Welcome to the School Admissions App !!! Press X for exit");
System.out.println("***********************************************************");
System.out.println("Enter the Student Name: ");
String student_name=sc.next();
System.out.println("press y to use this application again. press x to exit from this application ");
String input_user=sc.next();
if(input_user.equalsIgnoreCase("y")){
flag=true;
}else{
flag=false;
System.out.println("Thanks for using it.");
}
}while(flag);
U should use equals method for comparing string value in if statment. ui.equals("yes").

When I run this code it is not allowing me to input to my scanner. Am I using the Scanner properly?

When I run the code I am not able to input to the scanner and continue through the code the way I want to. Can someone help me with some advice? I have imported the java.util.Scanner succesfully. BTW, I do call the method in the original program, I just removed it before I posted the question. I am using BlueJ.
public class Instructions extends ConsoleProgram
{
public boolean question(String prompt) {
Scanner s = new Scanner(System.in);
println(prompt);
String str = s.next();
boolean result = true;
while(!(str.equals("yes") || str.equals("no"))) {
str = s.next();
println("enter yes or no");
}
if (str.equals("yes")) {
result = true;
} else if (str.equals("no")) {
result = false;
}
return result;
}
Am I using the Scanner properly?
That isn't the problem. The real problem is a straight-forward bug in your application logic. This condition:
!(str.equals("yes") && str.equals("no"))
can never be false. A String cannot be both equal to "yes" AND equal to "no" at the same time. Therefore your while loop cannot terminate.
UPDATE
Following the edit, your code should more or less work. But this is not quite right.
while(!(str.equals("yes") || str.equals("no"))) {
str = s.next();
println("enter yes or no");
}
1) You are reading the next input token BEFORE you prompt for it.
2) You are not consuming the remaining characters after the first token of the line that the user just entered.
This is better
while(!(str.equals("yes") || str.equals("no"))) {
s.nextLine();
println("enter yes or no");
str = s.next();
}
I suggest you go back and read the javadocs for the Scanner class carefully.
It is also possible that new Scanner(System.in) is wrong. That is normally the right thing to do, but your requirements might require you to read use input from some other input stream.

Java .nextLine() repeats line

Everything of my guessing game is alright, but when it gets to the part of asking the user if he/she wants to play again, it repeats the question twice. However I found out that if I change the input method from nextLine() to next(), it doesn't repeat the question. Why is that?
Here is the input and output:
I'm guessing a number between 1-10
What is your guess? 5
You were wrong. It was 3
Do you want to play again? (Y/N) Do you want to play again? (Y/N) n
Here is the code:(It is in Java)
The last do while loop block is the part where it asks the user if he/she wants to play again.
import java.util.Scanner;
public class GuessingGame
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
boolean keepPlaying = true;
System.out.println("Welcome to the Guessing Game!");
while (keepPlaying) {
boolean validInput = true;
int guess, number;
String answer;
number = (int) (Math.random() * 10) + 1;
System.out.println("I'm guessing a number between 1-10");
System.out.print("What is your guess? ");
do {
validInput = true;
guess = input.nextInt();
if (guess < 1 || guess > 10) {
validInput = false;
System.out.print("That is not a valid input, " +
"guess again: ");
}
} while(!validInput);
if (guess == number)
System.out.println("You guessed correct!");
if (guess != number)
System.out.println("You were wrong. It was " + number);
do {
validInput = true;
System.out.print("Do you want to play again? (Y/N) ");
answer = input.nextLine();
if (answer.equalsIgnoreCase("y"))
keepPlaying = true;
else if (answer.equalsIgnoreCase("n"))
keepPlaying = false;
else
validInput = false;
} while (!validInput);
}
}
}
In your do while loop, you don't want the nextLine(), you just want next().
So change this:
answer = input.nextLine();
to this:
answer = input.next();
Note, as others have suggested, you could convert this to a while loop. The reason for this is that do while loops are used when you need to execute a loop at least once, but you don't know how often you need to execute it. Whilst it's certainly doable in this case, something like this would suffice:
System.out.println("Do you want to play again? (Y/N) ");
answer = input.next();
while (!answer.equalsIgnoreCase("y") && !answer.equalsIgnoreCase("n")) {
System.out.println("That is not valid input. Please enter again");
answer = input.next();
}
if (answer.equalsIgnoreCase("n"))
keepPlaying = false;
The while loop keeps looping as long as "y" or "n" (ignoring case) isn't entered. As soon as it is, the loop ends. The if conditional changes the keepPlaying value if necessary, otherwise nothing happens and your outer while loop executes again (thus restarting the program).
Edit: This explains WHY your original code didn't work
I should add, the reason your original statement didn't work was because of your first do while loop. In it, you use:
guess = input.nextInt();
This reads the number off the line, but not the return of the line, meaning when you use:
answer = input.nextLine();
It immediately detects the leftover carriage from the nextInt() statement. If you don't want to use my solution of reading just next() you could swallow that leftover by doing this:
guess = input.nextInt();
input.nextLine();
rest of code as normal...
The problem really lies in a completely different segment of code. When in the previous loop guess = input.nextInt(); is executed, it leaves a newline in the input. Then, when answer = input.nextLine(); is executed in the second loop, there already is a newline waiting to be read and it returns an empty String, which activates the final else and validInput = false; is executed, to repeat the loop (and the question).
One solution is to add an input.nextLine(); before the second loop. Another is to read guess with nextLine() and then parse it into an int. But this complicates things as the input could not be a correct int. On a second thought, the code already presents this issue. Try entering a non-numeric response. So, define a function
public static int safeParseInt(String str) {
int result;
try {
result= Integer.parseInt(str) ;
} catch(NumberFormatException ex) {
result= -1 ;
}
return result ;
}
And then replace your first loop with:
do {
validInput= true ;
int guess= safeParseInt( input.nextLine() ) ;
if( guess < 1 || guess > 10 ) {
validInput= false ;
System.out.print("That is not a valid input, guess again: ");
}
} while( !validInput );
PS: I don't see any problem with do-while loops. They are part of the language, and the syntax clearly indicates that the condition is evaluated after the body is executed at least one time. We don't need to remove useful parts of the language (at least from practice) just because others could not know them. On the contrary: if we do use them, they will get better known!
validInput = false;
do {
System.out.print("Do you want to play again? (Y/N) ");
answer = input.next();
if(answer.equalsIgnoreCase("y")){
keepPlaying = true;
validInput = true;
} else if(answer.equalsIgnoreCase("n")) {
keepPlaying = false;
validInput = true;
}
} while(!validInput);
I changed the coding style as I find this way more readable.
Your problem is that nextInt will stop as soon as the int ends, but leaves the newline in the input buffer. To make your code correctly read the answer, you'd have to enter it on the same line as your guess, like 5SpaceYReturn.
To make it behave more than one would expect, ignore the first nextLine result if it contains only whitespace, and just call nextLine again in that case without printing a message.
I believe the output of input.nextLine() will include the newline character at the end of the line, whereas input.next() will not (but the Scanner will stay on the same line). This means the output is never equal to "y" or "n". Try trimming the result:
answer = input.nextLine().trim();

Categories

Resources