java中的arraylist对数据进行排序

时间:2016-02-16 20:52:21

标签: java arraylist

所以我遇到了让我这么做的问题。这段代码需要做的是有3个不同的(字符串)字段,然后将它们按字母顺序排序我以前有过帮助,但它不会在我的netbeans上运行。我目前最新的所有更新。

这是我到目前为止的代码

import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
import java.util.Comparator;

public class test {
private Scanner scan = new Scanner(System.in);
private List<LayoutOfScientist> scientistsNames = new ArrayList<LayoutOfScientist>();
private String name, field, idea;
private boolean continueLoop = true;
private int countTo3 = 0;

private void run() {
    while(countTo3<3&&continueLoop) {
        if(countTo3>0) {
            System.out.println("Would you like to add another scientist? (Y/N)");
        }

        if(countTo3 == 0 || scan.nextLine().equalsIgnoreCase("y")) {
            System.out.println("Please enter the scientist's name:");
            name = scan.nextLine();
            System.out.println("Please enter the scientist's field:");
            field = scan.nextLine();
            System.out.println("Please enter the scientist's idea:");
            idea = scan.nextLine();
            scientistsNames.add(new LayoutOfScientist(name, field, idea));
        } else {
            continueLoop = false;
        }
        countTo3++;
    }

    scientistsNames.sort(Comparator.comparing(LayoutOfScientist::getScientistName));
    for(LayoutOfScientist lOS : scientistsNames) {
        System.out.println(lOS.getScientistName() + ", " + lOS.getScientistField() + ", " + lOS.getScientistIdea());
    }
}

private class LayoutOfScientist {
    private String scientistName, scientistField, scientistIdea;

    private LayoutOfScientist(String scientistName, String scientistField, String scientistIdea) {
        this.scientistName = scientistName;
        this.scientistField = scientistField;
        this.scientistIdea = scientistIdea;
    }

    public String getScientistName() {
        return scientistName;
    }

    public String getScientistField() {
        return scientistField;
    }

    public String getScientistIdea() {
        return scientistIdea;
    }
}

public static void main(String[] args) {
    new Test().run();
}
}

1 个答案:

答案 0 :(得分:1)

您的班级名称为test(小写字母t),在您的主要方法中,您正在调用Test().run()。 您需要将您的类重命名为Test,这应该有效。或者,如果您的文件是测试版,则需要将Test().run()更改为test().run(),而不是public class test更改为public class test。但是,命名ClassLikeThis是一种很好的编程习惯。

如果您的错误完全不同,请告诉我们错误是什么。