| Author |
Integer.parseInt(String)
|
Bindu Lakhanpal
Ranch Hand
Joined: Oct 17, 2008
Posts: 163
|
|
This is my own practice code.
But i could not understand why i get this output.Why there is NumberFormatException in line1
output:
Enter age
23
23
Exception in thread "main" java.lang.NumberFormatException: For input string: "2
"
at java.lang.NumberFormatException.forInputString(NumberFormatException.
java:48)
at java.lang.Integer.parseInt(Integer.java:456)
at java.lang.Integer.parseInt(Integer.java:497)
at exc.Test.main(Test.java:28)
|
 |
Balu Sadhasivam
Ranch Hand
Joined: Jan 01, 2009
Posts: 874
|
|
This all sounds problem inviting. You got readLine() method in BufferedReader which directly returns your String.
check readLine()>
|
 |
Bindu Lakhanpal
Ranch Hand
Joined: Oct 17, 2008
Posts: 163
|
|
Thanks,readLine() worked very well.
But i was just testing read() method in this program.
String p is printing alright.Then what could be the problem parsing it to int.
|
 |
Balu Sadhasivam
Ranch Hand
Joined: Jan 01, 2009
Posts: 874
|
|
String p is printing alright.Then what could be the problem parsing it to int.
Add SOPs inside the loop and see what each character it prints. char[] array is of size 3 , check out what is n.length() and check for any special characters in the final String ( space may be misleading when you print like that )
|
 |
Bindu Lakhanpal
Ranch Hand
Joined: Oct 17, 2008
Posts: 163
|
|
Yes, you are right. The space in end is the problem.
I changed the code as suggested by you.
See the outputs.
outputs:C:\IOEX\classes>java exc.Test
Enter age
456
456
4
5
6
Error
C:\IOEX\classes>java exc.Test
Enter age
56
56
5
6
Exception in thread "main" java.lang.NumberFormatException: For input string: "5
"
at java.lang.NumberFormatException.forInputString(NumberFormatException.
java:48)
at java.lang.Integer.parseInt(Integer.java:456)
at java.lang.Integer.parseInt(Integer.java:497)
at exc.Test.main(Test.java:32)
So,using trim() made the code run.
|
 |
Balu Sadhasivam
Ranch Hand
Joined: Jan 01, 2009
Posts: 874
|
|
Oh great . I like the way people work out their own code and find issues just by guiding them.
|
 |
Bindu Lakhanpal
Ranch Hand
Joined: Oct 17, 2008
Posts: 163
|
|
yes,thank you so much.
I am out of touch from core concepts for almost 2 months.
And i have forgotten so much. .
Now i understand why Arulk always says" keep applying what you have learnt in the certification result forum.
I hope ranchers here will help me just like you did.
Thanks again.
|
 |
 |
|
|
subject: Integer.parseInt(String)
|
|
|