• Post Reply Bookmark Topic Watch Topic
  • New Topic

Java, read text from file and break it into lines  RSS feed

 
xayda cadic
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm writing a code that read a text from a file and then sort it into lines of max specific width.

Example: a text that contains "aaaa bbbb cccc dddd"

specified width is 16

so the output should be

aaaa bbbb cccc //width is only 14, if dddd is added, it would be longer than 16.

dddd

My approach: read the text and assign it to a string

Although it compiles. But the file doesn't show any output. I think my code is not right. I know there is options for stringbuild, string split, array. But i'm now allowed to do that.
 
Ramesh Pramuditha Rathnayake
Ranch Hand
Posts: 178
2
Java MySQL Database Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In 11th line it should be str = str + " " + s;

And after first loop, you assign s="";. That means, s.length()=0
Therefore the if statement in second loop are actually useless. I can't understand, what you are going to do in that if statement..
 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

xayda cadic wrote: . . . aaaa bbbb cccc //width is only 14, if dddd is added, it would be longer than 16. . . .
Surely that width is 15?
I think you should stop coding altogether. Write down on paper how you intend to do it. Also consider how you are adding the space.
Forget about writing to a file for the time being. Simply display your output on System.out and think about file writing later when you are sure it works.
You appear to be using next() twice; that means you will miss out every other token.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!