gpt4 book ai didi

Java: "this"关键字的问题

转载 作者:行者123 更新时间:2023-12-01 08:10:32 24 4
gpt4 key购买 nike

我正在尝试使用类 Library{} 和 Book{} 创建一个 Java 包“mylib”。

以下是类库{}的代码:

/*
Create collection of books
List books and status
User input:
'B' - Borrow a book
'R' - Reserve a book
'I' - Return a book
'X' - Exit program
*/

package mylib;

public class Library {

public static void main(String[] args) {
Book[] MyBooks = new Book[3];
Book x;

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

for (int i = 0; i < MyBooks.length; i++) {
x = MyBooks[i];
System.out.println((i + 1) + " " + x.sTitle);
}
}
}

以下是 Book{} 类的代码:

package mylib;

class Book {
// Declare fields
byte iStatus;
int iPages;
String sTitle, sAuthor;
String sBorrowedBy, sReservedBy;
String sDueDate, sReturnDate;

public static final byte BORROWED = 0, AVAILABLE = 1, RESERVED = 2;

// Constructor
public Book(String Title, String Author, int Pages) {
this.sTitle = Title;
this.sAuthor = Author;
this.iPages = Pages;
this.iStatus = this.AVAILABLE;
}

// Borrow method
static void borrowBook(String Borrower, String Due) {
if (this.iStatus == this.AVAILABLE) {
this.sBorrowedBy = Borrower;
this.sDueDate = Due;
this.iStatus = this.BORROWED;
} else if (this.iStatus == this.RESERVED
&& this.sReservedBy == Borrower) {
this.sBorrowedBy = Borrower;
this.sDueDate = Due;
this.sReservedBy = "";
this.iStatus = this.BORROWED;
}
}

/*
* static int reserveBook(String Borrower) {
*
* }
*
* static void returnBook(String Return) {
*
* }
*/
}

上面的部分代码是教授给出的。我注释掉了空方法并测试了程序只是为了看看它是否可以编译。

我的 this 关键字有 14 个错误。有什么帮助吗?

最佳答案

在这个方法中

static void borrowBook(String Borrower, String Due) {

您不能在静态上下文中使用this

据我所知,没有必要将该方法设为静态

更喜欢阅读Understanding Instance and Class Members

关于Java: "this"关键字的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17832044/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com