-3

I look for a simplest way to sort objects in array by their float field.

I have java.lang.NullPointerException when I call method sort(); from Main();

How to sort these objects by student[].Rating? Any idea? This is my class:

public class Students {

public static String First_Name;
public static String Last_Name;
public static String id;
public static String Spec;
public static String Course;
public static String Ratingstr;
public float Rating;
public static int Number_of_students;
Students student[] = new Students[100];

public void sort() {

    int j;
    boolean flag = true;   // set flag to true to begin first pass
    Students temp;   //holding variable

    while (flag) {
        flag = false;    //set flag to false awaiting a possible swap
        for (j = 0; j < student.length - 1; j++) {
            if (student[ j].Rating < student[j + 1].Rating) // change to > for ascending sort
            {
                temp = student[ j];                //swap elements
                student[ j] = student[ j + 1];
                student[ j + 1] = temp;
                flag = true;              //shows a swap occurred 
            }
        }
    }
}

public void Read() {
    try {
        File fXmlFile = new File("C://Students.xml");
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(fXmlFile);
        //optional, but recommended
        //read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
        doc.getDocumentElement().normalize();

        //System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
        NodeList nList = doc.getElementsByTagName("student");
        System.out.println("----------------------------");

        for (int temp = 0; temp < nList.getLength(); temp++) {

            Node nNode = nList.item(temp);

            //System.out.println("\nCurrent Element :" + nNode.getNodeName());
            if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                Element eElement = (Element) nNode;
                System.out.println("First Name : " + eElement.getElementsByTagName("firstname").item(0).getTextContent());
                System.out.println("Last Name : " + eElement.getElementsByTagName("lastname").item(0).getTextContent());
                System.out.println("Student id : " + eElement.getAttribute("id"));
                System.out.println("Spec : " + eElement.getElementsByTagName("spec").item(0).getTextContent());
                System.out.println("Course : " + eElement.getElementsByTagName("course").item(0).getTextContent());
                System.out.println("Rating : " + eElement.getElementsByTagName("rating").item(0).getTextContent());

            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public void Read2() {
    try {
        File fXmlFile = new File("C://Students.xml");
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(fXmlFile);
        //optional, but recommended
        //read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
        doc.getDocumentElement().normalize();

        //System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
        NodeList nList = doc.getElementsByTagName("student");
        //System.out.println("----------------------------");

        for (Number_of_students = 0; Number_of_students < nList.getLength(); Number_of_students++) {
            //   Node nNode = nList.item(0);
            Node nNode = nList.item(Number_of_students);
            //System.out.println("\nCurrent Element :" + nNode.getNodeName());
            if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                Element eElement = (Element) nNode;

                student[Number_of_students] = new Students();

                student[Number_of_students].First_Name = eElement.getElementsByTagName("firstname").item(0).getTextContent();
                student[Number_of_students].Last_Name = eElement.getElementsByTagName("lastname").item(0).getTextContent();
                student[Number_of_students].Course = eElement.getElementsByTagName("course").item(0).getTextContent();
                student[Number_of_students].Ratingstr = eElement.getElementsByTagName("rating").item(0).getTextContent();
                student[Number_of_students].id = eElement.getAttribute("id");
                student[Number_of_students].Spec = eElement.getElementsByTagName("spec").item(0).getTextContent();

                System.out.println("----------------------------");

                student[Number_of_students].Rating = Float.parseFloat(student[Number_of_students].Ratingstr);

                String Ratingstr = Float.toString(student[Number_of_students].Rating);
                System.out.println("Rate is : " + Ratingstr);
                System.out.println("First Name : " + First_Name);
                System.out.println("Last Name : " + Last_Name);
                System.out.println("Student id is : " + id);
                System.out.println("Spec : " + Spec);
                System.out.println("Course is : " + Course);
                System.out.println("----------------------------");
                System.out.println("//////////////////////////");
            }

        }

    } catch (Exception e) {
    }

}

public static void main(String argv[]) {
    new Students().Read2();
    new Students().sort();

}

public void print() {

    System.out.println("----------------------------");

    // String Ratingstr = Float.toString(student[Number_of_students].Rating);
    System.out.println("Rate is : " + Ratingstr);
    System.out.println("First Name : " + First_Name);
    System.out.println("Last Name : " + Last_Name);
    System.out.println("Student id is : " + id);
    System.out.println("Spec : " + Spec);
    System.out.println("Course is : " + Course);
    System.out.println("----------------------------");
    System.out.println("//////////////////////////");

}

} 
ZygD
  • 22,092
  • 39
  • 79
  • 102

4 Answers4

0

You are using anonymous objects for reading and sorting, thus they are working on two different objects,

a2800276
  • 3,272
  • 22
  • 33
Saurabh Jhunjhunwala
  • 2,832
  • 3
  • 29
  • 57
0

In your main method you are creating Students object and reading the data inside its field Students[] student. After that you are dropping this object, creating the new one and trying to sort its student data which is empty. This way would be better:

public static void main(String argv[]) {
    Students s = new Students();
    s.Read2();
    s.sort();
}

Needless to say that your code is a big mess.

Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
0

First, let's review your code a little bit:

Make class Student

class Student {
    private String first_Name;
    private String last_Name;
    private String id;
    private String spec;
    private String course;
    private float rating;

   public Student(String first_Name, String last_Name,String id,
                  String spec,String course,float rating){

        this.first_Name=first_Name;
        this.last_Name=last_Name;
        this.id=id;
        this.spec=spec;
        this.course=course;
        this.rating=rating;

   }

   // getters and setters
   ...
}

Then in Students main class

public class Students {

    private static Student students[] = new Student[100];


    public void Read() {
        //your code here
    }

    public void Read2() {
        try {
           File fXmlFile = new File("C://Students.xml");
           DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
           DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
           Document doc = dBuilder.parse(fXmlFile);umentElement().normalize();
           NodeList nList = doc.getElementsByTagName("student");

           for (int i = 0; i< nList.getLength(); i++) {
            Node nNode = nList.item(i);
            if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                Element eElement = (Element) nNode;

                students[i] = new Student
                (                                        
                  eElement.getElementsByTagName("firstname")
                  .item(0).getTextContent(),

                   eElement.getElementsByTagName("lastname")
                  .item(0).getTextContent(),

                   eElement.getAttribute("id"),

                   eElement.getElementsByTagName("spec")
                   .item(0).getTextContent(),

                    eElement.getElementsByTagName("course")
                   .item(0).getTextContent(),

                   Float.parseFloat
                  (eElement.getElementsByTagName("rating")
                   .item(0).getTextContent())

                );

                print(i);
              }
           }
       } catch (Exception e) {
           //stack trace
       }

    }

    public static void main(String argv[]) {
        Read2();
        students.sort((s1, s2) -> s1.getRating().compareTo(s2.getRating()));

    }

    public void print(int i) {


            System.out.println("----------------------------");

            System.out.println("Rate is : " + students[i].getRate());
            System.out.println("First Name : " + students[i].getFirst_Name());
            System.out.println("Last Name : " + students[i].getLast_Name());
            System.out.println("Student id is : " + students[i].getId());
            System.out.println("Spec : " + students[i].getSpec());
            System.out.println("Course is : " + students[i].getCourse());
            System.out.println("----------------------------");
            System.out.println("//////////////////////////");
    }
}

So you can sort students using Lambdas in java 8

students.sort((s1, s2) -> s1.getRating().compareTo(s2.getRating()));
MChaker
  • 2,610
  • 2
  • 22
  • 38
  • @HristoTsonev Have tried any of the given answers? discussing answers is very important in order to find the best way to solve your problem. – MChaker May 03 '15 at 10:03
0

I would guess it's related due to the fact that you are creating an array of one hundred students

Students student[] = new Students[100];

but you read less then one hundred. So in the array there will be null references. And during the sort you try to sort one hundered students rather to sort only the number of read students.

SubOptimal
  • 22,518
  • 3
  • 53
  • 69