我有这个类创建寄存器和客户端的模拟,并询问完成它们的总时间和平均等待时间。我创建了一个FIFO数组,它由我所拥有的IntQueueImpl类列出的队列组成。现在代码编译好了,但是当我运行它时,我得到一个运行时。
这是班级:
import java.util.Scanner;
public class QueueSimulation
{
public static void main(String[] args)
{
int a, tail, head;
int i = 0;
String s;
Scanner input = new Scanner(System.in);
System.out.println("This programs simulates a queue of customers at registers.");
System.out.println("We assume the every customer take 4 seconds to leave the register.");
System.out.println("Enter the number of registers you want to simulate:");
a = input.nextInt();
while(a==0 || a <0){
System.out.println("0 registers or no registers is invalid. Enter again: ");
a = input.nextInt();
}
IntQueueImpl fifo[] = new IntQueueImpl[a];
System.out.println("Enter how many customers enter per second.For example: 0 0 1 1 2 2 2 3 3. Enter: ");
s = input.nextLine();
s = input.nextLine();
String[] parts = s.split(" ");
int[] A = new int[parts.length];
for(int j = 0; j < parts.length; j++){
A[j]= Integer.parseInt(parts[j]);
while(A[j] < 0){
System.out.println(A[j]+" is invalid.Enter positive integer: ");
A[j]= input.nextInt();
}
}
input.close();
head = tail = 0;
int T[] = new int[A.length];
int temp= 0;
for(int j = 0 ; j< A.length ; j++){
if(fifo[tail].isEmpty()) fifo[tail].put(A[j] +4);
else{
temp = fifo[tail].size();
fifo[tail].put(A[j] + 4*temp);
}
if(tail == a-1){
tail=0;
}else tail++;
if(j>=4){
temp = fifo[head].get();
T[j]= j-temp;
if(head == a-1){
head=0;
}else head++;
}
}
int sum = 0;
for(int j= 0; j<T.length; j++){
sum =+ T[j];
}
System.out.println("All customers leaved at: " + sum + " seconds.");
}
}
我得到的运行时错误是:
Exception in thread "main" java.lang.NullPointerException
at QueueSimulation.main(QueueSimulation.java:58)
这是命令:
if(fifo[tail].isEmpty()) fifo[tail].put(A[j] +4);
我已经尝试了很多东西来避免它,但没有任何反应......
答案 0 :(得分:0)
有很多地方可以在您的代码中抛出NPE。其中几个是: -
a = input.nextInt();// input can be null
String[] parts = s.split(" ");// s can be null
fifo[tail].isEmpty()) fifo[tail].put(A[j] +4)//fifo[tail] can be null