How to check that console input should be integer only?
Hi there,
I'm fairly new to java and am trying to validate user input to ensure what is entered is an integer.
so I have.....
int value = Keyboard.readInt();
I'd like a loop of somesort that can check whether the input was an integer, as oppose to a float.
Any ideas how you can do this? (baring in mind I'm still a beginner and am not familiar with more advanced ways to solve this problem).
Many thanks
Re: How to check an input is an integer as oppose to a float
Hello Konnor and welcome to the Java Programming Forums :)
Here is a simple method for you:
Code :
import java.util.Scanner;
public class Konnor {
public static void main(String[] args){
System.out.println("Enter Integer Value: ");
Scanner sc = new Scanner(System.in);
try {
int myInt = Integer.parseInt(sc.next());
System.out.println("Integer value is: " + myInt);
}
catch(NumberFormatException e) {
System.out.println("You have not entered an Integer!");
}
}
}
This uses the Scanner class to take user input from the console and then it tries to parse the given value to Integer.
A try/catch block catches any exceptions which are generated when a non Integer value is entered.
Re: How to check an input is an integer as oppose to a float
Thanks for that.
I'll have a look online and try to understand whats going on.
Re: How to check an input is an integer as oppose to a float
Hey Konnor,
Glad I could help...
Check out the Sun Java Tutorials:
Lesson: Exceptions (The Java™ Tutorials > Essential Classes)
The try Block (The Java™ Tutorials > Essential Classes > Exceptions)
Basically when there is an error, this is called an 'exception'. You can catch these exceptions in a try/catch block.
In the above code, when the code cannot parse the given value as an Integer, an error is generated. We have created the try/catch block to catch the NumberFormatException error which then prints "You have not entered an Integer!"
When the given value is an actual Integer, no error is created so nothing goes to the catch part of the code.