可能重复:
Java:扫描仪在换行处停止
我是编程新手,我想知道是否有办法识别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.