This question already has answers here:
Validating input using java.util.Scanner [duplicate]
(6 answers)
Closed 7 years ago.
So I made a program, and I need to keep prompting for coordinates if the user enters a non-negative, invalid input. Meaning that if the user enters a number above 2 or a letter it should ask him to choose again. The problem that I am running into is that right when I enter a letter, the program terminates and I get InputMisMatchException for the letter, and ArrayOutOfBoundsException for the higher numbers. Is there a way to bypass all those errors and just ask the user to pick again?
So for example:
"Enter the coordinates to place an 'X'. Row then Column."
//enters number > 2 or letter
"Invalid input. Please choose again."
Use a do/while loop:
boolean valid = false;
do {
try {
// "Enter the coordinates to place an 'X'. Row then Column."
// validate input
valid = // final value of validation goes here
} catch (Throwable t) {
// invalid input
} while (!valid)
}
Related
This question already has answers here:
How would I use a while loop to keep requesting user input
(3 answers)
Closed 2 years ago.
I have looked at other StackOverflow questions on this topic but being a new developer I am extremely confused. I am trying to write a program that asks the user riddles and restarts after the user gets three wrong answers on one specific riddle. The code that needs the restart is:
if (wrongAnswer == 3){
System.out.println("You have failed three times.");
restartApp();
The code where I need to restart should go right where the restartApp() is right now.
Thanks in advance!
So, as Turing85 mentioned, restarting the whole program probably isn't the way to go. Generally, you use what's called a state machine. For this example, a simple one can be implemented with a while loop. Here's an example:
import java.util.Scanner;
public class foo
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
boolean running = true;
while(running){
System.out.println("enter a value, enter -1 to exit...");
int value = scan.nextInt();
if(value == -1){
System.out.println("exiting");
break;
}else{
System.out.println("do stuff with the value");
}
}
}
}
and here's the output:
enter a value, enter -1 to exit...
1
do stuff with the value
enter a value, enter -1 to exit...
2
do stuff with the value
enter a value, enter -1 to exit...
4
do stuff with the value
enter a value, enter -1 to exit...
-1
exiting
Now I know that there is a thread called "Validating input using java.util.Scanner". I already looked there and that thread only answered 1/2 of my problems. The other half is when someone enters a number greater than 2 I get Array Index Out of Bounds Exception. I just need help on if someone enters a 3 for either row or column, the console should prompt something like this:
"Enter the coordinates to place an 'X'. Row then Column."
//enters 3 and 3
"Please enter a valid input"
It would keep and asking the user for a valid number until he gives one.
Would I need to do something like the !keyboard.hasNextInt() but for integers? And that would run smoothly with the rest of my code?
You could use a do-while loop. Something like
do {
//prompt
//input
} while (input not valid);
Where prompt and input should be replaced by code to prompt the user and accept input. In the while section, check if input is valid.
You're question isn't too clear but I'll try to make sense of it.
I'm assuming you've named your scanner "keyboard"
Before I try running this code, the first problem I can see is this (Note that I grabbed this from your code before you edited the question):
while (board[row][col] != ' ')
{
System.out.println("Already occupied space");
System.out.println("Choose again");
row = keyboard.nextInt();
col = keyboard.nextInt();
}
Earlier, you made sure that the user enters integers. However, you have abandoned that completely in this case.
Assuming you're trying to avoid an error if the user enters something other than an integer, this is what I would do:
while(true){
boolean valid = true;
if(!keyboard.hasNextInt()){
valid = false;
keyboard.next();
}
else{
row = keyboard.nextInt();
}
if(!keyboard.hasNextInt()){
valid = false;
keyboard.next();
}
else{
col = keyboard.nextInt();
}
if (valid && (row > 2 || col > 2)){
System.out.println("Please enter a valid input");
continue;
}
else if(!valid){
System.out.println("Please enter a valid input");
continue;
}
else
break;
}
There are a couple reasons this code might seem a bit long. First off, we're trying to test if the input is an integer before we attempt to store it as an int. Secondly, we want to compare the input after we store it successfully to see if it's less than 3. If the input isn't an integer, the boolean "valid" will be false. The way a compiler works, if valid is false in the if statement it will ignore anything to the right of the &&, avoiding an error.
I admit, this is using some commands that I haven't learned before, so this might not be the most efficient way. But you get the idea :)
P.S. You should probably throw the above code into a method.
This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 8 years ago.
I'm attempting to make a java function that returns an int inputted by the user, but won't return until the user inputs a valid number. Here's my initial model of the function:
public int getChoice(){
try{
return scan.nextInt();
}catch(Exception e){
return getChoice();
}
}
scan is declared by Scanner scan = new Scanner(System.in);
This function resulted in a Java.lang.stackOverflowError(hmm... this seems an appropriate website for that...). I figure this is because the function is being constantly called.
I've considered somehow using Integer.valueOf(scan.nextLine())', but the reason I haven't really done anything with it is because at some points, and I can't figure out what determines whether this happens or not, but pressing 'Enter' when the program is calling nextLine() will skip the next nextLine(). I can't really figure out a way around that.
So if anyone could possibly provide me with a Java function that will loop until the user inputs a valid integer, then return that integer, please do so, thank you.
You are getting a bad recursion because the getChoice call inside catch block. To repeat the code indefinitely until the user gives you a valid number use while(true) infinite loop. The code you have to read the line and convert it to Integer it is just fine.
public int getChoice() {
while (true) {
try {
return Integer.valueOf(scan.nextLine());
} catch (Exception e) {
System.out.println("Enter a valid number");
}
}
}
This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 5 years ago.
how can I give a condition on an input from "system.in" that will halt the program until the right value is inserted?
for exemple, I'm waiting for an INT from the user, 1,2,3,4 or 5
the user inputs "hello"
how can i give the user a message of "Invalid input, try again"
and keep the program at halt until he does give the right one?
update: I didnt came so you can write my code, right now it looks something like this:
int j=UserIn.nextInt();
switch (j) {
case 1:
break;
case 2:
writetoDic(word, "dict.txt");
break;
case 3:
word = correction;
break;
i'm asking that, if im getiing something else than an int from the user, how can i ask the user to give a valid argument instead of just getting an error?
You need to use a loop. I don't think you actually mean halt the program, but actually preventing to program to proceed until valid input. You can do something like this
Scanner scanner = new Scanner(System.in);
int num;
while (true) {
try {
System.out.println("Enter a number: ");
num = scanner.nextInt();
if (num >= 1 && num <= 5) {
break;
}
} catch (InputMistmatchException ex){
System.err.println("Input needs to be a number between 1 and 5, dummy.");
}
}
Program will run if not between 1 and 5 and not an integer
This question already has answers here:
How to check that a string is parseable to a double? [duplicate]
(6 answers)
Closed 9 years ago.
I am making a program and cannot figure out how to make my scanner input only recognize numbers. Here is what I mean.
System.out.print(" What is the distance in feet:" );
//ask the user to input variables
Distance = keyboard.nextDouble();
What can I put after the distance input in order to allow me to output some sort of message telling the user they didn't enter a number.
I thought maybe starting with something like
if (Distance != double)
System.out.print ("You did not enter a valid character, please enter again."
but that does not work. Any suggestions?
You need to use Scanner#hasNextDouble() method to test, whether there is a double value to read:
// While the next input is not a double value, repeat
while (!keyboard.hasNextDouble()) {
System.out.println("Please enter a valid numeric value");
keyboard.nextLine(); // Move Scanner past the current line
}
double distance = keyboard.nextDouble();
Also, the loop might go infinite, if the user keeps on passing wrong input. You can give him some max number of attempt to get it right, and then throw some exception, or display some message, and then do a System.exit(1);.
You can make this using a try cacth block, somethinh like:
System.out.print(" What is the distance in feet:" );
//ask the user to input variables
Distance = keyboard.nextDouble();
try
{
//you next code, considering a valid number
}catch (NumberFormatException ex)
{
//here u show a message ou another thing
}
Hope it helps ^^