2011-12-26 48 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 [])我想它工作正常。