2012-05-14 135 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