i want to pass an integer value as an input, for that first i have to get the value as an string and then convert it into an Integer. i wrote the code and it looked like this ..

String age="";
int intage=0;
       System.out.print("Please Enter your age : ");
               
        try{
            age= dataIn.readLine();
            intage=Integer.parseInt(age);
        }catch( IOException e ){
            e.printStackTrace();
        }

but my problem here is that when i enter a String like "dfjdkdjre" , as input , i get an error or rather an exeption.. how do i prevent this ... can i display an error message or ??

can some one help me complete my code .. please :(

and could some one tell me what does this line do...

e.printStackTrace();

please help me .. i am kind of lost in this :(

e.printStackTrace()

is used for "tracing" where your exception occurred. It is useful to the programmer for debugging, but useless to the end user. Try validating your input before you parse it to an integer. If you catch that exception you get from

intage=Integer.parseInt(age);

you can handle it accordingly.

e.printStackTrace()

is used for "tracing" where your exception occurred. It is useful to the programmer for debugging, but useless to the end user. Try validating your input before you parse it to an integer. If you catch that exception you get from

intage=Integer.parseInt(age);

you can handle it accordingly.

it didnt work, i get an error when i type a string like " hhfdh "; it works for numbers but not for string ...

it didnt work, i get an error when i type a string like " hhfdh "; it works for numbers but not for string ...

I don't know what you did, but you perhaps aren't catching a NumberFormatException. IOException won't catch the error you are referring to. parseInt throws a NumberFormatException in the situation you are referring to. If you are only catching IOException, you are going to get an error.
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Integer.html#parseInt(java.lang.String)

You can try like this

Buffered reader tast=new BufferedReader( new InputStreamreader(System.in));
     String age="";
     age=tast.readLine();
     intage=Integer.parseInt(age);
Comments
read before you post

You can try like this

Buffered reader tast=new BufferedReader( new InputStreamreader(System.in));
     String age="";
     age=tast.readLine();
     intage=Integer.parseInt(age);

They already have that. If you actually read the thread they were having trouble with an exception.

but my problem here is that when i enter a String like "dfjdkdjre" , as input , i get an error or rather an exeption.. how do i prevent this ... can i display an error message or ??

by making sure to use only valid input..
or, just by replacing

e.printStackTrace();

by

System.out.println(age + " is not a valid Integer.");
This article has been dead for over six months. Start a new discussion instead.