Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/369.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 尝试按属性对arraylist中的对象进行排序,但对象不';I don’我不总是分类正确_Java_Sorting - Fatal编程技术网

Java 尝试按属性对arraylist中的对象进行排序,但对象不';I don’我不总是分类正确

Java 尝试按属性对arraylist中的对象进行排序,但对象不';I don’我不总是分类正确,java,sorting,Java,Sorting,我有四个类,但它们只是模板,所以我只发布我的主类(我已经为每个类重写了toString)。排序方法位于底部。对于我的代码,其他一切都很好(或多或少),但是当我在数组中创建对象,然后对它们进行排序(通过一个名为uid的字符串值)时,有时其中的一个或两个会出现顺序错误。我怎样才能解决这个问题 代码如下: import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.

我有四个类,但它们只是模板,所以我只发布我的主类(我已经为每个类重写了toString)。排序方法位于底部。对于我的代码,其他一切都很好(或多或少),但是当我在数组中创建对象,然后对它们进行排序(通过一个名为uid的字符串值)时,有时其中的一个或两个会出现顺序错误。我怎样才能解决这个问题

代码如下:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;

enum ClassStanding{FRESHMAN,SOPHOMORE,JUNIOR,SENIOR,UNKNOWN,MASTERS_STUDIES,PHD_STUDIES};
enum Major{CS,CEG,EE,ISE,BME,ME,MET,UNKNOWN};
enum StudentType{UNDERGRADUATE,GRADUATE,UNDECLARED};

public class Main {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    Scanner stdin = new Scanner(System.in);
    ArrayList<Student> studentList = new ArrayList<>();
    int counter;
    boolean continueInput;
    int contCounter;
    do {
        do {
            System.out.print("Please enter what you want to do-ADD, REMOVE, SORT, LIST, or SAVE: ");
            switch (stdin.next().toLowerCase()) {
                case "add":
                    add(stdin, studentList);
                    counter = 0;
                    break;
                case "remove":
                    remove(studentList, stdin);
                    counter = 0;
                    break;
                case "list":
                    list(studentList);
                    counter = 0;
                    break;
                case "save":
                    String fileName = getFileName(stdin);
                    save(fileName, studentList);
                    counter = 0;
                    break;
                case "sort":
                    counter = 0;
                    sort(studentList);
                    break;
                default:
                    System.out.println("Improper input, please enter only ADD, REMOVE, LIST, or SAVE.");
                    counter = 1;
            }
        } while (counter == 1);
        do {
            System.out.print("\nDo you want to continue? Yes or no: ");
            switch (stdin.next().toLowerCase()) {
                case "yes":
                    contCounter = 0;
                    continueInput = true;
                    break;
                case "no":
                    contCounter = 0;
                    continueInput = false;
                    break;
                default:
                    contCounter = 1;
                    continueInput = false;
                    System.out.print("\nPlease only enter 'yes' or 'no'.");
            }
        } while (contCounter == 1);
    } while (continueInput);
} // end main method

public static void add(Scanner stdin, ArrayList<Student> studentList) {
    String firstName;
    String lastName;
    String uid;
    StudentType studentType;
    ClassStanding studentClassStanding;
    Major major;
    double overallGPA;
    double majorGPA;
    String majorProfessor;
    boolean thesisOption;
    System.out.print("Please enter the student's first name: ");
    String tempName = stdin.next();
    firstName = checkName(tempName);
    System.out.print("Please enter the student's last name: ");
    tempName = stdin.next();
    lastName = checkName(tempName);
    System.out.println("Please enter the student's UID in the format 'U####' or 'U#####': ");
    String tempUID = stdin.next();
    uid = checkUID(tempUID).toUpperCase();
    int count;
    do {
        System.out.print("Please enter the student's status as UNDECLARED, UNDERGRADUATE, or GRADUATE: ");
        switch (stdin.next().toUpperCase()) {
            case "UNDECLARED":
                studentType = StudentType.UNDECLARED;
                studentClassStanding = setStudentClassStanding(studentType);
                count = 0;
                Student student = new Student(firstName, lastName,
                        uid, studentType, studentClassStanding);
                studentList.add(student);
                break;
            case "UNDERGRADUATE":
                studentType = StudentType.UNDERGRADUATE;
                major = setMajor();
                studentClassStanding = setStudentClassStanding(studentType);
                System.out.println("Enter the student's overall GPA below.");
                overallGPA = setGPA();
                System.out.println("Enter the student's major GPA below.");
                majorGPA = setGPA();
                count = 0;
                UnderGraduate underGraduate = new UnderGraduate(firstName, lastName, uid, studentType,
                        studentClassStanding, major, overallGPA, majorGPA);
                studentList.add(underGraduate);
                break;
            case "GRADUATE":
                studentType = StudentType.GRADUATE;
                studentClassStanding = setStudentClassStanding(studentType);
                majorProfessor = setMajorProfessor();
                thesisOption = setThesisOption();
                count = 0;
                Graduate graduate = new Graduate(firstName, lastName, uid, studentType,
                        studentClassStanding, majorProfessor, thesisOption);
                studentList.add(graduate);
                break;
            default:
                System.out.println("Please enter either Undeclared, Undergraduate, or Graduate only.");
                count = 1;
        }
    } while (count == 1);
} // end add method

public static String checkName(String tempName) {
    int a = 1;
    String name1;        
    Scanner scanner = new Scanner(System.in);
    do {
        name1 = tempName; // hold the value of firstName in name1
        for (int i = 0; i < tempName.length(); i++) { // loop to check input consists of letters (is a name)
            if (!Character.isLetter(tempName.charAt(i))) { // if non-letters detected, ensure this was intentional
                System.out.println("Please ensure you've entered the correct name. Re-enter the name or enter 'continue' to proceed: ");
                tempName = scanner.nextLine();
                if (tempName.equalsIgnoreCase("continue")) { // if user enters "continue", use original input
                    a = 0;
                    tempName = name1; // pass name1 value to firstName
                    break;
                } else {
                    a = 1; // continue prompting for firstName
                }
            } else { // accept input
                a = 0;
            }
        }
    } while (a == 1); // loop to ensure proper input
    return tempName;
} // end checkName method

public static String checkUID(String tempUID) {
    Scanner scan = new Scanner(System.in);
    int a;
    do {
        if (tempUID.charAt(0) == 'U' || tempUID.charAt(0) == 'u') {
            if (tempUID.length() == 6 || tempUID.length() == 5) {
                a = 0;
            } else {
                a = 1;
                System.out.print("Please ensure input is in the form of U#### or U#####. Please re-enter the UID: ");
                tempUID = scan.next();
            }
        } else {
                a = 1;
                System.out.print("Please ensure input is in the form of U#### or U#####. Please re-enter the UID: ");
                tempUID = scan.next();
        }
    } while (a == 1);
    return tempUID;
} // end checkUID method

public static ClassStanding setStudentClassStanding(StudentType studentType) {
    Scanner scan = new Scanner(System.in);
    int count;
    ClassStanding studentTempClassStanding = null;
    do {
        if (studentType == StudentType.UNDECLARED || studentType == StudentType.UNDERGRADUATE) {
        System.out.print("Please enter the student's class standing as either Freshman, Sophomore, Junior, Senior, or Unknown: ");
        switch (scan.next().toUpperCase()) {
            case "FRESHMAN":
                studentTempClassStanding = ClassStanding.FRESHMAN;
                count = 0;
                break;
            case "SOPHOMORE":
                studentTempClassStanding = ClassStanding.SOPHOMORE;
                count = 0;
                break;
            case "JUNIOR":
                studentTempClassStanding = ClassStanding.JUNIOR;
                count = 0;
                break;
            case "SENIOR":
                studentTempClassStanding = ClassStanding.SENIOR;
                count = 0;
                break;
            case "UNKNOWN":
                studentTempClassStanding = ClassStanding.UNKNOWN;
                count = 0;
                break;
            default:
                System.out.println("Please enter only Freshman, Sophomore, Junior, Senior, or Unknown.");
                count = 1;
        } 
        } else {
                System.out.print("Please enter the student's class standing as either 'Masters' for Masters Studies or 'PhD' for PhD Studies: ");
                switch (scan.next().toUpperCase()) {
                    case "MASTERS": studentTempClassStanding = ClassStanding.MASTERS_STUDIES; count = 0; break;
                    case "PHD": studentTempClassStanding = ClassStanding.PHD_STUDIES; count = 0; break;
                    default: System.out.println("Please enter only 'Masters' or 'PhD'.");
                count = 1;
                }
                }
    } while (count == 1);
    return studentTempClassStanding;
} // end setStudentClassStanding method

public static Major setMajor() {
    Major tempMaj = null;
    Scanner s = new Scanner(System.in);
    int c;
    do {
        System.out.print("Please enter the student's major as either CS, CEG, EE, ISE, BME, ME, MET, or Unknown: ");
        switch (s.next().toUpperCase()) {
            case "CS":
                tempMaj = Major.CS;
                c = 0;
                break;
            case "CEG":
                tempMaj = Major.CEG;
                c = 0;
                break;
            case "EE":
                tempMaj = Major.EE;
                c = 0;
                break;
            case "ISE":
                tempMaj = Major.ISE;
                c = 0;
                break;
            case "BME":
                tempMaj = Major.BME;
                c = 0;
                break;
            case "ME":
                tempMaj = Major.ME;
                c = 0;
                break;
            case "MET":
                tempMaj = Major.MET;
                c = 0;
                break;
            case "UNKOWN":
                tempMaj = Major.UNKNOWN;
                c = 0;
                break;
            default:
                System.out.println("Please enter only the specified values. ");
                c = 1;
        }
    } while (c == 1);
    return tempMaj;
} // end setMajor method

public static double setGPA() {
    Scanner s = new Scanner(System.in);
    double gpa;
    int a;
    do {
            try {
                System.out.print("Please enter the student's GPA: ");
                gpa = s.nextDouble();// read in the gpa
                if (gpa < 0.0 || gpa > 4.0) { // ensure the gpa is in the correct range
                    System.out.println("Invalid input, please enter a positive value between 0.0 and 4.0.");
                    a = 1;
                } else {
                    a = 0;
                }
            } catch (InputMismatchException ex) { //catch any exceptions, prompt for correct input
                a = 1;
                gpa = 0.0;
                System.out.println("Sorry, please enter a double value.");
                s.nextLine(); // skip the last input
            }
        } while (a == 1 || gpa < 0.0 || gpa > 4.0); //loop while gpa is negative or incorrect input is received
    return gpa;
} // end setGPA method

private static String setMajorProfessor() {
    Scanner s = new Scanner(System.in);
    String prof;
    System.out.print("Please enter the name of the major professor: ");
    String tempName = s.nextLine();
    prof = checkName(tempName);
    return prof;
} // end setMajorProfessor method

private static boolean setThesisOption() {
    Scanner s = new Scanner(System.in);
    boolean thesis = false;
    int a;
    do {
    System.out.print("Please enter 'yes' if a thesis will be written, otherwise enter 'no': ");
    switch (s.next().toUpperCase()) {
        case "YES": thesis = true; a = 0; break;
        case "NO": thesis = false; a = 0; break;
        default: System.out.println("Please enter only 'yes' or 'no'."); a = 1;
    }
    } while (a == 1);
    return thesis;
} // end setThesisOption method

private static void list(ArrayList<Student> studentList) {
    for (int i = 0; i < studentList.size(); i++) {
        System.out.println(studentList.get(i).toString());
    }
} // end list method

public static String getFileName(Scanner stdin) {
    System.out.print("Please enter the file name: "); // Prompt for input
    String fileString = stdin.next();
    return fileString; // Pass the fileString var to the main method
}//end of getFileName method

private static void save(String fileName, ArrayList<Student> studentList) {
    int a; // create a counter
    Scanner stdin = new Scanner(System.in);
    do {
        try {
            PrintWriter writer = new PrintWriter(fileName); // Create a printwriter 
            for (int i = 0; i < studentList.size(); i++) {
                writer.print(studentList.get(i).toString() + "\n"); //Print the arraylist to file
            }
            writer.close(); //Close the printwriter and save the file
            a = 0;
        } catch (FileNotFoundException ex) { // Catch any exceptions
            System.out.println("The file could not be found, please re-enter the file name: "); // get new file name if an exception is thrown
            fileName = stdin.nextLine();
            a = 1;
        }
    } while (a == 1); // loop while exceptions are thrown
    System.out.println("All information has been saved at " + fileName); // output that the arraylist has been saved in the specified file
    // Make the following its own method
    System.out.print("Would you like to read the contents of the file? Yes or no: ");
    int b;
    do {
    switch (stdin.next().toLowerCase()) {
        case "yes": readFromFile(fileName); b = 0; break;
        case "no": b = 0; break;
        default: System.out.println("Please enter only yes or no."); b = 1;
    }
    } while (b == 1);
} // end save method

private static void remove(ArrayList<Student> studentList, Scanner stdin) {
    System.out.print("Please enter the UID of the student to be removed: ");
    String tempUID = stdin.next();
    String uidRemove = checkUID(tempUID);
    for (int i = 0; i < studentList.size(); i++) {
        if ((studentList.get(i).getUid()).equalsIgnoreCase(uidRemove)) {
            studentList.remove(i);
        }
    }
    System.out.println("The student with UID " + uidRemove + " has been removed.");
} // end remove method

private static void sort(ArrayList<Student> studentList) {
    String uidLessU1;
    String uidLessU2;
    for (int i = 0; i < studentList.size(); i++) {
        uidLessU1 = (studentList.get(i).getUid()).substring(1, studentList.get(i).getUid().length());
        for (int j = 0; j < studentList.size(); j++) {
            uidLessU2 = (studentList.get(j).getUid()).substring(1, studentList.get(j).getUid().length());
            if (Integer.parseInt(uidLessU1) < Integer.parseInt(uidLessU2)) {
                Student hold = studentList.get(i);
                studentList.set(i, studentList.get(j));
                studentList.set(j, hold);
            }
        }
    }
} // end sort method

private static void readFromFile(String fileName) {
    System.out.println("The contents of " + fileName + " as read from NotePad: ");
    try {
        Scanner fileReader = new Scanner(new File(fileName)); //Create a scanner
        while (fileReader.hasNextLine()) {    //Loop to read the file
            String fromFile = fileReader.nextLine();
            System.out.println(fromFile); //Output the file contents
        }
    } catch (FileNotFoundException ex) { //Catch any exceptions
        System.out.println("Exception caught");
    }
} // end readFromFile method
} // end main class

只要让学生实现可比性,然后你就可以做到

    Collections.sort(studentList);
    Collections.sort(studentList);