I am trying to validate input from a user.The user puts in Y coordinate a letter between (A-J) and x coordinate a number between (1-9).I can validate the y coordinate but am having trouble validating the x coordinate. I want it so if the user puts in something other than a number between 1 and 9 it keeps asking the user for valid input.
do {
// inner loop checks and validates user input
do {
System.out.println("Enter X Co-Ord (A-J), or Q to QUIT");
letter = input.next().toUpperCase(); // upper case this for
// comparison
if (letter.equals("Q"))
break; // if user enters Q then quit
String temp = "ABCDEFGHIJ";
while (temp.indexOf(letter) == -1) {
validString = false;
System.out.println("Please enter a valid input");
letter = input.next().toUpperCase();
col = temp.indexOf(letter);
}
if (temp.indexOf(letter) != -1) {
validString = true;
col = temp.indexOf(letter);
}
try {
System.out.println("Enter Y Co-Ord (0-9)");
row = input.nextInt();
} catch (InputMismatchException exception) {
validInt = false;
System.out.println("Please enter a number between 1 -9");
}
catch (Exception exception) {
exception.printStackTrace();
}
valuesOK = false; // only set valuesOK when the two others are
// true
if (validString && validInt) {
valuesOK = true;
}
} while (!valuesOK); // end inner Do loop
The output is:
Enter X Co-Ord (A-J), or Q to QUIT
d
Enter Y Co-Ord (0-9)
h
Please enter a number between 1 -9
Enter X Co-Ord (A-J), or Q to QUIT
Enter Y Co-Ord (0-9)
You just need to put a while loop around your nextInt() the same as you do when reading the letter:
System.out.println("Enter Y Co-Ord (0-9)");
row = -1
while (row < 0) {
try {
row = input.nextInt();
validInt = true;
} catch (InputMismatchException exception) {
System.out.println("Please enter a number between 1 -9");
row = -1;
validInt = false;
}
}
Just want to make the validation make more sense with the requirement, since human 's eye can skip easily the line nextInt()
String value = "";
System.out.println("Enter Y Co-Ord (1-9)");
while (!(value = input.next()).matches("[1-9]+")) {
System.out.print("Wrong input. Insert again: ");
}
System.out.println(value);
Of course, when you get the right value, then you can parse it to integer again (safely !!!)
Related
This question already has answers here:
Validating input using java.util.Scanner [duplicate]
(6 answers)
Closed 4 years ago.
I'm currently making a program and I want to take a input of either "Red" or "Black" and then a number from 1-10.
Input should look like Red 7 or Black 3
I want the program to reprint the line if the input is invalid. I was thinking about using a try { and then catch {. But I'm unsure what condition to check.
I tried this:
System.out.print("Please choose Black or Red....and a number from 1-10 (Example : Black 4): ");
String color = input.next();
int number = input.nextInt();
if(!color.equals("Red") || !color.equals("red") || !color.equals("Black") || !color.equals("black")) {
System.out.println("Incorrect input. Please enter Black or Red: ");
color = input.next();
}
if(!(number < 0 || number > 10)) {
System.out.println("Incorrect input. Please re-enter a valid number from 1 to 10: ");
color = input.next();
}
There are quite a few approaches to this situation. I suggest the following, which reads input by line:
Separate the input into an array using String#split(regex).
Check the color input using String#equalsIgnoreCase(String).
Parse the number input using Integer#parseInt(String).
Check the number input using a switch.
When all thrown together, it will look something like this:
System.out.println("Please choose Black or Red....and a number from 1-10: ");
Scanner input = new Scanner(System.in);
boolean flag = true;
while (flag) {
String line = input.nextLine();
String[] parts = line.trim().split("[\\s]");
try {
int num = Integer.parseInt(parts[1]);
if (parts[0].equalsIgnoreCase("red")) {
switch (num) {
case 1:
{
flag = false;
//...
}
/*
* I'm not going to include all the cases
*/
default:
throw new NumberFormatException();
}
} else if (parts[0].equalsIgnoreCase("black")) {
switch (num) {
case 1:
{
flag = false;
//...
}
/*
* I'm not going to include all the cases
*/
default:
throw new NumberFormatException();
}
} else {
System.out.println("'" + parts[0] + "' is invalid."
+ "\nPlease re-enter a color");
}
} catch (NumberFormatException e) {
System.out.println("'" + parts[1] + "' is invalid."
+ "\nPlease re-enter a number");
}
}
There is, of course, a cleaner approach which uses methods and things, but for the sake of a clean answer I am not going to include that.
ALong with what #hoobit said, also for checking a condition use the .equalsIgnoresCase method
So:
Scanner input = new Scanner(System.in);
String color = "";
int number = -1;
while(!color.equalsIgnoreCase("Black") || !color.equalsIgnoreCase("Red") && (number < 0 || number > 10))
{
System.out.print("Please choose Black or Red....and a number from 1-10: ");
color = input.next();
number = input.nextInt();
}
// \n puts that "quote" on the next line
System.out.println("Color chose: " + color + "\nnumber chose: " + number);
As requested by OP:
So just make sure to import the exception to be caught that crashed the program before, so before if they entered 2 strings, instead of a String and a int, it would crash, now it wont. It will now CATCH the "Crash" and keep going.
import java.util.InputMismatchException;
Now for the code:
Scanner input = new Scanner(System.in);
String color = "";
int number = -1;
while(!color.equalsIgnoreCase("Black") || !color.equalsIgnoreCase("Red") && (number <= 0 || number >= 10))
{
try
{
System.out.print("Please choose Black or Red....and a number from 1-10: ");
color = input.next();
number = input.nextInt();
}
catch(InputMismatchException e) //More specific error
{
e.getMessage();
System.out.println("Invalid entry, most specific. ");
}
catch(Exception e) //less specific general error
{
e.getMessage();
System.out.println("unknown entry error.");
}
}
// \n puts that "quote" on the next line
System.out.println("Color chose: " + color + "\nnumber chose: " + number);
You will put this in a while loop because you want to keep printing it until the user puts in a valid input. The while loop condition is if the the color doesn't equal red or black, and the number is not between 1-10 (the input is invalid). So if the input is invalid, it will keep asking for different colors and numbers, and if the input is valid, it will go out of the while loop.
String color = "";
int number = -1;
while(!color.equals("Black") || !color.equals("Red") && (number < 0 || number > 10){
System.out.print("Please choose Black or Red....and a number from 1-10: ");
color = input.next();
number = input.nextInt();
}
**Thanks Adi219 & Charles Spencer for helping with my part 1.
Now i'm trying a different approach, by validating the input before it store into an array, it look fine most of the time, but the exception only run once.
This is what i input to test the validating
1) I input "a", it returned "enter number between 0 to 100" which is correct.
2) I input 1000, and it returned "Invalid age" which i can tell that my IF conditions works.
3) No issue when i input the correct value for User no.1
Problem happens when i try to run the same test on User no.2. After I input correct value for User no.1, I type in "A" again and the programs just bypass all those conditions and captured no integer value.
import java.util.Scanner;
public class test2
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int i = 0;
double x = 0;
double Total = 0;
double Average = 0;
int Users = 2; //I fixed a number for testing purpose
boolean isNumber =false;
double ages[] = new double[Users];
for(int counter =0; counter < Users; counter++){
System.out.print("Enter the age for users "+(counter+1)+ ": ");
do{
try {
x =input.nextDouble();
if(x<0 || x>100){
System.out.print("Invalid age.. try again.. ");
}else if(x>0 || x<100){isNumber=true;}
}catch(Exception e){
System.out.print("Please enter number between 0 to 100 ");
input.next();
}
}while(!(isNumber));
System.out.println("User Age is "+ x); //Just to check input user's age
}
}
}
Because your entire do/while loop is based on whether isNumber is false, if you enter a valid number for user1, the isNumber variable is set to true, and the do/while loop will never run again because you never set isNumber back to false. There are two places were I set isNumber back to false, I've marked them. But I'm pretty sure this whole thing should be rewritten. For example there's no need to do:
else if(x > 0 || x < 100)
because you've already done:
if(x<0 || x>100)
If you do the first condition as x <= 0 || x >= 100 there's no need to do an else if statement.
for(int counter = 0; counter < Users; counter++)
{
System.out.print("Enter the age for users "+(counter+1)+ ": ");
do{
try {
x = input.nextDouble();
if(x<0 || x>100)
{
isNumber = false; // Set to false if invalid number
System.out.print("Invalid age.. try again.. ");
}
else if(x > 0 || x < 100)
{isNumber = true;} // If the age for user1 is valid, isNumber is set
// to true
}catch(Exception e)
{
isNumber = false; // Set to false if number invalid
System.out.print("Please enter number between 0 to 100 ");
input.next();
}
}while(!(isNumber));
Hello all I am trying to validate a set of inputs from a user, where it does not accept blanks, letter, letter with numbers, and numbers out of the range 0=100.
It goes fine except but when I input greater than 100, for example 150, it will catch and tell you to try again but when a letter is typed on the second prompt, it fails. And it'll only fail if the sequence of input is int is greater than 100 is input and the second input is a letter. I have a feeling it is the logic but I cant figure out exactly on which part.
It errors right on the line when arrayInt is declared (3rd set of while loop from validateUserInput method)
public static void main(String[] args) {
// Ask for user input
Scanner input = new Scanner(System.in);
//declare an array with index of 5
int array[] = new int[5];
//loop to prompt user to input 5 test scores, each of which are stored in array
for (int i = 0; i < array.length; i++){
System.out.println("Enter score " + (i+1) + ": ");
//array[i] = Integer.parseInt(input.nextLine());
String arrayInput = input.nextLine();
arrayInput = validateUserInput (arrayInput);
array[i] = Integer.parseInt(arrayInput);
}
//call method to display test scores
displayTestScores(array, array);
//exit out
System.out.println("Press any key to exit...");
input.nextLine();
System.exit(0);
}
//validate user input
public static String validateUserInput ( String arrayInput){
//variable to itirate through the string
int counter = 0;
//variable to index
int arrayInputLength = arrayInput.length();
//assign scanner for user input
Scanner input = new Scanner(System.in);
//loop to check if blank
while (arrayInputLength == 0){
System.out.println("that is not an integer X such that: 0 <= x <= 100, try again");
arrayInput = input.nextLine();
arrayInputLength = arrayInput.length();
}
//loop to check if user inputs numbers mixed with letters, iterate using counter
while (arrayInputLength > counter){
if (!Character.isDigit(arrayInput.charAt(counter))){
System.out.println("that is not an integer X such that: 0 <= x <= 100, try again");
arrayInput = input.nextLine();
arrayInputLength = arrayInput.length();
counter = 0;
}
else{
counter ++;
}
while (arrayInputLength == 0){
System.out.println("that is not an integer X such that: 0 <= x <= 100, try again");
arrayInput = input.nextLine();
arrayInputLength = arrayInput.length();
}
}
//loop to check while there is something inputted, make sure only between 0 and 100
while (arrayInputLength > 0 ){
int arrayInt = Integer.parseInt (arrayInput);
if (arrayInt > 0 && arrayInt <= 100){
return arrayInput;
}
else {
System.out.println("that is not an integer X such that: 0 <= x <= 100, try again");
arrayInput = input.nextLine();
arrayInputLength = arrayInput.length();
}
while (arrayInputLength == 0 ){
System.out.println("that is not an integer X such that: 0 <= x <= 100, try again");
arrayInput = input.nextLine();
arrayInputLength = arrayInput.length();
}
}
return arrayInput;
}
validateUserInput has too much responsibility (and duplicate code). It's trying to validate the user input and also get new input. But that new input might not be valid either (which is causing the error in your question).
Separate getting user input from validating the input. Consider changing
public static String validateUserInput ( String arrayInput)
to
public static boolean isValidInput(String arrayInput)
It only checks to see if the input is valid. It does not prompt the user for new input.
Then within the main for loop, keep prompting the user for input until it is valid.
for(...) {
....
while (!isValidInput(arrayInput)) {
System.out.println("that is not an integer X such that: 0 <= x <= 100, try again");
arrayInput = input.nextLine();
}
....
}
im trying to do two checks with a while loop:
1) To show "error" if the user inputs something other than an int
2) Once the user entered an int, if it is one digit, show "two digits only" and keep the loop on until a two digit int has been entered (so an IF should be used as well)
Currently I only have the first part done:
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number");
while (!scan.hasNextInt()) {
System.out.println("error");
scan.next();
}
However, if possible, I would like to have both checks in one while loop.
And that's where I'm stuck...
Since you already have two answers. This seems a cleaner way to do it.
Scanner scan = new Scanner(System.in);
String number = null;
do {
//this if statement will only run after the first run.
//no real need for this if statement though.
if (number != null) {
System.out.println("Must be 2 digits");
}
System.out.print("Enter a 2 digit number: ");
number = scan.nextLine();
//to allow for "00", "01".
} while (!number.matches("[0-9]{2}"));
System.out.println("You entered " + number);
As said above you should always take the input in as string and then try
and parse it for an int
package stackManca;
import java.util.Scanner;
public class KarmaKing {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input = null;
int inputNumber = 0;
while (scan.hasNextLine()) {
input = scan.next();
try {
inputNumber = Integer.parseInt(input);
} catch (Exception e) {
System.out.println("Please enter a number");
continue;
}
if (input.length() != 2) {
System.out.println("Please Enter a 2 digit number");
} else {
System.out.println("You entered: " + input);
}
}
}
}
First take the input as a String. If it is convertible to Int then you do your checks, else say 2 digit numbers are acceptable. If it is not convertible to a number throw an error. All this can be done in one while loop. And you would like to have a "Do you want to continue? " kind of a prompt and check if the answer is "yes" / "No." Break from the while loop accordingly.
To have it as one loop, it's a bit messier than two loops
int i = 0;
while(true)
{
if(!scan.hasNextInt())
{
System.out.println("error");
scan.next();
continue;
}
i = scan.nextInt();
if(i < 10 || >= 100)
{
System.out.println("two digits only");
continue;
}
break;
}
//do stuff with your two digit number, i
vs with two loops
int i = 0;
boolean firstRun = true;
while(i < 10 || i >= 100)
{
if(firstRun)
firstRun = false;
else
System.out.println("two digits only");
while(!scan.hasNextInt())
{
System.out.println("error");
scan.next();
}
i = scan.nextInt();
}
//do stuff with your two digit number, i
This while loop that is suppose to prompt for a price and a y/n and end if price = 0. However, when I run the code, it asks for the price, takes it, goes to a blank line, and I have to enter the number again before asking me the next question. For the second question, I only have to enter the input once.
And when I print the price array, the value is the number I inputted the second time.
int keepGoing = 1;
while (keepGoing > 0) {
System.out.print("How much is the item? (If no more items, enter '0') ");
if (in.nextDouble() > 0) {
prices.add(in.nextDouble());
System.out.print("Is the item a pet? (Y or N) ");
String input = in.next();
if (new String("Y").equals(input) || new String("y").equals(input)) {
isPet.add(true);
}
else { isPet.add(false); }
}
else { keepGoing = 0; }
}
Help please?
That's because each time you write in.nextDouble(), the user will be need to type something into the scanner. Instead, you should store the input in a tempory variable:
Double input = in.nextDouble(); // Keep the input in this variable
if (input > 0) { // You can use it on each of these lines
prices.add(input); // so that the user doesn't have to type it twice.
System.out.print("Is the item a pet? (Y or N) ");
String input = in.next();
if (new String("Y").equals(input) || new String("y").equals(input)) {
isPet.add(true);
}
else { isPet.add(false); }
}
else { keepGoing = 0; }
A little side note: keepGoing should probably be a boolean instead of an int
Also, you can use new String("Y").equalsIgnoreCase(input) so that you don't need the ||
It asks you twice because you call the in.nextDouble() method twice, one in the if statement and another time in the following line.
Take a look at the comments on your code below:
int keepGoing = 1;
while (keepGoing > 0) {
System.out.print("How much is the item? (If no more items, enter '0') ");
if (in.nextDouble() > 0) { // <-- You are asking for the input here
prices.add(in.nextDouble()); // <-- and asking for the input here again.
System.out.print("Is the item a pet? (Y or N) ");
String input = in.next();
if (new String("Y").equals(input) || new String("y").equals(input)) {
isPet.add(true);
}
else { isPet.add(false); }
}
else { keepGoing = 0; }
}
Just change your code to be like this:
int keepGoing = 1;
double d = 0;
while (keepGoing > 0) {
System.out.print("How much is the item? (If no more items, enter '0') ");
d = in.nextDouble();
if (d > 0) {
prices.add(d);
System.out.print("Is the item a pet? (Y or N) ");
String input = in.next();
if (new String("Y").equals(input) || new String("y").equals(input)) {
isPet.add(true);
}
else { isPet.add(false); }
}
else { keepGoing = 0; }
}