-3
{

public static class Member
{
    private String name;
    private int age;

    public Member(String x,int y){
    name=x;
    age=y;
    }
    public int compareTo(Member a){
    if(a.getAge()>age)
        return 1;
       else if (age<a.getAge())
        return -1;
        else return 0;
    }

    public String getName(){return name;}

    public int getAge(){return age;}
}

public static void sortMember(Member [] a,int l){
for (int j = 0; j < l-1; j++) {
if (a[j].compareTo(a[(j+1)]) > 0) {
      Member temp = a[j]; 
     a[j] = a[j+1]; 
     a[j+1] = temp; 
}}
}
public static void main(String[] args)
{

    String name[]=new String[7];
    int age[]=new int[7];
    for(int x=0,y=0;x<14;x+=2,y++){
    name[y]=args[x];
    age[y]=Integer.parseInt(args[x+1]);}

    Member [] s= new Member[7];

    for(int i =0;i< (s.length -1);i++){
        s[i]=new Member(name[i],age[i]);
                    }

        for(int count =0;count< (s.length -1);count++){
             System.out.println(s[count].getName()+" "+s[count].getAge());
             }

         sortMember(s,s.length);
    for(int count =0;count< (s.length -1);count++){
    System.out.println(s[count].getName()+" "+s[count].getAge());
    }
    }}


CommandLine Arguments: Alice 15 Bob 55 Cat 56 David 63 Elan 37 Fanny 75 Helen 55

Output:

Alice 15
Bob 55
Cat 56
David 63
Elan 37
Fanny 75
Exception in thread "main" java.lang.NullPointerException
    at TestAsg1Q1$Member.compareTo(TestAsg1Q1.java:16)
    at TestAsg1Q1.sortMember(TestAsg1Q1.java:30)
    at TestAsg1Q1.main(TestAsg1Q1.java:55)
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • Can you also add TestAsg1Q1.java class? – TheCoder Oct 10 '19 at 11:34
  • @TheCoder I think this *is* that class, it's just not well expressed. –  Oct 10 '19 at 11:37
  • 1
    `for(int i =0;i< (s.length -1);i++)` This loop comes one short. The last element in your array will not be initialized. – Ivar Oct 10 '19 at 11:38
  • 1) For better help sooner, [edit] to add a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). 2) See [What is a stack trace, and how can I use it to debug my application errors?](http://stackoverflow.com/q/3988788/418556) & [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/q/218384/418556) – Andrew Thompson Oct 10 '19 at 11:38

1 Answers1

0

Your sort method, doesn't need you to pass the length of the array because you are passing the array and you can access that property directly from the method. But when you have if (a[j].compareTo(a[(j+1)]) for j having the value of 6 you try to access the array a at index 7 that does not exist.

If you are using an IDE (Netbeans, Eclipse, Intellij) you can set some breakpoints in the first line of the for loop of your sort method and check the values of the variables for each iteration until the error pops up.

Traufvihal
  • 54
  • 6