Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Code problem  RSS feed

 
prerna boja
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,


I have the following program, I have to get the odd n even numbers out.

I ma getting an exception as :
Exception in therad "main" java.lang.NumberFormatException :For inputString
"The first data value is"
at OddEven.main<OddEven.java :17>



The data.in file contains the data as :
The first data value is
1066
The second data value is
1492
The third data value is
1939
The fourth data value is
1944
The fifth data value is
2000


Can you explain where am I wrong.
 
K Riaz
Ranch Hand
Posts: 375
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If that is the contents of your "data.in", then you are passing in a String which cannot be parsed to a float. You need to skip a line each time because your program is catching "The first data value is" as float, when you think your getting "1066".

Its not an ideal solution, but you need to do a "inFile.readLine();" before you do your float parsing (where you would to another "indline.readLine()", and then again in the loop.
[ April 16, 2005: Message edited by: Kashif Riaz ]
 
prerna boja
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I did the inFile.readLine() before the parsing the float.

inputString = inFile.readLine();
value = Float.valueOf(inputString).floatValue();
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, you must read two lines: skip the first, parse the second. Do this repeatedly.

The other option is to put the conversion into a try-catch block and ignore the line if it can't be parsed into a number. Put that inside the loop reading lines. This way your code will handle a file that isn't "text-num-text-num" but rather "text-num-num-text-num" or any other combination, but only if the assignment calls for it of course.

Also, why are you parsing the numbers as float when the file clearly has integers and you're casting the float to an int before adding to the sum anyway. You lose any decimal portion that may have been there, so why parse it as float in the first place?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!