使用Queue [] queues = new Queue [10]获取错误;

时间:2014-01-06 15:42:24

标签: java queue

这是我的代码:

import java.util.*;
import unit4.collectionsLib.*;

public class Page255Project_class
{
    static Scanner reader = new Scanner (System.in);

    /**
     * @param args
     */
    public static void radixSort(int[] numbers){
        Queue[] queues = new Queue[10];
        for(int i=0; i<numbers.length; i++){
            if(numbers[i]%10 == i)
            {
                queues[i].insert(numbers[i]);
                System.out.println(queues[i]);
            }
        }
    }

    public static void main(String[] args)
    {
        int[] numbers = new int[10];

        numbers[0] = 170;
        numbers[1] = 45;
        numbers[2] = 75;
        numbers[3] = 90;
        numbers[4] = 2;
        numbers[5] = 24;
        numbers[6] = 802;

        radixSort(numbers);
    }
}

我收到了这个错误:

Exception in thread "main" java.lang.NullPointerException
    at Page255Project_class.radixSort(Page255Project_class.java:15)
    at Page255Project_class.main(Page255Project_class.java:33)

请帮助解决该错误

1 个答案:

答案 0 :(得分:2)

在您的函数radixSort中,您定义了大小为10的数组,其中包含10个“空插槽”,但您忘记初始化所有插槽。

您的代码更改如下:

public static void radixSort(int[] numbers) {
    Queue[] queues = new Queue[10];
    Arrays.fill(queues, new Queue()); // Queue is interface you need to implement it 
                                      // or you need to choose specific type of
                                      // queues [PriorityQueue, LinkedBlockingQueue, ...]
    for(int i = 0; i < numbers.length; i++) {
        if(numbers[i] % 10 == i) {
            queues[i].insert(numbers[i]);
            System.out.println(queues[i]);
        }
    }
}