I am getting a weird NullPointerExcpetion in line 20:
regs[Integer.parseInt(str.split(" ")[1]) - 1].add(line.poll());
I do not know what has caused this. Can someone please help me fix this?
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);
}
}
Also, I am getting a warning:
Type safety: Unchecked cast from java.util.LinkedList[] to java.util.LinkedList[]
Does this have something to do with the error?
Edit: Input is just a string of lines. First line is a number, and the rest are either "C" or "R" followed by a number. Also, I need a queue for regs.
Not knowing what your input looks like, I can only guess at the cause of the error. I would guess that when you split the String, you are splitting something that results in array of size 1. Are you aware that this will be zero-indexed? This means that the first position in the array is 0
and the second is 1
and so forth. If you did intend to select the second item in the list, then ensure that your input will always split into at least 2 items.
Don't create an array of generic lists. For technical reasons, it doesn't really work cleanly. It's much better to use a list of lists:
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());
}
As a side issue, is there any reason you're using LinkedList for regs
instead of ArrayList
?
Whoops. I changed my mind and decided to use an array. (int[]) I guess it worked fine.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.