我輸入這個文本文件到命令行:While循環不工作
800 5 10
800 1 8
800 7 7
810 2 9
845 2 10
850 1 3
第一列是時間,那麼優先級,然後長度
輸出由時間加上長度排序,下一個項目輸出,如果該項目的時間小於或等於當前時間,具有最高優先級會第一(是它的混亂,但它的一類項目)
將輸出:
Job: [800,1,8] Start time: 800 End time:808
Job: [800,5,10] Start time: 800 End time:818
Job: [810,2,9] Start time: 810 End time: 819
Job: [800,7,7] Start time: 800 End time: 807
Job: [845,2,10] Start time: 845 End time 855
Job: [850,1,3] Start time: 850 End time: 853
即時通訊使用鏈接列表與隊列方法稱爲事件,和優先隊列隊列
我的問題是,while循環while (event.size() != 0 && queue.size() != 0)
根本不執行。
如果我改變它做一個while while循環,我得到空指針異常錯誤,而和if (event.peek().time > currentTime)
我試圖通過添加event.peek() != null
修復空指針異常,它仍然無法正常工作。事件(鏈表)有6個Job對象,所以我不知道爲什麼event.peek()返回null。
import java.util.*;
import java.io.*;
public class pj2
{
Queue<Job> event = new LinkedList<Job>();//interface queue
PriorityQueue<Job> queue = new PriorityQueue<Job>();
public static void main(String[] args) throws IOException
{
if (args.length != 1)
{
System.out.println("Usage: java pj2 jobs.txt");
System.exit(0);
}
else
new pj2(args[0]);
}
public pj2 (String textFile) throws IOException
{
File file = new File(textFile);
if (!file.exists())
{
System.out.println(textFile + " does not exist.");
System.exit(0);
}
//add time,priority,length to event queue
Scanner data = new Scanner(file);
while (data.hasNext())
{
int time = Integer.parseInt(data.next());
int priority = Integer.parseInt(data.next());
int length = Integer.parseInt(data.next());
Job temp = new Job(time,priority,length);
event.add(temp);
}
data.close();
int currentTime = 0;
//loop through priority queue, outputting results
while (event.size() != 0 && queue.size() != 0)
{
if (queue.size() == 0)
currentTime = event.peek().time;
while (event.peek().time <= currentTime)
{
currentTime += event.peek().length;
queue.offer(event.poll());
}
if (event.peek().time > currentTime)
{
currentTime = (event.peek().time + event.peek().length);
queue.offer(event.poll());
}
System.out.println(queue.peek() + " Start time: " + queue.peek().time + " End time: " + (queue.peek().time + queue.peek().length));
queue.poll();
}
}
}
public class Job implements Comparable<Job>
{
int time, length, priority;
public Job(int time, int priority, int length)
{
this.time = time;
this.priority = priority;
this.length = length;
}
public int compareTo(Job that)
{
if (this.priority == that.priority)
return this.time - that.time;
return this.priority - that.priority;
}
public String toString()
{
return "[" + time + "," + priority + "," + length + "]";
}
}