【问题标题】:Read text file with scanner and insert line break every 10 characters使用扫描仪读取文本文件并每 10 个字符插入换行符
【发布时间】:2017-06-01 20:18:04
【问题描述】:

在进行 java 练习时遇到问题,我需要从文本文件中获取输入并将内容打印出来,但每 10 个字符插入一个新换行符,例如它应该读入: 我喜欢吃冰淇淋

作为

我喜欢 吃冰块 团队

这是我目前的解决方案

public class practice {

public static void main(String[] args) {
Scanner input = new Scanner (practice.class.getResourceAsStream("hello.txt"));
String currentLine = "";
String lineTen = "\n";
int charCount = 0;

while (input.hasNext()) {
    currentLine =  input.nextLine();
    System.out.println(currentLine);
    //charCount++;
    for (int i = 0; i < currentLine.length(); i++) {
        if (currentLine.charAt(i) !=  ' ' && currentLine.charAt(i) != '\n') 
        {
            charCount++;
        }
        if (charCount > 20) {
        currentLine = ("\n");
        }
        }
    }
    System.out.println(currentLine);
    System.out.println(charCount);
}
}

任何建议将不胜感激。

【问题讨论】:

  • currentLine = ("\n"); 将整行设置为新行,因此任何超过 20 个字符的字符串都将打印为新行。同样在您的问题中,您说了 10 个字符,但您的代码计为 20 个字符。您也没有重置 charCount ,因此一旦达到 20 个字符,之后的每个字符都会触发 if 语句

标签: java text java.util.scanner


【解决方案1】:

如果您在示例中计算空格,为什么要排除空格?您应该在代码中删除它,您可以构建一个字符串,然后在其完成时打印它,如下所示:

try (Scanner input = new Scanner(new File("test.txt"))) {
        String currentLine = "";
        String result = "";
        int charCount = 0;
        while (input.hasNext())
            currentLine += input.nextLine() + " ";
            //charCount++;
        for (int i = 0; i < currentLine.length(); i++) {
            if (currentLine.charAt(i) != '\n') { 
                if (charCount >= 20) {
                    result+= "\n" + currentLine.charAt(i);
                    charCount = 1;
                }
                else {
                    result += currentLine.charAt(i);
                    charCount++;
                }
            }
            else
                charCount++;
        }
        System.out.println(result);
    }

也可以使用try-with-resources,如上面的代码所示。

输入:

I like to eat ice cream

输出:

I like to eat ice cre
am 

【讨论】:

    猜你喜欢
    • 2012-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-04
    相关资源
    最近更新 更多