6-44 Implement Book分数 10
创建一个Book类。
拷贝如下的代码框架。该类定义了一些方法:获取书名、判断是否可用、借书和还书。然而,我们所提供的框架缺少这些方法的实现。请在方法体中填上合适的代码。
主方法用于测试这些方法,运行此程序,应该有如下的输出:
Title (should be The Da Vinci Code): The Da Vinci Code
Borrowed? (should be false): false
Borrowed? (should be true): true
Borrowed? (should be false): false
提示:查看主方法看每个方法如何使用,然后在每个方法中填入代码。
程序框架如下:
class Book {
String title;
boolean borrowed;
// Creates a new Book
public Book(String bookTitle) {
// Implement this method
}
// Marks the book as rented
public void rented() {
// Implement this method
}
// Marks the book as not rented
public void returned() {
// Implement this method
}
// Returns true if the book is rented, false otherwise
public boolean isBorrowed() {
// Implement this method
}
// Returns the title of the book
public String getTitle() {
// Implement this method
}
}
仔细阅读测试程序中的main()方法,根据上述的样例框架补充完整缺失的方法实现部分。
裁判测试程序样例:
public class Main {
public static void main(String[] arguments) {
// Small test of the Book class
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());
example.rented();
System.out.println("Borrowed? (should be true): " + example.isBorrowed());
example.returned();
System.out.println("Borrowed? (should be false): " + example.isBorrowed());
}
}
/* 请在这里填写答案 */
输入样例:
在这里给出一组输入。例如:
输出样例:
在这里给出相应的输出。例如:
Title (should be The Da Vinci Code): The Da Vinci Code
Borrowed? (should be false): false
Borrowed? (should be true): true
Borrowed? (should be false): false
以下是答案
public class Pta_6_44 {
public static void main(String args[]) {
Book44 example = new Book44("The da Vinci Code");
System.out.println("Title (should be The DaVinci Code):"+example.getTitle());
System.out.println("Borrowed? (should be false): "+example.isBorrowed());
example.rented();
System.out.println("Borrowed? (should be ture): "+example.isBorrowed());
example.returned();
System.out.println("Borrowed? (should be false) :"+example.isBorrowed());
}
}
//以下是答案,把Book44换成Book
class Book44{
String title;
boolean borrowed=false;
public Book44(String bookTitle) {
this.title=bookTitle;
}
public void rented() {
borrowed = true;
}
public void returned() {
borrowed = false;
}
public boolean isBorrowed() {
return borrowed;
}
public String getTitle() {
return this.title;
}
}