【发布时间】:2012-12-05 06:42:59
【问题描述】:
我是编程新手,我想知道是否有办法识别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.
【问题讨论】:
-
我不清楚 - 你是想把 existing 行也放在一起,还是只是 insert 换行符?如果是后者,只需使用
nextLine()一次读取一行... -
所以你想在 60 个字符后添加一个换行符?
-
嗯……你是不是想搞 rickroll SO? :-)
-
我正在尝试插入现有的换行符。我一次读一行时遇到的问题是它仍然在单词中间中断。这就是为什么我是通过令牌阅读的原因