Validating input with try-catch - java

I am trying to learn try-catch uses and have to validate input so that the user must enter 1 or 2 for the program to continue. I believe I am close, but cannot seem to get the program to continue if the user enters something wrong such as '3' or '2.12'.
Here's what I have:
String input = " ";
try {
Scanner scan = new Scanner(System.in);
input = scan.next();
Integer.parseInt(input);
if (!input.equals("1") && !input.equals("2")) {
System.out.println();
System.out.println("Invalid imput! Please select '1' or '2':");
}
} catch (InputMismatchException a) {
System.out.println();
System.out.println("Invalid imput! Please select '1' or '2':");
}

I don't necessarily see the point of using InputMismatchException for your use case. Instead, if the input doesn't match what you expect, you can log an error and just prompt the user to input again.
But [Integer#parseInt()][1] can throw an exception if the input isn't an actual integer. In your original code you never actually use the result of this call, but I have done so in my answer. In this case, it does potentially make sense to use a try-catch block.
int result;
while (true) {
try {
Scanner scan = new Scanner(System.in);
input = scan.next();
result = Integer.parseInt(input);
} catch(Exception e) {
System.out.println("Could not parse input, please try again.");
continue;
}
if (result != 1 && result != 2) {
System.out.println("Invalid input! Please select '1' or '2':");
}
else {
break;
}
}

You should put in your condition the throw statement in able to your catch statement fetch the error, the code should be like this:
String input = " ";
try {
Scanner scan = new Scanner(System.in);
input = scan.next();
Integer.parseInt(input);
if (!input.equals("1") && !input.equals("2")) {
System.out.println();
System.out.println("Invalid imput! Please select '1' or '2':");
throw new InputMismatchException ();
}
} catch (InputMismatchException a) {
System.out.println();
System.out.println("Invalid imput! Please select '1' or '2':");
}

The code is expecting for positive integers but can input string and loop again until got a positive integer input value.
Scanner scanner = new Scanner(System.in);
Integer expectedOutput = -1;
public Integer getInputNumber(){
boolean valid;
String inputData;
do {
System.out.print("Enter Input Number: \t");
try {
inputData = scanner.nextLine();
// expecting positive integers
if (Integer.parseInt(inputData) > 0) {
expectedOutput = Integer.parseInt(inputData);
valid = true;
} else {
System.out.println("Invalid Input!");
valid = false;
}
} catch (Exception ex){
valid = false;
}
} while(!valid);
return expectedOutput;}

Related

More succinct way to get Scanner input with error checking?

Just want to know if there was any better way of doing this since it's a lot of writing.
boolean isInputValid = false;
do {
System.out.print("Input: ");
final String input = sc.nextLine();
try {
age = Integer.parseInt(input);
} catch (NumberFormatException e) {
System.out.println("Invalid input. Try again");
continue;
}
if (input < 0 || 10 < input) {
System.out.println("Number outside of range.");
} else {
isInputValid = true;
}
} while (!isInputValid);
Well there are some things that can be ommited on a first look, but there is not much to remove.
Reduced integer parsing in a single line and removed input variable.
Change isInputValid to its negation isInputInvalid to remove else , Boolean assignment and negation in the while clause.
Moved if into the try clause to make redundant and remove the continue statement.
boolean isInputInvalid = true;
do {
System.out.print("Input: ");
try {
age = Integer.parseInt( sc.nextLine());
isInputInvalid = input < 0 || 10 < input;
if (isInputInvalid) {
System.out.println("Number outside of range.");
}
} catch (NumberFormatException e) {
System.out.println("Invalid input. Try again");
}
} while (isInputInvalid);
Well by first glance, I can see that you're comparing an incorrect variable type of string with an integer (your input variable), I'm just going to assume that you meant to compare the age. You should also put the if statements within your try/catch to ensure that its handled as intended (there's also no point in having it outside the try/catch if a NFE is thrown, it won't get ran anyways).
boolean isInputValid = true;
do {
System.out.print("Input: ");
final String input = sc.nextLine();
try {
age = Integer.parseInt(input);
if (age < 0 || 10 < age) {
System.out.println("Number outside of range.");
isInputValid = false;
}
} catch (NumberFormatException e) {
System.out.println("Invalid input. Try again");
continue;
}
} while (isInputValid);

Handling InputMismatchException in a While-Loop

So I have a while-loop where you have 3 options to choose from and you choose them by inserting a number on standard input using a scanner, my code is like this:
int option;
String request;
Scanner input2 = new Scanner(System.in);
System.out.println("Choose an option:\n" + "1-Get camera information\n" + "2-Submit Data\n"
+ "3-Exit");
while(true){
try {
option = input2.nextInt();
if (option == 1) {
System.out.println("Camera name:");
request = input2.nextLine();
while (request.length() < 3 || request.length() > 15) {
System.out.println("Name has to be between 3 and 15 characters, insert a new one:");
request = input2.nextLine();
}
CamInfoRequest info_request = CamInfoRequest.newBuilder().setName(request).build();
if (stub.camInfo(info_request).getReturn() != 0) {
System.out.println("Camera does not exist");
} else {
System.out.println(stub.camInfo(info_request).getLatitude() + " " + stub.camInfo(info_request).getLongitude());
}
} else if (option == 2) {
System.out.println("submit");
} else if(option ==3){
break;
} else{
System.out.println("Invalid option.");
}
}catch(InputMismatchException e){
System.out.println("Invalid input");
}
}
So the way this is the code enters in an infinite loop when it catches the exception where it keeps printing "Invalid input", I tried using input2.next() at the catch but then he waits for another input I don't want, I can't use input2.close() either. What can I do?
I can't use input2.close() either.
You should never close the Scanner instance for System.in as it also closes the System.in.
I tried using input2.next() at the catch but then he waits for another
input I don't want
Use Scanner::nextLine instead of Scanner::next, Scanner::nextInt etc. Check Scanner is skipping nextLine() after using next() or nextFoo()? to learn why.
Also, try to use do...while wherever you need to ask the user to enter the data again in case of an invalid entry.
Given below is a sample code incorporating these points:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int option;
boolean valid;
Scanner input2 = new Scanner(System.in);
do {
valid = true;
System.out.println("Choose an option:\n" + "1-Get camera information\n" + "2-Submit Data\n" + "3-Exit");
try {
option = Integer.parseInt(input2.nextLine());
if (option < 1 || option > 3) {
throw new IllegalArgumentException();
}
// ...Place here the rest of code (which is based on the value of option)
} catch (IllegalArgumentException e) {
System.out.println("This is an invalid entry. Please try again.");
valid = false;
}
} while (!valid);
}
}
A sample run:
Choose an option:
1-Get camera information
2-Submit Data
3-Exit
abc
This is an invalid entry. Please try again.
Choose an option:
1-Get camera information
2-Submit Data
3-Exit
6
This is an invalid entry. Please try again.
Choose an option:
1-Get camera information
2-Submit Data
3-Exit
2
Feel free to comment in case of any further doubt/issue.
Just Put the Scanner statement inside your try block
while (true) {
try {
Scanner input2 = new Scanner(System.in);
option = input2.nextInt();
if (option == 1) {

Do while infinite loop

I am trying to write a method that asks a user for a positive integer. If a positive integer is not inputted, a message will be outputted saying "Please enter a positive value". This part is not the issue. The issue is that when I try to implement a try catch statement that catches InputMismatchExceptions (in case user inputs a character or string by accident), the loop runs infinitely and spits out the error message associated with the InputMistmatchException.
Here is my code:
private static int nonNegativeInt(){
boolean properValue = false;
int variable = 0;
do {
try {
while (true) {
variable = scanner.nextInt();
if (variable < 0) {
System.out.println("Please enter a positive value");
} else if (variable >= 0) {
break;
}
}
properValue = true;
} catch (InputMismatchException e){
System.out.println("That is not a valid value.");
}
} while (properValue == false);
return variable;
}
Essentially what is happening is that the scanner runs into an error when the given token isn't valid so it can't advance past that value. When the next iteration starts back up again, scanner.nextInt() tries again to scan the next input value which is still the invalid one, since it never got past there.
What you want to do is add the line
scanner.next();
in your catch clause to basically say skip over that token.
Side note: Your method in general is unnecessarily long. You can shorten it into this.
private static int nonNegativeInt() {
int value = 0;
while (true) {
try {
if ((value = scanner.nextInt()) >= 0)
return value;
System.out.println("Please enter a positive number");
} catch (InputMismatchException e) {
System.out.println("That is not a valid value");
scanner.next();
}
}
}
you are catching the exception but you are not changing the value of variable proper value so the catch statement runs forever. Adding properValue = true; or even a break statement inside the catch statement gives you the required functionality!
I hope I helped!
You can declare the scanner at the start of the do-while-loop, so nextInt() will not throw an exception over and over.
private static int nonNegativeInt(){
boolean properValue = false;
int variable = 0;
do {
scanner = new Scanner(System.in);
try {
while (true) {
variable = scanner.nextInt();
if (variable < 0) {
System.out.println("Please enter a positive value");
} else if (variable >= 0) {
break;
}
}
properValue = true;
} catch (InputMismatchException e){
System.out.println("That is not a valid value.");
}
} while (properValue == false);
return variable;
}
This is indeed nearly identical to SO: Java Scanner exception handling
Two issues:
You need a scanner.next(); in your exception handler
... AND ...
You don't really need two loops. One loop will do just fine:
private static int nonNegativeInt(){
boolean properValue = false;
int variable = 0;
do {
try {
variable = scanner.nextInt();
if (variable < 0) {
System.out.println("Please enter a positive value");
continue;
} else if (variable >= 0) {
properValue = true;
}
} catch (InputMismatchException e){
System.out.println("That is not a valid value.");
scanner.next();
}
} while (properValue == false);
return variable;
}
Just add a break statement inside your catch.
Btw, you can get rid of the while loop by rewriting it like this:
try {
variable = scanner.nextInt();
if (variable < 0) {
System.out.println("Please enter a positive value");
} else {
properValue = true;
}
}
//...

infinite loop on non-numeric input in java

This is a simple java function taking an input in double. It takes an input and first check if the value is non-numeric. And then check if the value is greater than 0 or not.
The problem I am facing is every time I enter a non-numeric input, it runs an infinite loop and only print "Enter a number greater or equal to 1.0: "
double getInput(double n) {
Scanner kbd = new Scanner(System.in);
boolean flag = false;
boolean check = false;
while (!flag) {
System.out.println("Enter a number greater or equal to 1.0: ");
try {
n = kbd.nextDouble();
if (n >= 0 || n < 0)
check = true;
} catch (InputMismatchException ex) {
err.print("Invalid Data Type (not Numeric)");
}
if (check == true) {
if (n < 0)
System.out.println("Invalid value (too small)");
else
flag = true;
}
}
return n;
}
kbd.nextDouble does not consume new line characters, hence these will be repeatedly passed into the while loop.
In your catch block instead of just throwing an exception, you can pass kbd.nextLine() so that for the next loop your input method is ready.
catch(InputMismatchException ex)
{
System.out.println("Invalid Data Type (not Numeric)");
kbd.nextLine();
}
Here is the complete code for you:
double getInput(double n)
{
Scanner kbd = new Scanner( System.in );
boolean flag =false;
boolean check = false;
while(!flag)
{
System.out.println("Enter a number greater or equal to 1.0: ");
try
{
n = kbd.nextDouble();
if(n>=0 || n<0)check = true;
}
**catch(InputMismatchException ex)
{
System.out.println("Invalid Data Type (not Numeric)");
kbd.nextLine();
}**
if(check==true)
{
if(n<0)
System.out.println("Invalid value (too small)");
else
flag = true;
}
}
return n;
}
Reading a double value from the scanner wont read the end of line
n = kbd.nextDouble();
so the scanner object will have something to read unless you get the line ending calling
kbd.nextLine();
the logic point to do this exactly after the exception comes...
catch (InputMismatchException ex) {
System.err.print("Invalid Data Type (not Numeric)");
kbd.nextLine(); ///here!!!
}

Do-while loop not waiting for user input?

I'm sure this is something simple that I just can't spot, I have a do while loop prompting the user for an array size, which will be used for the rest of the program. If the user enters the right input, the program continues and works fine, but if the user enters the wrong input...
public static void main(String[] args)
{
// user enters up to 20 double values, stored in an array, user should enter 99999 to quit entering numbers. If user has not entered any numbers yet
// display an error message, otherwise, display each entered value and it's distance from the average
Scanner keyboard = new Scanner(System.in);
int arraySize = 0;
boolean isValid = false;
do
{
isValid = true;
arraySize = 0; // reset these values at start of each loop.
System.out.println("Enter an array size.");
try {
arraySize = keyboard.nextInt();
}
catch(NegativeArraySizeException mistake) {
System.out.println("Do not enter a negative number for the arrays size.");
System.out.println();
isValid = false;
}
catch(InputMismatchException mistake) {
System.out.println("Make sure to enter a valid number.");
System.out.println();
isValid = false;
}
} while (isValid == false);
If the user enters an invalid input, such as "red", the catch block kicks in and prints "Make sure to enter a valid number." and "Enter an array size." over and over without giving the user a chance to actually enter any input. I figured resetting the arraySize variable would fix it, but it doesn't. I guess the keyboard buffer has stuff in it, but no combination of empty printlns has worked so far.
I've heard that Exceptions shouldn't be used to validate user input. Why is that?
Regardless, it's not relevant to this question, as it is an exercise in Exception handling.
Without using isValid boolean variable and make simple code for input.
int arraySize = 0;
do {
System.out.println("Enter a valid array size.");
try {
arraySize = Integer.valueOf(keyboard.nextLine());
if (arraySize < 0) throw new NegativeArraySizeException();// for negative arry size
break;// loop break when got a valid input
} catch (Exception mistake) {
System.err.println("Invalid input: " + mistake);
}
} while (true);
You can add a keyboard.nextLine(); in the event of exception and it should resolve the issue.
try {
arraySize = keyboard.nextInt();
}
catch(NegativeArraySizeException mistake) {
System.out.println("Do not enter a negative number for the arrays size.");
System.out.println();
isValid = false;
keyboard.nextLine();
}
catch(Exception mistake) {
System.out.println("Make sure to enter a valid number.");
System.out.println();
isValid = false;
keyboard.nextLine();
}
Please see if this fix works for you. Scanner has a problem when you are trying to get the string from nextInt function. In this I have fetched the string and parsed to Integer and then handled the Number format exception
public static void main(String[] args) {
// user enters up to 20 double values, stored in an array, user should enter 99999 to quit entering numbers. If user has not entered any numbers yet
// display an error message, otherwise, display each entered value and it's distance from the average
Scanner keyboard = new Scanner(System.in);
int arraySize = 0;
boolean isValid = false;
do {
isValid = true;
arraySize = 0; // reset these values at start of each loop.
System.out.println("Enter an array size.");
try {
arraySize = Integer.parseInt(keyboard.next());
} catch (NegativeArraySizeException mistake) {
System.out.println("Do not enter a negative number for the arrays size.");
System.out.println();
isValid = false;
} catch (InputMismatchException mistake) {
System.out.println("Make sure to enter a valid number.");
System.out.println();
isValid = false;
} catch (NumberFormatException nfe) {
System.out.println("Make sure to enter a valid number.");
System.out.println();
isValid = false;
}
} while (isValid == false);
}
mmuzahid is almost there. But I added a way of checking negative number as well. Try this
Scanner keyboard = new Scanner(System.in);
int arraySize = 0;
boolean isValid = false;
do {
System.out.println("Enter a valid array size.");
try {
arraySize = Integer.valueOf(keyboard.nextLine());
if (arraySize < 0) {
System.out.println("Make sure to enter a valid positive number.");
} else {
break;
}
} catch (Exception mistake) {
System.out.println("Make sure to enter a valid number. Error:" + mistake);
}
} while (true);
Use keyboard.nextLine() and NumberFormatException
do {
// more code
try {
arraySize = Integer.valueOf((keyboard.nextLine()));
} catch (NegativeArraySizeException mistake) {
// more code
isValid = false;
} catch (InputMismatchException mistake) {
// more code
isValid = false;
} catch (NumberFormatException mistake) {
// more code
isValid = false;
}
} while (isValid == false);

Categories