views:

88

answers:

2
+1  Q: 

sort problem ??

hello !!

i try to program radix sort , but i have NullPointerException when i run this code

public class ThreeRadixSort {

    public Queue getSortedData(Queue queue){
     Queue array[] = new Queue[10];


     for(int i=1;i<=3;i++){

     while(queue.front != null){
      Student student = queue.dequeue();


      if( i == 1) 
       array[(int)(student.id%10)].enqueue(student);
      else if( i == 2)
       array[(int)((student.id%100)/10)].enqueue(student);
      else 
       array[(int)(student.id/100)].enqueue(student);

     }

     for(int j=0;j<=9;j++){

     while( array[j] != null && array[j].front != null)
      queue.enqueue(array[j].dequeue());
     }
     } 
     return queue;
    }
}

The Exception show when the implement reach to

 array[(int)(student.id%10)].enqueue(student);
+2  A: 

The problem here is that when you initialize your array of Queue, each spot is initialized to null. So right now, you are trying to call the enqueue method on null. You need to loop through each position of the array and assign it a new Queue() or however you initialize those.

So for example:

for (int i = 0; i < array.length; i++) {
  array[i] = new Queue();
}
danben
thanx , problem solved
wasim
You're welcome - would you mind modding up / accepting this answer if it worked for you?
danben
oK ..i did this
wasim
Thanks! Good luck with everything.
danben
+1  A: 

this line:

 Queue array[] = new Queue[10]

only declares an array of queues. It does not allocate the queues itself. you should initialize them like this:

 for(int i; i<10; i++)
 {
      array[i] = new Queue();
 }

p.s. by the way. Instead of relying on a magic number like '10' it's better practice to make it a constant and declare on the top of your program. Like such:

 const int numElements = 10;
Toad
I would tend to agree with your statement about magic numbers, except when the constant can never change - then I feel like it just decreases readability (since it suggests to the reader that it might change). In this case, the only way his number of queues would change is if he implemented the algorithm in a base other than 10, which seems unlikely.
danben
thanx , problem solved
wasim
I would tend to your idea ,danben
wasim