BufferedReader在java中阅读我的文件时每隔一行跳过一行

cbjzeqam  于 2023-03-28  发布在  Java
关注(0)|答案(4)|浏览(183)

所以我正在阅读一个包含约会的文件,我在代码的前面写了这些约会。我想筛选文本文件,找到某个日期的约会,并将它们添加到ArrayList中,但是当BufferedReader浏览它时,它会跳过其他行......这是我的代码

public ArrayList<String> read(int checkDay, int checkMonth, int checkYear) {
    ArrayList<String> events = new ArrayList<String>();
    BufferedReader in = null;
    String read;
    try {
        in = new BufferedReader(new FileReader("calendar.txt"));
        while ((read = in.readLine()) != null) {
            read = in.readLine();

            String[] split = read.split(",");
            System.out.println(read);

            if (split[1].equals(Integer.toString(checkDay)) && split[2].equals(Integer.toString(checkMonth)) && split[3].equals(Integer.toString(checkYear))) {
                events.add(split[0] + " : " + split[1] + "/" + split[2] + "/" + split[3]);
            }

        }
    } catch (IOException e) {
        System.out.println("There was a problem: " + e);
        e.printStackTrace();

    } finally {
        try {
            in.close();
        } catch (Exception e) {
        }

    }
    return events;
}
htrmnn0y

htrmnn0y1#

你阅读了两遍。

while ((read = in.readLine()) != null) { // here
            read = in.readLine();      // and here
e3bfsja2

e3bfsja22#

你在这里有错误:

while ((read = in.readLine()) != null) 
 read = in.readLine();

你应该在while.中保留read = in.readLine(),并删除另一行。

noj0wjuj

noj0wjuj3#

试试这个
你在while循环中使用了两次“read = in.readLine())”,这就是为什么它跳过了lome

public ArrayList<String> read(int checkDay, int checkMonth, int checkYear) {
        ArrayList<String> events = new ArrayList<String>();
        BufferedReader in = null;
        String read;
        try {
            in = new BufferedReader(new FileReader("calendar.txt"));
            while ((read = in.readLine()) != null) {

                String[] split = read.split(",");
                System.out.println(read);

                if (split[0].equals(Integer.toString(checkDay)) && split[1].equals(Integer.toString(checkMonth)) && split[2].equals(Integer.toString(checkYear))) {
                    events.add(split[0] + " : " + split[1] + "/" + split[2] + "/" + split[3]);
                }

            }
        } catch (IOException e) {
            System.out.println("There was a problem: " + e);
            e.printStackTrace();

        } finally {
            try {
                in.close();
            } catch (Exception e) {
            }

        }
        return events;
mec1mxoz

mec1mxoz4#

使用“next()”而不是“nextLine()”可以解决这个问题:

System.out.println("Enter Emp ID: ");
        eid = scanner.nextInt();

        System.out.println("Enter Emp Name:");
        ename = scanner.next();

        System.out.println("Enter Emp Salary:");
        esal = scanner.nextFloat();

        System.out.println("Enter Emp Address:");
        eaddr = scanner.next();

相关问题