java - 避免输出用户输入的第一行

java - avoid outputting first line that is inputted by user

所以我正在尝试创建一个程序,该程序读取用户输入并仅在当前行小于前一行时才输出当前行。我的程序工作正常,但它一直打印我输入的第一行,这应该是无效的,因为还没有其他行可以与之比较。

想知道有没有办法让程序考虑第一行 但不输出给用户?感谢您的帮助!

public static void doIt(BufferedReader r, PrintWriter w) throws IOException {
    ArrayList<String> strings = new ArrayList<>();
    String line;
    while((line = r.readLine()) != null) {
        boolean checkIfSmaller = true;
        strings.add(line);
        for (int i = 0; i < strings.size()-1; i++) {
            if (line.compareTo(strings.get(i)) >= 0) {
                checkIfSmaller = false;
            }
        }

        if (checkIfSmaller) {
            w.println(line);
        }
    }
}

想法是在检查较小的行后将行添加到列表,因为将行与自身进行比较没有意义。此外,您所做的比较不正确 IMO:

public static void doIt(BufferedReader r, PrintWriter w) throws IOException {
    ArrayList<String> strings = new ArrayList<>();
    String line;
    while((line = r.readLine()) != null) {
        boolean isSmaller = false;
        for (int i = 0; i < strings.size()-1; i++) {
            if (line.compareTo(strings.get(i)) < 0) {
                isSmaller = true;
                break;
            }
        }
        strings.add(line);
        if (isSmaller) {
            w.println(line);
        }
    }
}

试试下面的代码,

public static void doIt(BufferedReader r, PrintWriter w) throws IOException {
    ArrayList<String> strings = new ArrayList<>();
    String line;
    boolean checkIfSmaller = false;
    while((line = r.readLine()) != null) {
        if (checkIfSmaller) {
            w.println(line);
        }
        checkIfSmaller = false;
        strings.add(line);
        for (int i = 0; i < strings.size()-1; i++) {
            if (strings.get(i).compareTo(line) >= 0) {
                checkIfSmaller = true;
            }
        }
    }
}

您不必维护所有先前字符串的列表。只维护到目前为止遇到的最小字符串就足够了。基于这个逻辑,代码可以即兴创作如下

public static void doIt(BufferedReader r, PrintWriter w) throws IOException {
        String line;
        String smallestLineSoFar = null;
        while ((line = r.readLine()) != null) {
            if (smallestLineSoFar == null) {
                // this case is for first line
                smallestLineSoFar = line;
            } else if (line.compareTo(smallestLineSoFar) < 0) {
                smallestLineSoFar = line;
                w.println(line);
            }
        }
    }