使用扫描仪处理字符串

时间:2012-05-14 09:51:31

标签: java

问题:编写一个名为wordWrap的方法,它接受一个表示输入文件作为参数的扫描器,并将文件的每一行输出到控制台,自动换行超过60个字符的所有行。例如,如果一行包含112个字符,则该方法应将其替换为两行:一行包含前60个字符,另一行包含最后52个字符。包含217个字符的一行应包装成四行:三行长度为60,最后一行长度为37。

我的代码:

public void wordWrap(Scanner input) {

    while(input.hasNextLine()){
        String line=input.nextLine();
        Scanner scan=new Scanner(line);
        if(scan.hasNext()){
            superOuter:
            while(line.length()>0){

                for(int i=0;i<line.length();i++){
                    if( i<60 && line.length()>59){
                        System.out.print(line.charAt(i));

                    }
                    //FINISH OFF LINE<=60 characters here

                    else if(line.length()<59){

                        for(int j=0;j<line.length();j++){
                            System.out.print(line.charAt(j));

                        }
                        System.out.println();

                        break superOuter;
                    }
                    else{
                        System.out.println();

                        line=line.substring(i);

                        break ;
                    }


                }

            }
        }
        else{
            System.out.println();
        }

    }
}

输出中的问题:

预期输出:

Hello
How are you
The quick brown fox jumps over the lazy dog the quick brown 
fox jumps over the lazy dog
I am fine

Thank you
The quick brown fox jumps over the lazy dog the quick brown 
fox jumps over the lazy dog
The quick brown fox jumps over the lazy dog the quick brown 
fox jumps over the lazy dog

The quick brown fox jumps over the lazy dog the quick brown 
fox jumps over the lazy dog
The quick brown fox jumps over the lazy dog the quick brown 
fox jumps over the lazy dog
The quick brown fox jumps over the lazy dog the quick brown 
fox jumps over the lazy dog

This line is exactly sixty characters long; how interesting!

Goodbye

制作输出:

Hello
How are you
The quick brown fox jumps over the lazy dog the quick brown 
fox jumps over the lazy dog
I am fine

Thank you
The quick brown fox jumps over the lazy dog the quick brown 
fox jumps over the lazy dog
The quick brown fox jumps over the lazy dog the quick brown 
fox jumps over the lazy dog

The quick brown fox jumps over the lazy dog the quick brown 
fox jumps over the lazy dog
The quick brown fox jumps over the lazy dog the quick brown 
fox jumps over the lazy dog
The quick brown fox jumps over the lazy dog the quick brown 
fox jumps over the lazy dog

This line is exactly sixty characters long; how interesting!This line is exactly sixty characters long; how interesting!This line is exactly sixty characters long; how interesting!...
*** ERROR: excessive output on line 13

我哪里做错了????

1 个答案:

答案 0 :(得分:0)

else条件下(对于正好为60个字符的行),您只是从内部for循环中断开,而您想要从外部while循环中断(和因此,你最终写出相同的60次线。)

请使用break superOuter代替少于59个字符的行。