java - 如何让我的 Java 程序终止?

标签 java data-structures linked-list priority-queue

我正在做一个模拟正在处理的CPU作业的项目。基本上,用户将输入一个具有将要处理的长度的作业和一个优先级键(从-20到19,从-20开始以获得更高的优先级)。到目前为止,除了程序正确终止之外,我已经完成了所有工作。基本上,当优先级队列中的所有作业都已处理完毕时,我需要程序终止。当每个作业处理完后,都会从长度中减去,直到为0。当为0时,将从优先级队列中删除。当没有剩余作业时(优先级队列为空),程序应在输入 n 后终止,因为没有新作业。然而由于某种原因,我完成代码的方式并没有终止。相反,当我输入 n 且没有剩余作业可供输入时,它会给我一个空指针错误。谁能向我指出我可能在哪里犯了错误?谢谢。

示例输入输出过程如下所示,格式如下(作业名称、长度、优先级):

Enter the job to be processed:
I:job1 3 0
O:job1

Enter new job to be processed:
I:n
O:job1

Enter new job to be processed:
I:job2 1 -3
O:job2

Enter new job to be processed:
I:n
O:job1

Enter new job to be processed:
I:n

这是我的代码:

import java.util.Scanner;
import java.lang.Integer;

public class PQScheduler {
String command = "";
String process = "";
String[] inputParts = null;
SLPQueue Q;
boolean empty = false;

PQScheduler(String inputCommand) {
    Q = new SLPQueue();
    Scanner comReader = new Scanner(System.in);
    this.command = inputCommand;
    this.inputParts = command.split("\\s");     // will split input at whitespace and store parts into array

    while (empty == false) {        // will loop until priority queue becomes empty
        if (this.inputParts[0].equals("n")) {       // input of no new jobs, will continue processing previous jobs however
            if (Q.isEmpty()) {
                System.exit(0);
            }
            else {
                this.process(Q.entries.getHead(), Q.entries.getHead().getValue());
            }
        }
        else {
            int value = Integer.parseInt(inputParts[1]);    // parses value of length into an integer
            int key = Integer.parseInt(inputParts[2]);      // parse value of key into an integer

            try {
                Q.insert(inputParts[0], key, value);        // inserts job, length, and key into priority queue
            } catch (InvalidKeyException e) {
                e.printStackTrace();
            }
            this.process(Q.entries.getHead(), Q.entries.getHead().getValue());      // processes the highest priority job
        }
        System.out.println("Enter new job to be processed: ");
        command  = comReader.nextLine();
        inputParts = command.split("\\s");
    }
}

public void process(Node n, int value) {
    if (value == 0) {
        try {
            Q.removeMin();      // removes the finished job
            if (Q.isEmpty()) {
                empty = true;
            }
            else {
                process(Q.entries.getHead(), Q.entries.getHead().getValue());   // processes next highest priority job
            }

        } catch (EmptyPriorityQueueException e) {
            e.printStackTrace();
        }
    }
    else {
        n.setValue(value - 1);      // decrements job length by 1 when processed
        process = n.getElement();
        System.out.println(process);
    }
}

public static void main(String[] args) {
    String inputCommand = "";
    Scanner mainReader = new Scanner(System.in);

    System.out.println("Enter the job to be processed: ");      // takes in user input of job, length, and priority
    inputCommand = mainReader.nextLine();

    PQScheduler scheduler = new PQScheduler(inputCommand);
}

}

public class SLPQueue implements PQueue {
protected SLList entries;
protected int size;

public SLPQueue() {
    entries = new SLList();     // creates a new linked list to store elements
    size = 0;
}

public String min() throws EmptyPriorityQueueException {
    if(entries.isEmpty()) throw new EmptyPriorityQueueException("Priority Queue is empty.");
    else
        return entries.getHead().getElement();      // gets the first node in priority queue
}

public Node insert(String e, int k, int v) throws InvalidKeyException {
    Node tempNode = new Node(e, k, v, null);
    insertEntry(tempNode);
    return tempNode;        // insertion method to add values to node and then insert into priority queue
}

protected void insertEntry(Node n) {        // insertion method to add into priority queue
    if (entries.isEmpty()) {        // checks if it is empty, if so, it will make it head of list
        entries.addFirst(n);
        size++;
    }
    else if (compare(n.getKey(), entries.getTail().getKey()) > 0) {     // checks to see if lower priority key inserted
        entries.addLast(n);     // adds last if key inserted is lower priority than the current tail of list
        size++;
    }
    else if (compare(n.getKey(), entries.getHead().getKey()) < 0) {
        entries.addFirst(n);        // adds first if key inserted is higher priority than the current head of list
        size++;
    }
    else {
        Node temp1 = entries.getHead();     // starts traversal from beginning of list
        Node temp2 = temp1;     // creates a second temporary node to "capture" node for node n to be inserted after
        while (compare(n.getKey(), temp1.getKey()) > 0 ) {      // loop to see if keys are of lower priority
            if (temp1.equals(entries.getHead())) {      // if statement created to set back temp2 by one node
                temp1 = temp1.getNext();
            }
            else {
                temp2 = temp2.getNext();        // gets the node value before temp1
                temp1 = temp1.getNext();        // gets the next temp1 value
            }
        }
        temp2.setNext(n);       // loop will break when key has higher priority than temp1 key found
        n.setNext(temp1);
        size++;
    }
}

public int compare(int k1, int k2) {        // comparator method to check for key priorities
    int compare = 0;
    if (k1 >= k2) {
        compare = 1;        // returns 1 if first key is of lower priority than second key
    }
    else if (k1 < k2) {     // returns -1 if first key is of higher priority than second key
        compare = -1;
    }
    return compare;
}

public Node removeMin() throws EmptyPriorityQueueException {        // removal method to remove from head of list
    if (entries.isEmpty()) throw new EmptyPriorityQueueException("Priority Queue is empty.");
    else {
        return entries.removeFirst();
    }
}

public int size() {     // returns size of priority queue list
    return size;
}

public boolean isEmpty() {      // checks to see if priority queue list is empty
    return size == 0;
}

}

最佳答案

我敢打赌,Q.isEmpty() 的行为不会像您希望的那样。看起来它是在队列的 size 上进行操作,但您的 removeMin 方法并没有减少该值。

尝试将 size--; 添加到 SLPQueue.removeMin 中的 else block

关于java - 如何让我的 Java 程序终止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12896279/

相关文章:

java - PlayFramework 初学者。路由定义错误

java - Iterable 实现中的 Lambda 表达式

java - LinkedList.pollLast() 抛出 NullPointerException

java - 为什么不推荐错误处理?

c++ - 通过链表类从 main 中的另一个类调用函数

c - 链接列表中的元素没有被删除

java - 生成缺失的 Bpmn 图元素

java - 在 Java 中,如何根据一个列表对另一个列表进行排序?

algorithm - 子串算法建议

java - PriorityQueue addAll() 的复杂度