0

im having a trouble finishing my work because i dont know how to do the sorting of names together with the grade in ascending and descending. i hope you guys can help.

import java.util.Scanner;

public class SortingStudents {


    public static void main(String[] args) {

        Scanner s = new Scanner(System.in);

        System.out.print("Enter the number of students: ");
        int capacity = s.nextInt();

        String [] name = new String[capacity];
        Double [] grade = new Double[capacity];

        for(int i = 0; i < capacity; i++) {
            System.out.print("student's name: ");
            name [i] = s.next();
            System.out.print("grade: ");
            grade [i] = s.nextDouble();
        }

        Scanner input = new Scanner(System.in);
        System.out.println("Type A for Ascending D for Descending:");
        char a=input.nextLine().charAt(0);

        if(a == 'A' || a == 'a'){
        for(int i = 0; i<grade.length;i++){
            System.out.println(grade[i]+"\t" +grade[i]);

        }

    }
}
Adriaan Koster
  • 15,870
  • 5
  • 45
  • 60
  • This problem is some kind of sorting object. You can refer to answer on this link http://stackoverflow.com/questions/1206073/sorting-a-collection-of-objects – Minh Sep 08 '16 at 09:36
  • 1
    did you try Arrays.sort() method? – Arthas Sep 08 '16 at 09:38
  • If this is a homework problem where you are required to implement a basic sort algorithm please make sure to convey that in your question. – StaticBeagle Sep 08 '16 at 11:26

3 Answers3

3

You are using Java, which is an object-oriented programming language. This means you can think about your problem in terms of classes which represent state in your problem domain and have behavior (methods) which manipulate this state.

In this case your code shows several responsabilities, for which you could create useful classes and/or methods:

  • entering data via the command line (number of students, name and grade and desired sorting direction)
  • a registry of students with a fixed size
  • sorting the student registry in the desired direction

Class names that come to mind are: DataEntry, Student, StudentRegistry. For sorting the students in different ways the standard approach is creating a Comparator class, see below.

The classes could look roughly like this:

public class Student {
    private String name;
    private Double grade;

    // getters and setters ommitted for brevity
}

The registry:

public class StudentRegistry {
    // it's easier to use a List because you are adding students one by one
    private List<Student> students;

    public StudentRegistry(int capacity) {
        // ...constructor code initializes an instance of StudentRegistry 
    }

    public void addStudent(Student student) {
        // add a student to the list
    }

    public Student[] getStudents(Comparator<Student> comparator) {
         // sort the list using the comparator and Collections.sort()
         // use List.toArray() to convert the List to an array 
         // alternatively (java 8) return a Stream of Students
         // or return an unmodifiable List (using Collections.unmodifiableList())
         // you don't want to expose your modifiable internal List via getters
    }

}

A comparator which can sort Ascending or Descending. You could consider adding the capability to sort either by grades or by names, that would be quite easy.

public class StudentComparator implements Comparator<Student> {
    public enum Direction {
         ASCENDING, DESCENDING
    }

    // optional addition:
    //public enum Field{
    //     NAME, GRADE
    //}

    // if used, add Field parameter to the constructor
    public StudentComparator(Direction direction) {
        // initialize instance
    }

    @Override 
    public int compare(Student a, Student b) {
         // implement Comprator method, see JavaDoc
    }

    @Override
    public boolean equals(Object o) {
         // implement equals, see JavaDoc
    }
}

Class for letting the user enter data:

public class DataEntry {

    public int getNumberOfStudents() {
        // ...
    }

    public Student getStudent() {
        // ...
    }

    public StudentComparator.Direction getSortingDirection() {
        // ...
    }
}

And a main class:

public class Main {

    public static void main(String[] args) {

        DataEntry dataEntry = new DataEntry();
        int capacity = dataEntry.getCapacity();
        StudentRegistry studentRegistry = new StudentRegistry(capacity);
        for(int i=0; i<= capacity; i++) {
            studentRegistry.addStudent(dataEntry.getStudent());
        }
        StudentComparator comparator = new StudentComparator(dataEntry.getSortingDirection());
        Student[] students = studentRegsitry.getStudents(comparator);
    }
}

This approach separates concerns of your problem in separate classes and methods, making the code much easier to understand, debug and test.

For example, to test the Main class you could set up a mock DataEntry class which provides predetermined values to your test. See the topic of unit testing.

Adriaan Koster
  • 15,870
  • 5
  • 45
  • 60
0

You could just concatenate the name and grade and sort them, that way it could be a lot easier.

Eldon Hipolito
  • 704
  • 1
  • 8
  • 24
0

If you want to do it your way without changing how the arrays are stored separately. You will not be able to use the Arrays.sort() method to sort your grades because that will not take the name array into account and you will lose the link between them so that the grades will no longer match with the names.

You could very quickly code up your own bubble sorter to quickly sort the array, and then you could use your loop to affect the name array at the same time. But if you don't want to code your own sorter, you will need to organise your grades and names array so that can be treated as one unit i.e in a separate class.

If you choose to code your own sorter then here is a great link to learn that: http://www.java-examples.com/java-bubble-sort-example

If you choose to change the way that you store the grades and names, here is how you can use the Arrays.sort() method: http://www.homeandlearn.co.uk/java/sorting_arrays.html

SuperHanz98
  • 2,090
  • 2
  • 16
  • 33
  • 3
    You do know that everytime someone (advises to) use bubblesort a puppy dies? – Adriaan Koster Sep 08 '16 at 10:08
  • There is nothing wrong with a beginner programmer learning to use basic sorting algorithms without just using loads of standard library methods. You can't just throw 1000 pieces of information at someone and expect them to learn anything. – SuperHanz98 Sep 08 '16 at 10:12
  • see this page for some reasons why Bubblesort is Bad Idea for anything but theoretical use: http://warp.povusers.org/grrr/bubblesort_misconceptions.html Furthermore, the standard solutions for sorting collections in Java is using either Comparable or Comparator. If you suggest to a beginner to implement their own bubblesort you are definitely not pointing them in the right direction – Adriaan Koster Sep 08 '16 at 11:02