这个程序我看不出怎么能规定每行都是60.请大神指点(两天干坐没想出来)
//Report some basic information about a file
import java.io.*; //for File
import java.util.*;
public class test1 {
public static void main(String [] args)throws
FileNotFoundException {
String filename ="old.txt";
wordWrap3(filename);
}
public static void wordWrap3(String filename) throws File
NotFoundException {
int maxLineLength = 60;
Scanner input = new Scanner(new File(filename));
while (input.hasNextLine()) {
String line = input.nextLine();
while (line.length() > maxLineLength) {
// find the nearest token boundary
int index =maxLineLength;
while (!Character.isWhitespace(line.charAt(index))) {
index--;
}
String first = line.substring(0, index + 1);
System.out.println(first);
line = line.substring(index + 1);
}
System.out.println(line);
}
}
}
这是个自动换行的程序,自动换行的同时,不会把一个单词分成两半,我们假设单词之间都用空格分隔,而且所有单词长度小于60。
原文档:
consisting of people with cerebral palsy, polio, and permanent spinal cord injuries. A few sat inwheelchairs, some leaned on crutches, and still some limped around with their heads and hands turning and wringing at odd angles. They could create an attraction unique in its own! But each and every one of them wore
处理后:
consisting of people with cerebral palsy, polio, and
permanent spinal cord injuries. A few sat in wheelchairs,
some leaned on crutches, and still some limped around with
their heads and hands turning and wringing at odd angles.
They could create an attraction unique in its own! But each
and every one of them wore
我认为:按程序代码的理解,每行的读取和处理输出 都和下一行的处理输出没有关系,那应该不可能输出每行都保证60字符以内,。
我脑海中有这样一个形象:好比卖肉的在切猪肉,你每给他一条猪肉,他都按60来切切切,每切好一小块之后,都丢到屏幕上,全部丢完再接下一条,而且他不看屏幕,只埋头切。。。
我认为应该出这样的结果:
consisting of people with cerebral palsy, polio, and
permanent spinal cord injuries. A few
sat in wheelchairs, some leaned on crutches, and still
some limped around with their heads
。。。。
为什么为什么为什么,表示很纠结,求大神指导
------解决方案--------------------
楼主,你确定你的原文档每行之间都有换行符么?
是不是你看起来换行的地方,其实只是你的写字板或者记事本自动换行
其实真实的文档本来就是一行