0

I'm having trouble with a project for my Java data structures and algorithms class. I have a classroom program with an option to create, update, display, or see all students.

Can someone help me by implementing a sorting algorithm and explain it? I was trying to sort the students by grade but I don't know how to implement it with a user input.

Here is main:

package main;

import school.School;


    public class Main {

        public static void main(String[] args) {
            School aSchool = new School();
            aSchool.initialMenu();
        }
    }

Here is school:

package school;

import java.io.PrintStream;
import java.util.Scanner;
import student.Student;

public class School {

    private final Scanner keyboard = new Scanner(System.in);
    private final PrintStream messagePane = new PrintStream(System.out, true);

    private int nextAvailablePosition;
    private Student[] classroom;

    public School() {
        super();
    }

    private void initializeArray() {
        classroom = new Student[4];
        nextAvailablePosition = 0;
    }
    private void storeStudentInArray(Student aStudent) {
        assert aStudent != null : "Null parameter supplied to School.storeStudentInArray()";
        if (nextAvailablePosition >= classroom.length) {
            Student[] biggerClassroom = new Student[(int) (classroom.length * 1.5)];
            System.arraycopy(classroom, 0, biggerClassroom, 0, classroom.length);
            classroom = biggerClassroom;
        }
        classroom[nextAvailablePosition] = aStudent;
        nextAvailablePosition++;
    }

    private Student searchForStudentInArray(String searchID) {
        assert searchID != null : "Null parameter supplied to School.searchForStudentInArray()";

        int index = 0;
        while (index < nextAvailablePosition) {
            if (searchID.equalsIgnoreCase(classroom[index].getID())) {
                return classroom[index];
            }
            index++;
        }
        return null;
    }

    public void initialMenu() {
        initializeArray();

        boolean stillWorking = true;
        do {
            messagePane.print("\n"
                    + "WELCOME to the Student Database Organizer 1.0!\n"
                    + "Here you can store students in a virtual classroom.\n"
                    + "\n"
                    + "(C)reates a Student\n"
                    + "(U)pdate a Student\n"
                    + "(D)isplay a Student\n"
                    + "(A)ll Students\n"
                    + "(E)nd\n"
                    + "Enter Letter Here: \n");
            String initialResponse = keyboard.nextLine();
            String response = initialResponse.trim().toUpperCase();
            if (response.length() > 0) {
                response = response.substring(0, 1);

                if (response.equals("E")) {
                    stillWorking = false;
                } else if (response.equals("U")) {
                    updateStudent();
                } else if (response.equals("D")) {
                    displayStudent();
                } else if (response.equals("C")) {
                    Student aStudent = createStudent();
                    if (aStudent != null) {
                        storeStudentInArray(aStudent);
                    }
                } else if (response.equals("A")) {
                    gpa();
                } else {
                    messagePane.println("Try again " + initialResponse
                            + ", is not a valid choice.\n"
                            + "Please enter one of the letters from the specified menu.");
                }
            } else {
                messagePane.println("You must enter one of the letters from the specified menu\n"
                        + "before you press \"Enter\".");
            }
        } while (stillWorking);
    }

    private Student createStudent() {
        messagePane.println(
                "\nYou can enter the student's information here: \n");

        messagePane.print("What's the Student's name?: ");
        String name = keyboard.nextLine();

        messagePane.print("What year/grade is the student?: ");
        String agrade = keyboard.nextLine();

        messagePane.print("Birthday (MMDDYY): ");
        int birthday = keyboard.nextInt();
        keyboard.nextLine();

        messagePane.print("What's their ID number? (1-7 Numbers): ");
        String id = keyboard.next();
        keyboard.nextLine();

        messagePane.print("Course(s) taken: ");
        String course = keyboard.nextLine();

        double gpa;
        messagePane.print("GPA: ");
        Scanner inputScanner = new Scanner(keyboard.nextLine());
        if (inputScanner.hasNextDouble()) {
            gpa = inputScanner.nextDouble();
        } else if (inputScanner.hasNext()) {
            messagePane.println("You entered something other than a number - the gpa "
                    + "has been set to the default of " + Student.DEFAULT_GPA);
            gpa = Student.DEFAULT_GPA;
        } else {
            gpa = Student.DEFAULT_GPA;
        }

        Student newStudent;
        try {
            newStudent = Student.create(name,
                    agrade, birthday, id,
                    course, gpa );
        } catch (Exception anException) {
            messagePane.println("   Sorry, I couldn't input the student for you. " + anException.getMessage());
            newStudent = null;
        }

        return newStudent;
    }

    private void displayStudent() {
        Student aStudent = locateStudent();
        if (aStudent == null) {
            messagePane.println("Sorry, this ID number is not in the classroom.");
        } else {
            messagePane.println("   " + aStudent.getGrade() + "   " + aStudent.getName()
                    + " (" + aStudent.getBirthday() + ", " + aStudent.getID() + ") " + "\n"
                    + "        " + aStudent.getCourse() + "  GPA: " + aStudent.getGpa()
                    );
        }
    }

    private void updateStudent() {
        Student aStudent = locateStudent();
        if (aStudent == null) {
            messagePane.println("Sorry, the student is not listed.");
        } else {
            updateMenu(aStudent);
        }
    }

    private void updateMenu(Student aStudent) {
        assert aStudent != null : "Null parameter supplied to School.updateMenu()";

        String studentBeforeUpdating = singleLineStudentDisplay(aStudent);
        messagePane.println("The Student being updated is: \n" + aStudent);

        boolean stillTrying = true;
        do {
            messagePane.print("\n"
                    + "Student Database Organizer 1.0\n"
                    + "UPDATE MENU OPTIONS\n"
                    + ""
                    + "Press 1 to change the Student's name\n"
                    + "Press 2 to update grade\n"
                    + "Press 3 to update course(s)\n"
                    + "Press 4 to update gpa \n"
                    + "Press 5 to finish updating current Student\n"
                    + ""
                    + "\nPlease enter your selection: ");
            Scanner inputScanner = new Scanner(keyboard.nextLine());
            if (inputScanner.hasNextInt()) {
                int response = inputScanner.nextInt();
                if (response == 1) {
                    updateName(aStudent);
                } else if (response == 2) {
                    updateGrade(aStudent);
                }  else if (response == 3) {
                    updateCourse(aStudent);
                } else if (response == 4) {
                    updateGpa(aStudent);
                }  else if (response == 5) {
                    stillTrying = false;
                } else {
                    messagePane.println(
                            "You typed " + response + ", which is not a legit option.\n"
                            + "Please check the list of numbers in the menu..");
                }
            } else if (inputScanner.hasNext()) {
                String junk = inputScanner.next();
                messagePane.println("You entered " + junk + ", which is not a legal option.\n"
                        + "Please enter one of the numbers from the specified menu.");
            } else {
                messagePane.println("Hold your horses! You need to enter a number\n"
                        + "before you press \"Enter\".");
            }

        } while (stillTrying);

        messagePane.println("\n" + "Student before updating: " + studentBeforeUpdating);
        messagePane.println("Student after updating: " + singleLineStudentDisplay(aStudent));
    }

    private void updateName(Student aStudent) {
        assert aStudent != null : "Null parameter supplied to School.updateName()";

        int result;
        messagePane.println("The student's name is: " + aStudent.getName());
        messagePane.print("Now it is...: ");
        String name = keyboard.nextLine();
        result = aStudent.setName(name);
        messagePane.println("\nUpdate status: "
                + Student.getDescriptionOfReturnedSignal(result) );
        messagePane.println("\nFinalized changes: " + singleLineStudentDisplay(aStudent));
    }

    private void updateBirthday(Student aStudent) {
        assert aStudent != null : "Null parameter supplied to School.updateBirthday()";

        int result;
        messagePane.println("The current birthday is: " + aStudent.getBirthday());
        messagePane.print("New birthday (exactly four digits): ");
        Scanner inputScanner = new Scanner(keyboard.nextLine());
        if (inputScanner.hasNextInt()) {
            int birthday = keyboard.nextInt();
            keyboard.nextLine();
            result = aStudent.setBirthday(birthday);
            messagePane.println("Update status: "
                    + Student.getDescriptionOfReturnedSignal(result));
            messagePane.println("Finalized Changes: " );
        } else {
            messagePane.println("You didn't enter a number\n"
                    + "Please Check the Format MMDDYY \n\n"
                    + "Sorry, no changes were made.");
        }
    }

    private void updateGrade(Student aStudent) {
        assert aStudent != null : "Null parameter supplied to School.updateGrade()";

        int result;
        messagePane.println("The student's grade is: " + aStudent.getGrade());
        messagePane.print("Now it is... (at least three characters: ");
        String agrade = keyboard.nextLine();
        result = aStudent.setGrade(agrade);
        messagePane.println("Update status: "
                + Student.getDescriptionOfReturnedSignal(result));
        messagePane.println("Finalized Changes: " + singleLineStudentDisplay(aStudent));
    }

    private void updateCourse(Student aStudent){
        assert aStudent != null : "Null parameter supplied to School.updateCourse()";

        int result;
        messagePane.println("The course(s) taken are: " + aStudent.getCourse());
        messagePane.print("Now it is...: ");
        String course = keyboard.nextLine();
        result = aStudent.setCourse(course);
        messagePane.println("Update status: "
                + Student.getDescriptionOfReturnedSignal(result));
        messagePane.println("Finalized Changes: " + singleLineStudentDisplay(aStudent));
    }

    private void updateGpa(Student aStudent){
        assert aStudent != null: "Null parameter supplied to School.updateGpa()";

        int result;
        messagePane.println("GPA is: " + aStudent.getGpa());
        messagePane.print("Now it is... (Must be Postive Number): ");
        Scanner inputScanner = new Scanner(keyboard.nextLine());
        double gpa;
        if (inputScanner.hasNextDouble())
        {
            gpa = keyboard.nextDouble();
        }
        else
        {
            messagePane.println("You entered something other than a number - " +
              "GPA is back to default " + Student.DEFAULT_GPA);
            gpa = Student.DEFAULT_GPA;
        }
        result = aStudent.setGPA(gpa);
        messagePane.println("Update status: " +
          Student.getDescriptionOfReturnedSignal(result));
        messagePane.println("Finalized Changes" + singleLineStudentDisplay(aStudent));
    }



    private void gpa() {
        int studentCount = nextAvailablePosition;

        if (studentCount > 0) {
            messagePane.println("\nThe student database has " + studentCount + " student(s):");

            messagePane.printf(" %25s, %-35s (%4s, %13s) %-30s  %9s \n",
                    "Grade/Standing", "Student's Name", "Birthday", "ID Number",
                    "Course(s) taken", "GPA");
            int index = 0;
            while (index < studentCount) {
                Student temp = classroom[index];
               messagePane.printf(" %25s, %-35s (%4d, %-13s) %-30s  %9.2f \n",
                        temp.getGrade().length() < 25
                        ? temp.getGrade() : temp.getGrade().substring(0, 25),
                        temp.getName().length() < 35
                        ? temp.getName() : temp.getName().substring(0, 35),
                        temp.getBirthday(),
                        temp.getID(),
                        temp.getCourse().length() < 30
                        ? temp.getCourse() : temp.getCourse().substring(0, 30),
                        temp.getGpa());
                index++;
            }
        } else {
            messagePane.println("The classroom is currently empty.");
        }
    }

    private Student locateStudent() {
        Student aStudent;
        messagePane.print("\nEnter the Student's ID you would like to find: ");
        Scanner inputScanner = new Scanner(keyboard.nextLine());
        if (inputScanner.hasNext()) {
            String searchID = inputScanner.next();
            aStudent = searchForStudentInArray(searchID);
        } else {
            messagePane.println("Please enter an ID");
            aStudent = null;
        }
        return aStudent;
    }

    private String singleLineStudentDisplay(Student aStudent) {
        assert aStudent != null : "Null parameter supplied to School.singleLineStudentDisplay()";

        return aStudent.getGrade() + ", " + aStudent.getName() + " ("
                + aStudent.getID() + ", " + aStudent.getBirthday() + ") "
                + aStudent.getCourse() + "  GPA: " + aStudent.getGpa();
    }
}

Here is Student :

package student;

public class Student {

    public static final int SET_SUCCESSFUL = 0;
    public static final int GRADE_CANNOT_BE_NULL = -1;
    public static final int GRADE_CANNOT_BE_EMPTY = -2;
    public static final int GRADE_MUST_BE_AT_LEAST_SIX_CHARACTERS = -3;
    public static final int NAME_CANNOT_BE_NULL = -11;
    public static final int NAME_CANNOT_BE_EMPTY = -12;
    public static final int BIRTHDAY_MUST_BE_EXACTLY_SIX_DIGITS_CHECK_FORMAT = -24;
    public static final int ID_MUST_BE_ONE_OR_SEVEN_NUMBERS = -31;
    public static final int ID_CANNOT_BE_NULL = -32;
    public static final int ID_CANNOT_BE_EMPTY = -33;
    public static final int COURSE_CANNOT_BE_EMPTY = -41;
    public static final int GPA_CANNOT_BE_NEGATIVE = -51;

    public static final double DEFAULT_GPA = 0.0;

    private String name;
    private String grade;
    private int birthday;
    private String id;
    private String course;
    private double gpa;

    private Student() {
        super();
    }

    public static Student create(String theName,
            String theGrade, int theBirthday,String theId,
            String theCourse, double theGpa) throws Exception {
        Student newStudent = new Student();

        int result;

        result = newStudent.setName(theName);
        if (result != SET_SUCCESSFUL) {
            throw new Exception(Student.getDescriptionOfReturnedSignal(result));}

        result = newStudent.setGrade(theGrade);
        if (result != SET_SUCCESSFUL) {
            throw new Exception(Student.getDescriptionOfReturnedSignal(result));}
        result = newStudent.setBirthday(theBirthday);
        if (result != SET_SUCCESSFUL) {
            throw new Exception(Student.getDescriptionOfReturnedSignal(result));}
        result = newStudent.setId(theId);
        if (result != SET_SUCCESSFUL) {
            throw new Exception(Student.getDescriptionOfReturnedSignal(result));}
        result = newStudent.setCourse(theCourse);
        if (result != SET_SUCCESSFUL) {
            throw new Exception(Student.getDescriptionOfReturnedSignal(result));}
        result = newStudent.setGPA(theGpa);
        if (result != SET_SUCCESSFUL) {
            throw new Exception(Student.getDescriptionOfReturnedSignal(result));}

        return newStudent;}


    // <editor-fold defaultstate="collapsed" desc="------------------------------------------------------------------------------"> /* */
    // </editor-fold>
    public String getName() {
        return name;}
    public String getGrade() {
        return grade;}
    public int getBirthday() {
        return birthday;}
    public String getID() {
        return id;}
    public String getCourse() {
        return course;}
    public double getGpa() {
        return gpa;}


    @Override
    public String toString() {
        StringBuilder temp = new StringBuilder(name);
        temp.append("\nwho is a ");
        temp.append(grade);
        temp.append("\nwith a Birthday on ");
        temp.append(birthday);
        temp.append("\nID Number ");
        temp.append(id);
        temp.append("\nwho takes ");
        temp.append(course);
        temp.append("\nwith a GPA of ");
        temp.append(gpa);
        temp.append(' ');


        return temp.toString();
    }

    public static String getDescriptionOfReturnedSignal(int aSignal) {

        if (aSignal == SET_SUCCESSFUL) {
            return "SET_SUCCESSFUL";}
        if (aSignal == GRADE_CANNOT_BE_NULL) {
            return "GRADE_CANNOT_BE_NULL";}
        if (aSignal == GRADE_CANNOT_BE_EMPTY) {
            return "GRADE_CANNOT_BE_EMPTY";}
        if (aSignal == GRADE_MUST_BE_AT_LEAST_SIX_CHARACTERS) {
            return "GRADE_MUST_BE_AT_LEAST_SIX_CHARACTERS";}
        if (aSignal == NAME_CANNOT_BE_NULL) {
            return "NAME_CANNOT_BE_NULL";}
        if (aSignal == NAME_CANNOT_BE_EMPTY) {
            return "NAME_CANNOT_BE_EMPTY";}
        if (aSignal == BIRTHDAY_MUST_BE_EXACTLY_SIX_DIGITS_CHECK_FORMAT) {
            return "BIRTHDAY_MUST_BE_EXACTLY_SIX_DIGITS_CHECK_FORMAT";}
        if (aSignal == ID_CANNOT_BE_NULL) {
            return "ID_CANNOT_BE_NULL";}
        if (aSignal == ID_CANNOT_BE_EMPTY) {
            return "ID_CANNOT_BE_EMPTY";}
        if (aSignal == ID_MUST_BE_ONE_OR_SEVEN_NUMBERS) {
            return "ID_MUST_BE_ONE_OR_SEVEN_NUMBERS";}
        if (aSignal == COURSE_CANNOT_BE_EMPTY) {
            return "COURSE_CANNOT_BE_EMPTY";}
        if (aSignal == GPA_CANNOT_BE_NEGATIVE) {
            return "GPA_CANNOT_BE_NEGATIVE";}


        return "Sorry, but the signal value " + aSignal + " is not recognized.";
    }


    public int setName(String theName) {
        if (theName == null) {
            return NAME_CANNOT_BE_NULL;
        }
        String trimmedName = theName.trim();
        if (trimmedName.isEmpty()) {
            return NAME_CANNOT_BE_EMPTY;
        }
        name = trimmedName;
        return SET_SUCCESSFUL;
    }


    public int setGrade(String theGrade) {
        if (theGrade == null) {
            return GRADE_CANNOT_BE_NULL;
        }
        String trimmedGrade = theGrade.trim();
        if (trimmedGrade.isEmpty()) {
            return GRADE_CANNOT_BE_EMPTY;
        }
        if (trimmedGrade.length() < 6) {
            return GRADE_MUST_BE_AT_LEAST_SIX_CHARACTERS;
        }
        grade = trimmedGrade;
        return SET_SUCCESSFUL;
    }


    public int setBirthday(int theBirthday) {
        if (theBirthday <= 7) {
            return BIRTHDAY_MUST_BE_EXACTLY_SIX_DIGITS_CHECK_FORMAT;
        }

        birthday = theBirthday;
        return SET_SUCCESSFUL;
    }


    private int setId(String theId) {
        if (theId == null) {
            return ID_CANNOT_BE_NULL;
        }
        String trimmedId = theId.trim();
        if (trimmedId.isEmpty()) {
            return ID_CANNOT_BE_EMPTY;
        }
        if (trimmedId.length() != 1 && trimmedId.length() != 7) {
            return ID_MUST_BE_ONE_OR_SEVEN_NUMBERS;
        }
        id = trimmedId;
        return SET_SUCCESSFUL;
    }


    public int setCourse(String theCourse) {
        if (theCourse == null) {
            course = "";
            return SET_SUCCESSFUL;
        }
        String trimmedCourse = theCourse.trim();
        if (trimmedCourse.isEmpty()) {
            return COURSE_CANNOT_BE_EMPTY;
        }
        course = trimmedCourse;
        return SET_SUCCESSFUL;
    }


    public int setGPA(double theGPA) {
        if (theGPA < 0.0) {
            return GPA_CANNOT_BE_NEGATIVE;
        }
        gpa = theGPA;
        return SET_SUCCESSFUL;
    }



/*
    public String getbirthday() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
*/
}
Mark Rotteveel
  • 82,132
  • 136
  • 114
  • 158
jackfrost
  • 1
  • 1
  • 5
    That's a lot of code. I think you need a more specific question or your current one will be put on hold – LppEdd Mar 08 '19 at 18:08

1 Answers1

1

Don't have sufficient reputation to comment so adding as answer.

You must remove the current code and specify only the snippets that you tried for 1) Reading the inputs, which I see you are using Scanner 2) What's your approach for sorting

To guide you on this considering this is your classroom program, look at these:

How to read inputs: How can I read input from the console using the Scanner class in Java?

Comparision:
https://www.baeldung.com/java-comparator-comparable
When should a class be Comparable and/or Comparator?

and then sorting:
https://www.geeksforgeeks.org/collections-sort-java-examples/
https://www.geeksforgeeks.org/arrays-sort-in-java-with-examples/

A Baldino
  • 168
  • 10