我是编程的新手,我想知道是否有办法确定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.
答案 0 :(得分:0)
你似乎在说你想分别对每一行进行自动换行。如果是这样,简单的解决方案是将输入拆分为行,然后为每行创建一个扫描程序并将其传递给现有的wordWrap3
方法。
答案 1 :(得分: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);
}
}
当然可以进一步改进。