简体   繁体   English

如何在 java 中按字母顺序对列表进行排序?

[英]How to sort a list alphabetically in java?

So I'm trying to sort a list of names both alphabetically and reverse alphabetically.所以我试图按字母顺序和反向字母顺序对名称列表进行排序。 The user would enter a list of names and once a blank entry is recorded, the program would sort the names and output it alphabetically and reverse alphabetically.用户将输入姓名列表,一旦记录了空白条目,程序将对姓名和 output 按字母顺序和字母顺序进行排序。

This is what I have so far:这是我到目前为止所拥有的:

import java.util.Scanner;

public class SortBuffer {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        System.out.println("Text Sorting Program: (ECSE 202 - Assignment 2)");
        System.out.println("Enter text to be sorted, line by line. A blank line terminates");
        System.out.println("You can cut and paste into this window");

        scan.nextLine();
        while (!scan.nextLine().isEmpty()) {
            scan.nextLine();
        }
        if (scan.nextLine().isEmpty()) {
            System.out.println("Text in sort order:");
        }
    }
}

UPDATE This is what I have now (but it has errors):更新这就是我现在所拥有的(但它有错误):

import java.util.ArrayList;导入 java.util.ArrayList; import java.util.Scanner;导入 java.util.Scanner;

public class SortBuffer { public static void main(String[] args) {公共 class SortBuffer { 公共 static 无效主(字符串 [] 参数) {

    Scanner scan = new Scanner(System.in);
    boolean moreLines = [];

    System.out.println("Text Sorting Program: (ECSE 202 - Assignment 2)");
    System.out.println("Enter text to be sorted, line by line. A blank line terminates");
    System.out.println("You can cut and paste into this window");


    List<String> scannedLines = new ArrayList<>();
    do{
        String scannedLine = scan.nextLine();
        boolean moreLines = !scannedLine.isEmpty();
        if (moreLines){
            scannedLines.add(scannedLine);
        }
        while (moreLines)

            java.util.Collections.sort(scannedLines);
    }




}}

First you need to put all read lines in a list.首先,您需要将所有读取的行放在一个列表中。

Eg例如

List<String> scannedLines = new ArrayList<>();
boolean moreLines = false
do{
 String scannedLine = scan.nextLine();
 moreLines = !scannedLine.isEmpty();
 if (moreLines){
   scannedLines.add(scannedLine);
 }
} while (moreLines)

Then proceed like here: How can I sort a List alphabetically?然后像这里一样继续: 如何按字母顺序对列表进行排序?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM