Take only Integer input from user in Java
Hey Everyone! In this article, we will learn about how to accept only Integer input from user in Java. So let’s get started.
There are several ways in which we can prompt the user the input only integer value in Java. Let’s go through them one by one.
1. In this way, we enclose the user input block in try-catch and if the user tries to enter any value other than an Integer, the user is again prompted to enter an integer value.
If you don’t know try-catch you can take a look at this: Java Exceptions, Errors, Exception Handling in Java
package program5; import java.util.Scanner; public class Program5 { public static void main(String[] args) { int n=0; boolean flag; do { try { Scanner sc = new Scanner(System.in); System.out.println("Enter integer value only "); n=sc.nextInt(); flag=false; } catch(Exception e) { // accept integer only. System.out.println("Enter only integer value.."+e); flag=true; } } while(flag); System.out.println("The Integer Value Entered is "+n); } }
Output:-
run: Enter integer : w Enter only integer value..java.util.InputMismatchException Enter integer : xyz Enter only integer value..java.util.InputMismatchException Enter integer : 9.23 Enter only integer value..java.util.InputMismatchException Enter integer : 13 The Integer Value Entered is 13
parseInt() method to convert the String into Integer Data Type
package program5; import java.util.Scanner; public class Program5 { public static void main(String[] args) { boolean flag; String n; do { System.out.println("Enter Integer Value only"); Scanner sc = new Scanner(System.in); n = sc.next(); try { Integer.parseInt(n); flag=false; } catch(NumberFormatException e) { System.out.println("Enter only integer value"); flag=true; } }while(flag); System.out.println("Integer value is "+n); } }
Output:-
Enter Integer Value only a Enter only integer value Enter Integer Value only 12 Integer value is 12
I hope you have the above article was useful to you. If any doubts/suggestions leave a comment down below.
What if we would like to extract integers only from a longer input?
E.g.
Input:
“I am 18 year old”
Output:
18
Thanks in advance!