0

似乎当我创建我的扫描仪时,我得到了这个错误。我试图通过搜索错误名称来解决这个问题,但到目前为止还没有成功让消息停止出现。

代码:

import java.util.Scanner;
public class PrintQueue {
    //Instance variables
    private Queue<Job> pq;
    //Constructor
    public PrintQueue() {
        pq = new Queue<Job>();
    }
    //Adds a job object to the end of the queue
    public void lpr(String owner, int jobId) {
        Job j = new Job(owner, jobId);
        pq.enqueue(j);
    }
    //Enumerates the queue
    public void lpq() {
        Job curr = pq.first();
        for (int i = 0; i < pq.size(); i++) {
            System.out.println(curr);
            curr = pq.next();
        }
    }
    //Removes the first entry in the queue if the input integer matches the integer contained within the job object
    public void lprm(int jobId) {
        if (pq.first().getJobId() == (jobId))
            pq.dequeue();
        else 
            System.out.println("Unable to find jobId.");
    }
    //Removes all objects that contain the input String
    public void lprmAll(String owner) {
        Job curr = pq.first();
        for (int i = 0; i < pq.size(); i++) {
            if (curr.getOwner().equals(owner)) 
                pq.dequeue();
            curr = pq.next();
        }
    }
    //Demo 
    public static void main(String[] args) {
        Scanner k = new Scanner(System.in);
        PrintQueue myPQ = new PrintQueue();
        String name;
        int id;
        for (int i = 1; i <= 5; i++) {
            System.out.print("Enter owner and id: ");
            name = k.next();
            id = k.nextInt();
            myPQ.lpr(name, id);
        }
        System.out.println("Print Queue");
        myPQ.lpq();
        myPQ.lprm(101);
        myPQ.lprmAll("ronaldinho");
        System.out.println("Print Queue"); 
        System.out.println("\n\n"); 
        myPQ.lpq(); 
    }
}

我得到错误的部分:

Scanner k = new Scanner(System.in);
4

2 回答 2

1

那是因为你永远不会关闭Scanner. 将您的代码更改为:

Scanner k = null;
try {
    k = new Scanner(System.in);
    //do stuff with k here...
} finally {
    if( k != null )
        k.close();
}
于 2013-10-19T18:50:42.377 回答
0

这似乎是警告而不是错误。但是,解决它是一个好习惯。

实际上你只需要k.close();在你的方法结束时调用。最佳实践是调用closefinally 块:这样可以保证无论是否抛出异常,资源都会关闭;

Scanner k = null;
try {
    k = new Scanner(System.in);
    ........
} finally {
    if (k != null) {
        k.close();
    }
}

幸运的是,java 7 提供了使这种语法不那么冗长:

try (
    Scanner k = new Scanner(System.in);
) {
    .... // use k
} 

当任何实现的类的对象是在用正则括号标记Closable的块的特殊部分中创建时,您不必编写块:它是由编译器添加的。try()finally

于 2013-10-19T18:55:36.967 回答