am having trouble trying to validate a user response to exit my app or try again(its a simple game)? when the game finishes I ask the user if they want to continue type "y" for yes or "n" for no to exit. How can I validate their response so if its neither y or n I show an error message and ask them to type it again???
This doesn't seem to worK for me???
if (!choice.equalsIgnoreCase("n") && !choice.equalsIgnoreCase("y"))
System.out.println("Error enter y for yes and n for no");
System.out.println("Would you like to play again (y/n):");
choice = sc.next();
Just change the
if (!choice.equalsIgnoreCase("n") && !choice.equalsIgnoreCase("y"))
to
while (!choice.equalsIgnoreCase("n") && !choice.equalsIgnoreCase("y"))
This will continue to ask them for another letter each time they don't choose the letter 'n' or 'y'.
EDIT: Also, you might want brackets around the code within the if (soon to be while) statement.
Without any full context, difficult to give a relevant answer.
But you can already test your code with curly braces around the if statement:
if (!choice.equalsIgnoreCase("n") && !choice.equalsIgnoreCase("y")){
System.out.println("Error enter y for yes and n for no");
System.out.println("Would you like to play again (y/n):");
choice = sc.next();
}
Indeed, with your current code, only the first line:
System.out.println("Error enter y for yes and n for no");
is taken in account by your condition.
Related
This is a part of a program I'm making for practice, its purpose doesn't really matter.
I have declared the Scanner as a field of the class** (it's not written here sorry).
I want to make a method that returns an answer specified to the users input. And I want to make all the neccesary checks needed so the user can't input a character or symbol, just an integer. When the input data is of the wrong type I want the user to try input again.
public static void Answer() {
System.out.println("\n\t1.It was good! \n\t2.Kinda bad too...");
System.out.println();
if (scanner.hasNextInt()) {
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("Oh great!");
break;
case 2:
System.out.println("I see you as well");
break;
default:
System.out.println("Please select a valid answer :");
Answer();
break;
} else {
System.out.println("Please select a number, characters are not acceptable!");
Answer();
}
When I enter an invalid number like 3,4 etc the algorithm triggers the switch block and the recursive call as well, working just fine!
BUT when I enter a character it triggers an infinite recursive call without letting me enter new input form the scanner and ends up in StackOverflow error.
You check if the Scanner has an int. If it does not, then it goes to the else branch.
In the else branch, it calls Answer() again. But here's the catch: your scanner still doesn't have an int. So scanner.hasNextInt() returns false. hasNextInt() does not try to read anything - it merely checks if there is input that can be interpreted as an int.
(Source: Java documentation).
So the program goes again to the else branch, without ever reaching the point where it can try to read input... and there it calls Answer() again. Now, the code still doesn't have an int... so once again, scanner.hasNextInt() returns false, and it goes to the else branch. Once again, it does not get to the part where the scanner consumes input, but instead gets to the part where it calls Answer() again...
And this will continue, until the call stack is full and you get the StackOverflow error.
You'll have to take care of the situation that the user enters something that is not an int. You'll have to consume that input that is not an int.
As an aside, I'd prefer to do this using iteration, rather than recursion.
In my program I need to take an input from a user, but it must be an integer. If the user doesn't input an integer, I need the program to reprompt them to enter an integer, and keep doing so until they enter one. I found an example while loop code snippet online which works perfectly, but I am having problems understanding why and how it works, and I'd really like to understand better:
Scanner reader = new Scanner(System.in);
int guess=0;
System.out.println("Guess the number");
while (!reader.hasNextInt()) { //I get that this is a "not have" boolean
System.out.println("That's not a number. Please enter a valid number");
reader.next();
}
guess= reader.nextInt();
System.out.println(guess);
My questions are:
Does the !hasNext condition in the while loop actually trigger the scanner object to ask the user for input and then check that input, or does it only check anything that has already been inputted?
Why is it necessary to have the reader.next(); line after the while loop's main statement and what is this doing exactly? I know it's necessary as the program doesn't work when I take it out. But is it prompting for input? If yes what happens to this input?
When guess= reader.nextInt(); runs, why doesn't it re-prompt the user for input at this point?
Sorry that these are probably really basic questions, I'm new to coding and Java and just can't get my head around what's happening internally in this particular example, though have no problem doing other basic stuff with the Scanner.
It's not particularly intuitive, for sure, so don't feel bad for not getting it immediately.
It seems to me that the problem you're having with your understanding is that that methods such as nextInt may or may not prompt for user input, depending if anything is already in the Scanner.
Here's the sequence of events:
All your code executes until you hit !reader.hasNextInt(). There's no input so it "blocks" (waits) until there is some input from the user.
If the user enters 'A', that's not an integer so we enter the body of the while loop. We then print the error message.
Now, hasNextInt doesn't "consume" (process) the user input when it's checking whether or not it's an integer, so we still have that invalid user input of 'A' sitting in our scanner. We call reader.next() to effectively discard that value.
Now we're back to !reader.hasNextInt(). The scanner is empty once again, so we prompt for user input. If they enter another non-integer, that process will simply keep repeating.
Say this time we do have a valid user input - they've entered the number 2. This passes the check so our while loop ends and we continue along.
We've now got some input in our scanner, but we've not consumed it. We're sure it's an integer because of the while loop condition. We can now consume the input with reader.nextInt() and assign it to our variable.
hasNextInt() only checks whether the next input is an integer. It won't consume any input at all. The ! is just negate theu outcome of this function.
As hasNextInt() won't consume, then we need to use next() to consumeo the user input to let hasNextInt() to check with user's next input value. As you won't need it at all, then no need to assign it to any variables.
Scanner won't display the prompt at all. The prompt is printed by System.out.println().
For the line nextInt(), it is used to consume the next user input. Since hasNextInt() must be true when it execute this line, there must be one integer input waiting for consumption, so this method can return immediately with that user input.
Try it :)
public static void main(String[] args) {
int option;
if(args!=null&&args.length>0){
option = Integer.parseInt(args[0]);
}
else{
System.out.println("Enter:\n 1 to run x \n 2 to run y \n");
Scanner keyboard = new Scanner(System.in);
option = keyboard.nextInt();
}
switch (option) {
case 1:
xx
break;
case 2:
yy
break;
default:
break;
}
}
Hi so I have had a look around and I cannot find the answer I am looking for..
What I am looking for is a way to set a requirement when using the scanner(in) method. I am making a bank account app now for a project and when I ask the user to enter an 8 digit account number I want to be able to restrict the users input to exactly 8 digits with errors popping up if they enter above or below that set requirement?
I seen something like Integer.toString().length but don't know how to use it and if it will even work? Any help will do thank you 😊
So you start by declaring scanner object:
Scanner in = new Scanner(System.in);
Some message to user so he/she would know what to do:
System.out.println("enter your account numer");
int account_number = in.nextInt();
Now just check if the numer is 8 digit.
if (new Integer(account_number).toString().length == 8)
System.out.println("Correct account numer);
else
System.out.println("Something went wrong 404");
I'm trying to complete a ticket issuing program, in which i have to ask the user a series of questions, however the program sometimes asks more than one question at a time, effectively skipping the first question before an input can be returned, here is the part of the code, that asks the questions and below the output.
System.out.println("Please enter date of Event (dd/mm/yyyy): ");
ev.setDate(sc.nextLine());
System.out.println("Please enter Artist/Band name ");
ev.setArtist(sc.nextLine());
System.out.println("Please enter name of Venue for event ");
ev.setVenue(sc.nextLine());
System.out.println("Please enter name of city where event is being held: ");
ev.setCity(sc.nextLine());
As you can see this shows up as this below, I dont want to ask the user to not put in spaces, that looks terrible!
Please choose your reference number for this event entry:
001
Please enter date of Event (dd/mm/yyyy):
Please enter Artist/Band name (use underscore, no spacing between words):
I have even tried multiple Scanners and even a final Scanner, but it doesn't seem to fix the problem.
Put an sc.nextLine(); at the end of your code. It will free the buffer and not jump anymore a question. +1 and accept if it works.
would you please help me on this?
I have written an class and here is the code. I have two problems.
(1) I wanted to know how to get back to the beginning of the loop after user has enter copies he wants to add instead of exiting the system. I mean after system says "copies has been added." it ask user "if you want to add a book?" and then loop start again.
(2) What should I do to add an object to the array each time loop is finished?
my problem is everytime loop is running, the book1 is being rewritten.
thank guys- solved
As discussed, this will make your loop run until the user enters yes
System.out.println("do you want to add a Book?(yes or no) ");
Scanner s=new Scanner(System.in);
String h = s.nextLine();
while (h.contains("yes")|| h.compareToIgnoreCase("YES") == 0) {
int size=list.size();
//your code here
System.out.println("do you want to add a Book?(yes or no) ");
h = s.nextLine();
}
Replace for (int m=0;m<10;m++) with a do-while loop
Declare Book book1=new Book(); at the top instead of inside the loop
Branching statements would help. http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
Ok to restart the loop there is a keyword continue