0

我正在使用类 Library{} 和 Book{} 创建一个包 mylib。

图书馆类

package mylib;
import java.util.*;

class Library {
public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    Book[] MyBooks = new Book[3];
    Book x;

    MyBooks[0] = new Book("The Lover's Dictionary", "Levithan, D.", 211, "AVAILABLE");
    MyBooks[1] = new Book("White Tiger", "Adiga, A.", 304, "AVAILABLE");
    MyBooks[2] = new Book("Thirteen R3asons Why", "Asher, J.", 336, "AVAILABLE");

    System.out.println("\n***** BOOK LISTING *****");
    for(int i = 0; i < MyBooks.length; i++) {
        x = MyBooks[i];
        System.out.println("[" + (i + 1) + "] " + x.sTitle + "\nAuthor: " +
            x.sAuthor + "\nPages: " + x.iPages + "\nStatus: " + Book.AVAILABLE);
        System.out.print("\r\n");
    }

    System.out.println("***** SELECT ACTION *****");
    System.out.println("B - Borrow a book");
    System.out.println("R - Reserve a book");
    System.out.println("I - Return a book");
    System.out.println("X - Exit program");

    System.out.print("\nEnter command: ");
    char cAction = input.nextLine().charAt(0); // Read single char

    switch(cAction) {
        case 'B':

            break;

        case 'R':

            break;

        case 'I':

            break;

        case 'X':
            Book book = new Book();
            book.exitProgram();
            break;

        default:
            System.out.println("INVALID INPUT!");
            break;
    }
}
}

书类

package mylib;

class Book {
int iPages;
String sTitle, sAuthor;
String sBorrowedBy, sReservedBy;
String sDueDate, sReturnDate;
    String sStatus;

public static final String BORROWED = "BORROWED", AVAILABLE = "AVAILABLE", RESERVED = "RESERVED";

// Constructor
public Book(String title, String author, int pages, String status) {
    this.sTitle = title;
    this.sAuthor = author;
    this.iPages = pages;
    this.sStatus = status;
}
/*
void borrowBook() {

}

void reserveBook() {

}

 void returnBook() {

}
*/
 void exitProgram() {
    System.exit(0);
}
}

Library课堂上,我试图通过 switch 退出程序,它从类中调用exitProgram()方法。Book我收到 1 个错误constructor x in class x...

任何帮助将非常感激。

4

3 回答 3

0
case 'X':
            Book book = new Book();
            book.exitProgram();
            break;

您没有可以接受无参数的构造函数

public Book() {
}

如果你想创建没有参数的“书”,这应该在书类中定义。

或者

您应该通过传递所需的参数来创建 Book 对象

case 'X':
                Book book = new Book("test","test",1,"test");
                book.exitProgram();
                break;
于 2013-07-25T05:19:11.397 回答
0

仅当类中没有定义构造函数时,Java 运行时才提供默认的无参数构造函数。在您的情况下,您有一个带有少量参数的构造函数,因此 Java 运行时不会添加无参数构造函数。您实际上必须在 Book 类中放置一个无参数构造函数。

于 2013-07-25T05:25:18.260 回答
0

在 Book.java 中将退出方法设为静态

Book.java
static void exitProgram() {
  System.exit(0);
}

Library.java
 case 'X':
        //Book book = new Book();
        Book.exitProgram();
        break;
于 2013-07-25T05:26:11.393 回答