• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Reading and displaying Strings from a file

 
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have 2 different sets of code below which yield different results for the same input. Though I understand the flow, I would like a more "Formalized/Academic" description of whats happening ...

THE INPUT FILE "income.txt"(contains the following 3 strings as they appear i.e on 3 diff lines):

This is Test1
This is Test2
This is Test3

The first code :



This gives the intended result.
Output:
This is Test1
This is Test2
This is Test3

The second code:



The output is:
This is Test2


As sought before I would like a formal description as to why the difference in output between the two pieces of code.
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
"A formal description?" This isn't exactly a theoretical problem You do have to realize that every time you call readLine(), you get the next line of the file; that line won't be returned again.

In the second version of this program, in the condition of the while loop, you read a line from the file, but don't use it for anything. In the body of the loop, you read another line and append it to a StringBuffer. So the first, third, fifth... and all odd-numbered lines of the file will be discarded.

In the first version, the line you read in the while condition is the one you append to the StringBuffer.
 
shank ram
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for the response Friedman (and for that rap too!! ).

I just wanted a bookish explanation .. which turned to be a (important !?) property of readLine() method as explained by you.

I am sure the second piece of code as a question is good enough for any of the preliminary cert tests, what say?
 
It's exactly the same and completely different as this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic