public class Book {
String title;
boolean borrowed;
// Creates a new Book
public Book(String bookTitle){
bookTitle= "The Da Vinci Code";
}
// Marks the book as rented
public void borrowed() {
int borrowed= 1;
// Implement this method
}
// Marks the book as not rented
public void returned() {
int returned = 2;
// Implement this method
}
// Returns true if the book is rented, false otherwise
public boolean isBorrowed(int returned, int borrowed) {
if (borrowed < 2 )
return true;
else
return false;
// Implement this method
}
// Returns the title of the book
public String getTitle() {
String bookTitle= "The Da Vinci Code";
return bookTitle;
// Implement this method
}
public static void main(String[] arguments){
// Small test of the Book class
int returned= 1;
int borrowed= 2;
Book example = new Book("The Da Vinci Code");
System.out.println("Title (should be The Da Vinci Code): " +example.getTitle());
System.out.println("Borrowed? (should be false): " + example.isBorrowed(returned, borrowed));
example.borrowed();
System.out.println("Borrowed? (should be true): " + example.isBorrowed(returned, borrowed)); // should be returning true but it not. It printing false
example.returned();
System.out.println("Borrowed? (should be false): " + example.isBorrowed(returned, borrowed));
}
我正在做课程和方法。我正在上一本书课,它几乎可以工作,但我需要让第二个打印语句打印为真,但我得到了假。我应该怎么做才能解决这个问题?
您正在借用 void 中创建一个新的 int,它与 main 方法中的 int 不同,因此使其成为借用的类 int 的属性,不要声明它两次。
在 main()
方法中将局部变量 borrowed
设置为 2。您调用isBorrowed()
并向其传递此变量。然后在isBorrowed()
中,您说如果borrowed
小于 2,则返回 true。不是这样你返回假的。
borrowed()
方法需要将Book
中的borrowed
字段设置为 true,而不是设置局部变量。
您应该了解声明变量和为变量赋值之间的区别