• Post Reply Bookmark Topic Watch Topic
  • New Topic

Reading lines of ints from file with a sentinel  RSS feed

 
Ciaran Reid
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a text file with this:

65 78 65 89 25 98 -999
87 34 89 99 26 78 64 34 -999
23 99 98 97 26 78 100 63 87 23 -999
62 35 78 99 12 93 19 -999

the -999 at end of each line is my sentinel.
Output: sum of each line.
I can get it to read and output sum of 1st line but cant onto second line.
This is my 1st time posting a code qu up so if anyone helps me out, be gentle!
Here be my code





My output is:




Line 1: Total = 420
Line 2: Total = 420
Line 3: Total = 420
Line 4: Total = 420


The 420 value is the first lines total
The book im studying with has this as an example but doesnt give the proper code to properly try test it.
p.s. i am a total novice!!!
thanks
 
fred rosenberger
lowercase baba
Bartender
Posts: 12563
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I put 'code tags' around your java. that makes it much easier to read by preserving your indentation and color-highlighting various keywords.

Notice that line 10 is inside your for-loop. That means that each time you come around, you create a new Scanner/FileReader, which re-opens the file and re-points it back to the first line.

What you need to do is use the FileReader to loop through each line. THEN use your Scanner to parse each line as you go.



As a general note, hard-coding your for loop on the number of the lines in the file is a bad idea. What if you don't know how many lines the file will have? A better idea is to create your file reader outside the loop, then have a while-loop that continues until your FileReader returns 'no more lines'. if you search around, I'm sure you can find an example.
 
Campbell Ritchie
Marshal
Posts: 56545
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you are using a Scanner on the input, why don't you use the Scanner to read the files? You can use the hasNextLine() method for the continuation condition for the outer loop, and ((num = inScan.nextInt()) != -999) as the continuation condition for the inner loop.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!