2011-11-22 2 views
0

밤새이 문제에 대한 간단한 해결책이있을 수 있습니다. 적어도 나는 거기에 있기를 바란다. 내 subQueues LinkedList에 객체를 제공하려고하면 NullPointerException이 발생합니다. 내 프로그램은 정확한 "머리"개체와 "자릿수"정수를 출력하지만 예외가 발생하고 프로그램이 종료됩니다.Java - LinkedList에 객체를 제공 할 때 NullPointerException 수신

내 프로그램은 간단히 말해서 integer의 mainQueue LinkedList를 취하여 모든 것을 하나씩 살펴보고 정렬하도록되어 있습니다. 각 정수의 마지막 자리를 조사해, 대응하는 subQueues에 배치합니다. 현재로서는, 나는 단지 장소입니다. 나는이 딜레마 과거를 얻을 후, 나는) 등

예, 수십, 수백을 작동 할 수 있습니다

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 } 

는 그래서 어떻게 내가 잘못 여기서 뭐하는 거지? 제가 말씀 드렸듯이, 일단이 작은 문제가 생기면 프로그램의 나머지는 산들 바람에 빠져야합니다. 어떤 도움을 주셔서 감사합니다, 감사합니다!

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); 
    } 
    } 
} 

답변

5

제대로 보이지 않는데 subQueues처럼 보입니다. 당신이 SIZE 연결된 목록의 배열을 원하는 경우,이 시도 :

subQueues = new LinkedList[ SIZE ]; 
for (int i = 0; i < SIZE; ++i) { 
    subQueues[i] = new LinkedList(); 
} 

참고 코드이기 때문에이 원시 유형을 사용하고, 바람직하게는 매개 변수 유형을 사용해야하지만.

+0

고마워요! 그 트릭을 했어, 나는 그게 뭔가 간단해야만한다는 것을 알았다. === – Dreiak

+0

매개 변수화 된 유형의 배열은 불법입니다. – Affe

+1

예, 매개 변수화 된 유형의 배열을 유지하고 유형을 안전하게 유지할 수 있습니다. –

관련 문제