# How can I determine the type of an input

• 03-17-2010, 03:00 PM
QJack
How can I determine the type of an input
What I mean is this :
I have to write a program that gets an integer and prints it on the screen. Otherwise, an error message should be printed.

EDIT :
So far what I have done is this :
Code:

```import java.util.Scanner; public class f{         public static boolean isItInt(String inp)         {                 char dgts[]={'0','1','2','3','4','5','6','7','8','9'};                 int i=0,j=0,count=0;                 for (i=0; i<inp.length(); i++)                 {                         for(j=0;j<dgts.length;j++)                                 if (inp.charAt(i)==dgts[j])                                         count++;                 }                 if (count==inp.length())                         return true;                 else                         return false;         }         public static void main(String argv[]){                 Scanner s = new Scanner(System.in);                 String p=s.next();                 System.out.println(p);                 boolean x=isItInt(p);                 System.out.println(x);         } }```
But I am sure there is something easier than this, so let me know.
• 03-17-2010, 04:01 PM
PhHein
Integer.parseInt("1234")
• 03-17-2010, 04:08 PM
j2me64
hi

Quote:

Originally Posted by QJack
But I am sure there is something easier than this, so let me know.

in java when a number format convertion goes wrong then a exception is thrown. so try this peace of code

Code:

```public class ExceptionExample {         public static void main(String[] args) {                 String str = "10000";                 try {                         System.out.println(Long.parseLong(str));                 } catch (NumberFormatException nfe) {                         System.out.println("NumberFormatException occured ");                         nfe.printStackTrace();                 }         } }```
run the code with different str values to see what happens.
• 03-17-2010, 04:11 PM
RamyaSivakanth
when you are accepting vis scanner use this method ...it will accept only integer.No need to have checking method for int.
nextInt()
hasNextInt()
• 03-18-2010, 11:22 AM
QJack
Alright, thank u all! That was helpful.