# Thread: How can I determine the type of an input

1. ## 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 :
Java 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.
Last edited by QJack; 03-17-2010 at 03:30 PM.

2. Integer.parseInt("1234")

3. hi

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

Java 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.

4. when you are accepting vis scanner use this method ...it will accept only integer.No need to have checking method for int.
nextInt()
hasNextInt()

5. Alright, thank u all! That was helpful.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•