繁体   English   中英

LinkedList队列数组的NullPointerException

[英]NullPointerException for LinkedList queue array

我在第20行中得到了一个奇怪的NullPointerExcpetion:

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”,后跟一个数字。 另外,我需要一个队列进行注册。

不知道您的输入是什么样子,我只能猜测错误的原因。 我猜想在拆分字符串时,您正在拆分的东西会导致数组大小为1。您知道这将是零索引的吗? 这意味着数组中的第一个位置为0 ,第二个为1 ,依此类推。 如果您确实打算选择列表中的第二个项目,请确保您的输入将始终分为至少两个项目。

不要创建通用列表数组。 由于技术原因,它并不能完全正常工作。 最好使用列表列表:

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

哎呀 我改变主意,决定使用数组。 (int [])我猜它工作正常。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM