How to Handle Incorrect User Input into a Scanner

How can I handle incorrect user input into a scanner?

You can just read your input as a String and check if it is a float value, else loop until it is or the user gets tired:

public static float floatInput() {
Scanner scanner = new Scanner(System.in);
System.out.println("Input a float:");
for(;;){
try{
return Float.parseFloat(scanner.next());
} catch(NumberFormatException e){
System.out.println("Incorrect input type, try again:");
}
}
}

How to handle users inputting invalid types into a scanner?

Short Answer

Use Integer.parseInt(input.nextLine()) in a try-catch block that looks for a NumberFormatException.

Without Try-Catch

If you really must avoid the use of try-catch, then your idea of calling input.hasNextInt() before attempting to parse the integer with input.nextInt() will work.

int userInt = 0;
if (input.hasNextInt()) {
userInt = input.nextInt();
} else {
System.out.println("That wasn't a valid int.");
// Take whatever corrective action you want here.
}

Long Answer

If you have a UI for the calculator, then you can ensure that clicking specific buttons only sends valid values back to the calculation backend. However, since it looks like you are letting your users type in their values on the command line, there isn't a way to lock their keyboard into only being able to type valid numbers. As a result you have to test the validity of their input on your own.

Potential Enhancements

Also, when I'm trying to get a number from a user, I like to loop and keep asking them for a valid number instead of terminating the program. Consider something like this.

Scanner input = new Scanner(System.in);
int userInt = 0;
boolean userIntReceived = false;

while (!userIntReceived) {
try {
userInt = Integer.parseInt(input.nextLine());
userIntReceived = true;
} catch (NumberFormatException e) {
System.out.println("That wasn't a valid int. Please try again.")
}
}

// Now you have a valid int from the user.

input.close();

How should I handle invalid user input?

The main issue I think is that you do not handle invalid input errors. Preferably you catch these exceptions and prompt the user to enter a valid input. Optionally, you could also add a default value, that the booleans are set to in the case of nothing being entered by the user (of course specify this at the start of the program).

Something like this should help convey what I mean:

public class ABaybayanAssignment3 {

public static void main(String[] args) {

Scanner scnr = new Scanner(System.in);

System.out.println("Type yes or no for the following questions:");

boolean Vegetarian = requestBooleanInput(scnr,"Is anyone in your party vegetarian?" );
boolean vegan = requestBooleanInput(scnr,"Is anyone in your party vegan?");
boolean glutenFree = requestBooleanInput(scnr,"Is anyone in your party gluten free?");

System.out.println("Here are your restaurant choices:");

if (Vegetarian || vegan || glutenFree) {
System.out.println("Corner Cafe");
}
if (!Vegetarian && !vegan && !glutenFree) {
System.out.println("Joe's Gourmet Burgers");
}
if (!vegan) {
System.out.println("Main Street Pizza Company");
}
if (!vegan && !glutenFree) {
System.out.println("Mama's Fine Italian");
}
}

public static boolean requestBooleanInput(Scanner scanner, String message){
boolean value = false;
boolean validInput = false;
while (!validInput){
System.out.println(message);
try {
value = scanner.nextBoolean();
validInput = true;
} catch (Exception e) {
System.out.println("You entered an invalid input '"+scanner.next()+"', please enter only 'true' or 'false'");
}
}
return value;
}
}

Exception Handling with wrong User Input Java

Scanner.nextInt returns ant int, so there is no need to go Object selection = scanner.nextInt(), and then cast to an int, you can merely have int selection = scanner.nextInt() and surround that in a try catch that chatches java.util.InputMismatchException, which is the exception thrown when the user types a letter and not an number

How do you handle invalid input if you need the user to enter an integer?

First, if the input is not an Integer the exception that will be thrown is InputMismatchException, and you shouldn't close the scanner until you continue with it, try this instead:

import java.util.InputMismatchException;

public class Question2 {

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean active = true;
String num_string_positive = "";
String num_string_negative = "";
int my_int;
while (active) {
try {
my_int = in.nextInt();
} catch(InputMismatchException e) {
active = false;
in.close();
}
}
}

}

How to prevent wrong user input on a variable?

You expect that the user enters an int, however, the user is free to enter whatever the user pleases. Therefore you need to ensure that the input can be parsed.

String userInput = scan.next(); //scan the input
int value;
try {
value = Integer.parseInt(userInput); // try to parse the "number" to int
} catch (NumberFormatException e) {
System.out.println("Hey, you entered something wrong...");
// now you can ask the user again to enter something
}

How to handle wrong user input

If you are using scanner, you can use the nextInt() method with the condition hasNextInt() which would only read integer inputs. Have a look at this post for example:

Taken from the above mentioned post.

Scanner sc = new Scanner(System.in);
System.out.print("Enter number 1: ");
while (!sc.hasNextInt()) sc.next();
int num1 = sc.nextInt();
int num2;
System.out.print("Enter number 2: ");
do {
while (!sc.hasNextInt()) sc.next();
num2 = sc.nextInt();
} while (num2 < num1);
System.out.println(num1 + " " + num2);

Also you can look at the documentation for scanner's nextInt() here

How do I display an error message for incorrect input?

I would use a while loop to have the user input something until I get the desired result. To determine whether or not the user entered the correct thing in this case, put a try/catch around scnr.nextDouble(). The exception you're looking for is InputMismatchException. This is an example that I made:

Scanner scanner = new Scanner(System.in);
double value;
while(true) {
System.out.print("Enter a double: ");
try {
value = scanner.nextDouble();
break;
}
catch (InputMismatchException e) {
System.out.println("That is not a valid input. Please try again.");
scanner = new Scanner(System.in);
}
}
System.out.println("The double entered was " + value);


Related Topics



Leave a reply



Submit