Reputation: 239
Question: Write a method called wordWrap that accepts a Scanner representing an input file as its parameter and outputs each line of the file to the console, word-wrapping all lines that are longer than 60 characters. For example, if a line contains 112 characters, the method should replace it with two lines: one containing the first 60 characters and another containing the final 52 characters. A line containing 217 characters should be wrapped into four lines: three of length 60 and a final line of length 37.
My code:
public void wordWrap(Scanner input) {
while(input.hasNextLine()){
String line=input.nextLine();
Scanner scan=new Scanner(line);
if(scan.hasNext()){
superOuter:
while(line.length()>0){
for(int i=0;i<line.length();i++){
if( i<60 && line.length()>59){
System.out.print(line.charAt(i));
}
//FINISH OFF LINE<=60 characters here
else if(line.length()<59){
for(int j=0;j<line.length();j++){
System.out.print(line.charAt(j));
}
System.out.println();
break superOuter;
}
else{
System.out.println();
line=line.substring(i);
break ;
}
}
}
}
else{
System.out.println();
}
}
}
Problem in the output:
Expected output:
Hello How are you The quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog I am fine Thank you The quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog The quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog The quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog The quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog The quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog This line is exactly sixty characters long; how interesting! Goodbye
Produced Output:
Hello How are you The quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog I am fine Thank you The quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog The quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog The quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog The quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog The quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog This line is exactly sixty characters long; how interesting!This line is exactly sixty characters long; how interesting!This line is exactly sixty characters long; how interesting!... *** ERROR: excessive output on line 13
Where did i do wrong ????
Upvotes: 1
Views: 1916
Reputation: 125865
In the else
condition (for lines of exactly 60 characters), you are only breaking from the inner for
loop, whereas you want to break from the outer while
loop (and, therefore, you end up writing out the same line 60 times).
Use instead break superOuter
as you have for lines of less than 59 characters.
Upvotes: 0