Continue to get info from scanner in catch block [duplicate] - java

This question already has answers here:
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
(5 answers)
Closed 7 years ago.
I'm simply want to get a valid int value for age
But when user enters an string, why i cant get an int again?
Here is my code:
public static void getAge() throws InputMismatchException {
System.out.print("Enter Your age: ");
try {
age = in.nextInt();
} catch (InputMismatchException imme) {
System.out.println("enter correct value for age:");
in.nextInt(); // why this not works?
}
}
Enter Your age: hh
enter correct value for age:
Exception in thread "main" java.util.InputMismatchException
I want to request to enter a valid int value until a valid input enters.

If nextInt() fails to parse the input as an int, it leaves the input in the buffer. So the next time you call nextInt() it is trying to read the same garbage value again. You must call nextLine() to eat the garbage input before trying again:
System.out.print("Enter your age:");
try {
age = in.nextInt();
} catch (InputMismatchException imme) {
System.out.println("Enter correct value for age:");
in.nextLine(); // get garbage input and discard it
age = in.nextInt(); // now you can read fresh input
}
You probably want to arrange this in a loop too, so that it will keep asking repeatedly so long as the input is unsuitable:
System.out.print("Enter your age:");
for (;;) {
try {
age = in.nextInt();
break;
} catch (InputMismatchException imme) {}
in.nextLine();
System.out.println("Enter correct value for age:");
}

Related

java do while asked for input twice

why do I need to input 2 times? please help I'm new to java, can't find the error
do {
System.out.println("Enter your age: ");
age= in.nextInt();
if(!in.hasNextInt()) {
System.out.println("Please enter a valid age");
in.nextInt();
valid=false;
}
}while(valid);
I removed the do while but it still asks for the second input
System.out.println("Enter your age: ");
age= in.nextInt();
if(!in.hasNextInt()) { //Will run till an integer input is found
System.out.println("Please enter a valid age");
in.nextInt();
valid=false;
}
I have updated your code. This will work for you.
public class Example
{
public static void main(String[] args) {
boolean valid = true;
do {
Scanner in = new Scanner(System.in);
System.out.println("Enter your age: ");
while(!in.hasNextInt()) {
System.out.println("Please enter a valid age");
in.next();
valid = false;
}
int age = in.nextInt();
} while(valid);
}
}
Output :
Enter your age:
2
Enter your age:
seven
Please enter a valid age
seven
Please enter a valid age
3
Explanation : If you are giving valid data, then the loop will continue to take inputs (not taking inputs twice). As soon as, you give invalid data, then, the code will prompt you to enter the valid data and loop will stop executing as you made valid = false.
The reason why it asks you for input twice is due to you in.hasNextInt() which will check your scanner for input from the system. Since your system does not have any input due to you calling age = in.nextInt(); which will move the scanner to the next word before your in.hasNextInt(), The function in.hasNextInt() will require you to input something so that it can validate if it is an Int or not.
what we want to do, is to first check the current scanner's input if it has an integer before we either store it inside age or loop again and ask for new input.
A better way of checking would be to do something like this.
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int age = 0;
System.out.println("Enter your age: ");
while(!in.hasNextInt()){// checks if scanner's next input is an int, return true if next input is not an Int and the while loop continues till the next input is an Int
System.out.println("Please enter a valid age: ");
in.nextLine();//move the scanner to receive the next nextLine
//this is important so the hasNextInt() wont keep checking the same thing
}
//it will only exit the while loop when user have successfully enter an interger for the first word they inputted.
age = in.nextInt();
System.out.println("Your age is: " + age);
}
}
Output:
Enter your age:
boy
Please enter a valid age:
boy girl
Please enter a valid age:
5
Your age is: 5
Hi : D there is becuase of the !in.hasNextInt() it will cause you need to do the input again but you can change it to other condition like if the age is bigger than certain value.
public class stackTest {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int age =0 ;
boolean valid = false;
do {
System.out.println("Enter your age: ");
age= in.nextInt();
if(age>90) {
System.out.println("Please enter a valid age");
valid=true;
}
else valid=false;
}while(valid);
System.out.println("Age: " + age);
}
}
You should move the System.out.println("Enter your age: "); statement outside the do-while loop.

Using scanner to recognize both integers and strings, and stopping user input if a certain string is inputted [duplicate]

This question already has answers here:
How to type a string to end a integer Scanning process in Java
(3 answers)
Closed 2 years ago.
Trying to use scanner to recognize both integers and strings, and stopping user input if a certain string is inputted.
Scanner myObj = new Scanner(System.in);
System.out.println("Enter number of students");
int numberof = myObj.nextInt();
Need to make it so if the user types "end", the scanner no longer takes user input. I can't put the line int numberof = myObj.nextInt(); in a loop or something and limit the variable scope, as i'm using that value of numberof throughout the rest of my code.
You can use Scanner#next and then parse integers if needed. I wouldn't recommend just directly using Scanner#nextInt.
Scanner sc = new Scanner(System.in);
do {
System.out.println("Enter number of students");
String next = sc.next();
if (next.equals("end")) break;
else {
try {
int num = Integer.parseInt(next);
} catch (NumberFormatException e) {
System.out.println("Please enter a valid input");
}
}
} while (true);

How to validate that input to Scanner is an int?

System.out.println("Enter your age here:");
setAge(sc.nextInt());
How can I validate that users' age is not a char or a negative number?
Ideally, if the users input anything but an int, the program would ask for the input again.
I have tried using a do-while, but doesn't seem to be working.
I am a beginner. Any help is super appreciated.
Thanks!
What you are doing with sc.nextInt() will only allow the user to enter an int or the program will throw an InputMismatchException (thus that part behaves the way you want). If you want to make sure the number isn't negative though, do this:
System.out.println("Enter your age here:");
while (!sc.hasNextInt()) {
System.out.println("Please enter an integer.");
sc.next();
}
int age = sc.nextInt();
if(age < 0) {
//do what you want if the number is negative
//if you're in a loop at this part of the program,
//you can use the continue keyword to jump back to the beginning of the loop and
//have the user input their age again.
//Just prompt them with a message like "invalid number entered try again" or something to that affect
}
else {
setAge(age);
//continue execution
}
The following block will do what you need:
int age;
System.out.println("Please enter an integer");
while (true) {
try{
age= scan.nextInt();
if (age<=0) throw new Exception("Negative number");
break;
} catch(Exception e){
System.out.println("Please enter a positive integer");
}
scan.nextLine();
}
// below just call
setAge(age);
I hope this helps.

Using while loop as input validation [duplicate]

This question already has answers here:
Determine if a String is an Integer in Java [duplicate]
(9 answers)
user input check int only
(4 answers)
Closed 9 years ago.
I'm trying to use while loop to ask the user to reenter if the input is not an integer
for eg. input being any float or string
int input;
Scanner scan = new Scanner (System.in);
System.out.print ("Enter the number of miles: ");
input = scan.nextInt();
while (input == int) // This is where the problem is
{
System.out.print("Invalid input. Please reenter: ");
input = scan.nextInt();
}
I can't think of a way to do this. I've just been introduced to java
The issue here is that scan.nextInt() will actually throw an InputMismatchException if the input cannot be parsed as an int.
Consider this as an alternative:
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number of miles: ");
int input;
while (true) {
try {
input = scan.nextInt();
break;
}
catch (InputMismatchException e) {
System.out.print("Invalid input. Please reenter: ");
scan.nextLine();
}
}
System.out.println("you entered: " + input);
The javadocs say that the method throws a InputMismatchException if the input doesn;t match the Integer regex. Perhaps this is what you need?
So...
int input = -1;
while(input < 0) {
try {
input = scan.nextInt();
} catch(InputMismatchException e) {
System.out.print("Invalid input. Please reenter: ");
}
}
as an example.

Testing for blank input using Scanner class during input validation

I need to ask the user to enter a positive non-zero integer from the console that I will use as a product number in my program.
If I enter any non-integer value, the program correctly enters the while loop.
If I enter a 0 or a negative integer, the program correctly throws the exception (which I catch and handle elsewhere).
When I just press the enter key (or end of line character) it seems that the program just puts the console to another line. I want it to enter the while loop to display the error message. I think the cause is that hasNextInt() will wait until the token is a non end of line character input.
private static void validateProductNumber() throws InvalidProductNumberException {
Scanner keyboard = new Scanner(System.in);
int number;
while(!keyboard.hasNextInt()) {
System.out.println("Number must be an integer. Try again. ");
System.out.println("Enter a new number: ");
keyboard.next();
}
number = keyboard.nextInt();
if (number <= 0)
throw new InvalidProductNumberException();
newNumber = number;
}
Is there another way I can implement my input validation with Scanner class so that it works correctly for all situations?
You can change your loop as follows:
while(true) {
try {
System.out.println("Enter a new number: ");
//read the line and parse it
number = Integer.parseInt(keyboard.nextLine());
break; //break the loop if the input is a valid integer
} catch(Exception ex) {
//print the error message if the input is incorrect
System.out.println("Number must be an integer. Try again. ");
}
}
if (number <= 0)
//...

Categories

Resources