There is probably a simple solution to this problem I've been having all night. At least I hope there is. When attempting to offer an object to my subQueues LinkedList, I receive a NullPointerException. My program prints out the correct "head" Objects and "digit" integers, but then the Exception is thrown and the program ends.
My program, in short, is supposed to take a mainQueue LinkedList of integers, look at them all one-by-one, and sort them. Its examining the last digit of each integer, and placing them into corresponding subQueues. As of now, I am only to the ones place. After I get past this dilemma, I'll be able to work out the tens, hundreds, etc.
Ex)
mainQueue = { 12 50 215 100 85 539 16 35 }
subQueue[0] = { 50 100 }
subQueue[1] = { }
subQueue[2] = { 12 }
subQueue[3] = { }
subQueue[4] = { }
subQueue[5] = { 215 85 35 }
subQueue[6] = { 16 }
subQueue[7] = { }
subQueue[8] = { }
subQueue[9] = { 539 }
So what am I doing wrong here? Like I said, once I get by this little problem, the rest of the program should be a breeze. Any help is appreciated, thanks!
public class Sorting
{
private LinkedList mainQueue;
private LinkedList[] subQueues;
private final int SIZE = 10;
private int maxDigits; //maximum number of digits
//The constructor instantiates the mainQueue using the LinkedList,
//subQueue array as an array of LinkedList using SIZE(10),
//and initializes maxDigits = 0;
public Sorting()
{
mainQueue = new LinkedList();
for (int i=0; i<SIZE; i++)
{
subQueues = new LinkedList[i];
}
// I have also tried:
// subQueues = new LinkedList[SIZE];
//I get the same runtime error.
maxDigits = 0;
}
public void sortNumbers()
{
while (mainQueue.isEmpty() == false)
{
Object head = mainQueue.peek();
mainQueue.remove();
String digitLine = "" + head;
int digit = Integer.parseInt(digitLine.substring(digitLine.length()-1, digitLine.length()));
System.out.println(head);
System.out.println(digit);
subQueues[digit].offer(head);
}
}
}
You're not correctly building your subQueues
it looks like. If you want an array of SIZE
linked-lists, try this:
subQueues = new LinkedList[ SIZE ];
for ( int i = 0; i < SIZE; ++i ) {
subQueues[i] = new LinkedList();
}
Note that this is using raw types as your code is, though preferably you should use parameterized types.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.