Possible Duplicate:
Java: Scanner stopping at new line
I’m new to programming and I was wondering if there is a way to identify when there is a new line in a Scanner. My method is supposed to take a Scanner of a text file and break the line if it is over 60 characters long without breaking it in the middle of a word.
The problem I’m having is since I’m going by each token my code doesn’t account for lines that are less than 60 characters and appends them onto the previous line up to 60 characters.
This is the method I have created:
public static void wordWrap3(Scanner s) {
String k = "";
int length = 0;
while(s.hasNext()) {
k = s.next();
length = length + k.length() + 1;
if (length>60) {
System.out.print("\n");
length = 0;
}
System.out.print(" " + k);
}
}
This is the text I am using:
We're no strangers to love, You know the rules and so do I,
A full commitment's what Im thinking of, You wouldn't get this from any other guy.
I just wanna tell you how I'm feeling, Gotta make you understand.
Never gonna give you up, Never gonna let you down, Never gonna run around and desert you.
Never gonna make you cry, Never gonna say goodbye, Never gonna tell a lie and hurt you.
You seem to be saying that you want to word wrap each line separately. If so, the simple solution is to split the input into lines, and then create a scanner for each line and pass that to your existing
wordWrap3method.