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

Reading an integer from a txt file  RSS feed

 
Mark Lockery
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Would anyone be able to tell me how to read an int from the beginning of a txt file, i managed to write one, but it is written as a string (does that make a difference?), but i can't figure out how to read an integer from that file. Any help would be appreciated but please don't point me to a website unless it's perfect for this, i've looked at about 20 and not got anywhere.


Alternatively, if anyone could tell me why this code here doesn't work that would be very helpful.



It prints "Record is: 11", and that is all.
It has record being 11 but then it doesn't enter the if statement, i'm confused.

thanks.
[ October 08, 2004: Message edited by: Mark Lockery ]
 
Mani Ram
Ranch Hand
Posts: 1140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Mark Lockery:
Would anyone be able to tell me how to read an int from the beginning of a txt file, i managed to write one, but it is written as a string (does that make a difference?), but i can't figure out how to read an integer from that file. Any help would be appreciated but please don't point me to a website unless it's perfect for this, i've looked at about 20 and not got anywhere.


You can't read the contents of a file as an integer if you are using FileReader. But you can read the content as a String and convert it into an integer by using Integer.parseInt() method.
Or you can use the readInt() method if you are using DataInputStream or RandomAccessFile.


Alternatively, if anyone could tell me why this code here doesn't work that would be very helpful.

That is because you are using '==' instead of using equals() method. Change the if() check as
 
Mark Lockery
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much, it's now all good
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!