2011-12-26 99 views
0

我得到一個奇怪的NullPointerExcpetion在第20行:NullPointerException異常的LinkedList的隊列陣列

regs[Integer.parseInt(str.split(" ")[1]) - 1].add(line.poll()); 

我不知道是什麼原因造成這一點。有人可以幫我解決這個問題嗎?

import java.io.*; 
import java.util.*; 

public class shoppay 
{ 
public static void main (String[] args) throws IOException 
{ 
    BufferedReader f = new BufferedReader(new FileReader("shoppay.in")); 
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("shoppay.out"))); 
    Queue<Integer> line = new LinkedList <Integer>(); 
    int num = Integer.parseInt(f.readLine()); 
    String str; 
    LinkedList<Integer>[] regs = (LinkedList<Integer>[]) new LinkedList[num]; 

    while ((str = f.readLine()) != null) 
    { 
     if (str.charAt(0) == 'C') 
      line.add(Integer.parseInt(str.split(" ")[1])); 
     else 
      regs[Integer.parseInt(str.split(" ")[1]) - 1].add(line.poll()); 
    } 

    out.close(); 
    System.exit(0); 
} 
} 

而且,我得到一個警告:

類型安全:未選中從java.util.LinkedList中施放[]到java.util.LinkedList中的[]

這是否與錯誤有關?

編輯:輸入只是一串行。第一行是一個數字,其餘的是「C」或「R」後跟一個數字。另外,我需要一個regs隊列。

+0

「類型安全性」警告與'NullPointerException'無關。 'Type Safety'異常可能與正在轉換的LinkedList類型有關,而不是設置爲Integer。 – jbranchaud 2011-12-26 01:20:24

回答

0

不要創建一個通用列表數組。由於技術原因,它並不是乾淨利落的。這是更好的使用列表的列表:

BufferedReader f = new BufferedReader(new FileReader("shoppay.in")); 
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("shoppay.out"))); 
Queue<Integer> line = new LinkedList <Integer>(); 
int num = Integer.parseInt(f.readLine()); // not needed 
String str; 
List<List<Integer>> regs = new ArrayList<List<Integer>>(num); 

for (int i = 0; i < num; ++i) { 
    regs.add(new LinkedList<Integer>()); 
} 

while ((str = f.readLine()) != null) 
{ 
    if (str.charAt(0) == 'C') 
     line.add(Integer.parseInt(str.split(" ")[1])); 
    else 
     regs.get(Integer.parseInt(str.split(" ")[1]) - 1).add(line.poll()); 
} 

作爲一個方面的問題,有沒有你正在使用的LinkedList爲regs,而不是ArrayList任何理由?

+0

我只需要一個regs隊列,所以我使用LinkedList。另外,我在運行時遇到了IndexOutOfBoundsException。 – 2011-12-26 01:55:48

+0

@DannyArsenic也許我不明白你的原始代碼,但我認爲你是通過與'get'調用中使用的表達式相同的表達式將'regs'索引。我相信如果你已經解決了NullPointerException問題,那麼你的代碼就會有相同的IndexOutOfBoundsException。 – 2011-12-26 01:59:23

0

不知道你的輸入是什麼樣的,我只能猜測錯誤的原因。我猜想,當你拆分字符串時,你正在拆分導致大小爲1的數組的東西。你知道這將是零索引嗎?這意味着陣列中的第一個位置是0,第二個位置是1等等。如果您打算選擇列表中的第二個項目,那麼確保您的輸入始終會分成至少兩個項目。

+0

他可能不想要第一個元素,因爲他已經檢查它是否以字符開頭。確保它至少包含2個物品當然是好的建議。 – Kapep 2011-12-26 01:30:55

0

哎呦。我改變了主意並決定使用數組。 (int [])我想它工作正常。