java - 以不区分大小写的顺序输出文本

所以我是java新手,目前正在学习如何读取文本文件。我正在尝试构建一个程序,一次从用户那里读取一行输入,当我按 ctrl + z 时,它应该以不区分大小写的排序顺序输出所有行。我对如何使用集合有点困惑,我尝试遵循我在网上找到的类似示例。但是,当我运行程序时,它只输出我输入的任何内容,而不对任何内容进行排序。我究竟做错了什么?


public static void doIt(BufferedReader r, PrintWriter w) throws IOException {

    List<String> listStrings = new ArrayList<>();

    String line;

    while((line = r.readLine()) != null) {

        listStrings.add(line);

    }


    Collections.sort(listStrings);


    Collections.sort(listStrings, String.CASE_INSENSITIVE_ORDER);


    Collections.sort(listStrings, Collections.reverseOrder());


    Collections.sort(listStrings, String.CASE_INSENSITIVE_ORDER);


//  Collections.reverse(listStrings);


    for (String text: listStrings) {

        w.println(text);

    }

}


温温酱
浏览 143回答 1
1回答

绝地无双

您的任何Collections._____()调用都不会打印任何内容。它们只是对底层集合(listStrings)进行操作。因此,在每个步骤之后,您期望最终得到的结果如下://listStringsCollections.sort(listStrings);//listStrings sorted alphabetically, case sensitiveCollections.sort(listStrings, String.CASE_INSENSITIVE_ORDER);//listStrings sorted alphabetically, case insensitiveCollections.sort(listStrings, Collections.reverseOrder());//listStrings sorted alphabetically in reverse order, case insensitiveCollections.sort(listStrings, String.CASE_INSENSITIVE_ORDER);//listStrings sorted alphabetically, case insensitiveCollections.reverse(listStrings);//listStrings sorted alphabetically in reverse order, case insensitive最后,在对 进行所有这些更改后listStrings,您尝试打印该集合。您在这里遇到的问题是,您实际上并没有刷新输出流,这可能是缓冲的。因此,不会打印任何内容。我重写了您的代码,使其具有完全相同的效果listStrings,并打印输出,如下所示:public static void doIt(BufferedReader r, PrintWriter w) throws IOException{&nbsp; &nbsp; List<String> listStrings = new ArrayList<>();&nbsp; &nbsp; String line;&nbsp; &nbsp; while((line = r.readLine()) != null)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; listStrings.add(line);&nbsp; &nbsp; }&nbsp; &nbsp; Collections.sort(listStrings, String.CASE_INSENSITIVE_ORDER.reversed());&nbsp; &nbsp; for(String text : listStrings)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; w.println(text);&nbsp; &nbsp; }&nbsp; &nbsp; w.flush();}我从我的 main 方法中调用它,如下所示:public static void main(String[] args) throws Exception{&nbsp; &nbsp; doIt(new BufferedReader(new InputStreamReader(System.in)), new PrintWriter(System.out));}这是最终的效果:输入:ABCDbcdefeghijkl输出:ijklfeghbcdeABCD
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java