Code中的扫描程序错误,使用引用变量构建数组

时间:2015-12-09 13:19:24

标签: java

我对编码还很陌生,所以如果这有明显的解决方法,我很抱歉。

我正在尝试构建一个可以存储图书对象的库,但在我开始处理功能之前,我需要整理一个数组。 Java本身在我的边栏中没有显示任何错误,但是当通过控制台运行时,会出现错误。

下面我发布了我的Library.java类。

import java.util.Scanner;


public class Library {
	
	public static void main(String[] args){
		
		Scanner input = new Scanner(System.in);
		
		Book[] books = new Book[2];
		String Title;
		String Author;
	    String BookID;
		Boolean onLoan;
		int NumberofLoans;
		
		for( int i = 0; i < books.length; i++){
			System.out.print("Enter the title of the book: ");
			Title = input.next();
			books[i] = new Book();
			books[i].setTitle(Title);
			System.out.println("");
			
			System.out.print("Enter the Author of the book: ");
			Author = input.next();
			books[i].setAuthor(Author);
			System.out.println("");
			
			System.out.print("Enter the Book's ID: ");
			BookID = input.next();
			books[i].setBookID(BookID);
			System.out.println("");
			
			NumberofLoans = 0;
			books[i].setNumberofLoans(NumberofLoans);
			
			onLoan = false;
			books[i].setonLoan(onLoan);
			
			input.close();
			}
		
		for(int i = 0; i < books.length; i++){
			System.out.println("Title: " + books[i].getTitle());
			System.out.println("Author: " + books[i].getAuthor());
			System.out.println("BookID: " + books[i].getBookID());
			System.out.println("Times loaned: " + books[i].getNumberofLoans());
			System.out.println("In library: " + books[i].getonLoan());
			
		}	
	}
}

控制台错误本身列在下面:

Exception in thread "main" Enter the title of the book:
java.lang.IllegalStateException: Scanner closed
at java.util.Scanner.ensureOpen(Scanner.java:1070)
at java.util.Scanner.next(Scanner.java:1358)
at Library.main(Library.java:19)

有人可以指出我的代码中的错误来自何处?然后,我可以做出哪些更改来阻止此错误发生?

为了确保列出所有内容,我将发布Book.java,以防错误源自那里。

public class Book {

private String Title;
private String Author;
private String BookID;
private Boolean onLoan;
private int NumberofLoans;



public Book(){
    Title = new String();
    Author = new String();
    BookID = new String();
    onLoan = false;
    NumberofLoans = 0;

}

public void setTitle(String title) {
    this.Title = title;
}

public void setAuthor(String author) {
    this.Author = author;
}

public void setBookID(String bookID) {
    this.BookID = bookID;
}

public void setonLoan(Boolean onLoan) {
    this.onLoan = onLoan;
}

public void setNumberofLoans(int numberofLoans) {
    this.NumberofLoans = numberofLoans;
}

public String getTitle() {
    return Title;
}

public String getAuthor() {
    return Author;
}

public String getBookID() {
    return BookID;
}

public Boolean getonLoan() {
    return onLoan;
}

public int getNumberofLoans() {
    return NumberofLoans;
}}

1 个答案:

答案 0 :(得分:3)

Library班级&#39;第一个循环导致这个。具体来说,这一行:

input.close();

因为在整个程序完全使用之前关闭Scanner。第一次循环运行时Scanner可用。但首次执行后,您关闭扫描仪。因此,对于连续循环运行,扫描程序将关闭,从而导致错误。

循环结束后添加此行。换句话说,就像这样:

for( int i = 0; i < books.length; i++){
    // ... Whatever
}

input.close();