2012-05-14 82 views
1

问题:编写一个名为wordWrap的方法,接受一个表示输入文件的扫描器作为其参数,并将该文件的每一行输出到控制台,对所有长度超过60个字符的行进行换行。例如,如果一行包含112个字符,则该方法应将其替换为两行:一行包含前60个字符,另一行包含最后52个字符。将含有217个字符线应该被包裹成四行:3长度60和长度的最后一行的37使用扫描器处理字符串

我的代码:

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(); 
     } 

    } 
} 

问题在输出:

预期输出:

 
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 

产生的输出:

 
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 

如果我做错????

+1

是不是更容易循环输入的行(扫描仪),检查它是否超过60个字符,打印第一个60(或更少),从字符60的子字符串到结束,并且重复,直到长度为0? – Hidde

回答

0

else条件(正好60个字符行),你只从内for环断裂,而要从外while环路(和断裂,因此,你最终写出相同的线60次)。

请改用break superOuter,因为对于少于59个字符的行,请使用break superOuter