【问题标题】:Java: scanner not scanning complete linesJava:扫描仪未扫描完整行
【发布时间】:2012-09-04 16:30:54
【问题描述】:

我有以下文本文件(不是 java 文件)

/*START OF CHANGES TO CODE*/
public class method1 {

    public static int addTwoNumbers(int one, int two){
        return one+two;
    }

    public static void main (String[] args){
        int total = addTwoNumbers(1, 3);
        System.out.println(total);
    }
}
/*END OF CHANGES TO CODE*/

我正在尝试使用以下代码来读取文件

String editedSection = null;
boolean containSection = false;
Scanner in = new Scanner(new FileReader(directoryToAddFile));
while(in.hasNextLine()) {
    if(in.nextLine().contains("/*START OF CHANGES TO CODE*/")) {
        containSection = true;
        editedSection = in.nextLine().toString();
    } else if (containSection == true) {
        editedSection = editedSection+in.nextLine().toString();
    } else if (in.nextLine().contains("/*END OF CHANGES TO CODE*/")) {
        containSection = false;
        editedSection = in.nextLine().toString();
    }
    in.nextLine();
}

所以基本上我想要它做的是读取一个文件直到它看到/*START OF CHANGES TO CODE*/,然后开始将它之后的每一行添加到一个字符串直到它到达/*END OD CHANGES TO CODE*/。但是当它读取行时,它会忽略一些行和其他部分。有人知道怎么做吗?

【问题讨论】:

    标签: java java.util.scanner


    【解决方案1】:

    您在 while 循环中调用了 in.nextLine() 很多 次。这听起来对我来说是一个非常糟糕的主意。每次迭代将执行多少次取决于它进入了哪些位......讨厌。

    我建议你使用

    while(in.hasNextLine()) {
        String line = in.nextLine();
        // Now use line for the whole of the loop body
    }
    

    这样您就不会为了检查而阅读它们而意外跳过行。

    【讨论】:

    • 这正是问题所在,我什至没有想到它会在我调用它时移到下一行......干杯:)
    猜你喜欢
    • 1970-01-01
    • 2021-05-25
    • 1970-01-01
    • 1970-01-01
    • 2015-05-02
    • 2013-11-15
    • 2017-05-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多