2012-12-05 89 views
0

可能重复:
Java: Scanner stopping at new line识别扫描仪新线

我新的编程,我想知道如果有一种方法来识别时,有一个新的在Scanner行。我的方法应该采用文本文件的Scanner,如果它超过60个字符长,并且不会将其中断,则会中断该行。

我遇到的问题是因为我要通过每个令牌,我的代码没有考虑少于60个字符的行,并将它们追加到上一行,最多60个字符。

这是我创建的方法:

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

这是我使用的文字:

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. 
+1

我不清楚 - 你是否试图将*现有的*行放在一起,或者只是*插入*换行符?如果是后者,只需使用'nextLine()'一次读取一行... –

+0

相关:http://stackoverflow.com/questions/10891511/java-scanner-stopping-at-new-line?rq= 1 – 2012-12-05 06:52:53

+0

所以你想在60个字符后放一个换行符? –

回答

0

你似乎是说,你要字分开装的每一行。如果是这样,简单的解决方案是将输入分成几行,然后为每一行创建一个扫描器并将其传递给现有的wordWrap3方法。

+0

阅读您是否说我应该创建另一台扫描仪,然后从前一台扫描仪一次将该扫描仪传出一行?即时通讯使用一个网站称为练习,所以我所有的控制权是方法,而不是实际的程序。 –

+0

是的。我是这么说的。如果你受到限制,你的代码必须进入该方法,那么你需要以不同的方式组织它,但基本逻辑应该是相同的。 –

0

你可以试试:

String fileLine = ""; 
while(s.hasNextLine()) { 
    fileLine = s.nextLine(); 
    if(fileLine.length() > 60) 
    { 
     while (fileLine.length() > 60) 
     { 
      String tempStr = fileLine.substring(0, 60); 
      int rightIdx = tempStr.lastIndexOf(' '); 
      String firstStr = tempStr.substring(0, rightIdx); 
      String secStr = fileLine.substring(rightIdx + 1, fileLine.length()); 
      System.out.println(firstStr); 
      //if still it is big 
      if(secStr.length() > 60) 
       fileLine = secStr; 
      else 
      { 
       System.out.println(secStr); 
       break; 
      } 
     } 
    } 
    else 
    { 
     System.out.println(fileLine); 
    } 
} 

ofcourse它可以进一步提高。

+0

我将如何实现这个为120个字符的行?我只是把if语句放在循环中吗? –

+0

更新了代码,并且可以进一步改进,我只是提供了一些帮助,而不是完全有效的代码 –