我正在尝试解决此问题:私有实例变量/类定义
书,作为标题,作者和出版年份。包含获取和设置私有实例变量的方法以及toString方法来显示对象。另外创建一个方法moreRecent,它将两本书作为输入参数,并返回最近发布的一本书。为更多最近创建3个JUnit测试。
但是,我不知道如何访问其他私有实例变量author和yearofPub。我只能为每个类做一个构造函数吗?那么如何获得其他2个变量?这是我的代码到目前为止: 谢谢!
class Book {
private String title;
private String author;
private String yearofPub;
Book(String input) {
title = input;
}
String moreRecent(int Book1, int Book2) {
String moreRecent;
if(Book1 > Book2) {
moreRecent = "Book 1";
}
if (Book2 > Book1) {
moreRecent = "Book 2";
}
else
moreRecent = "Both";
return moreRecent;
}
}
public class Chpt2930BookTitleAuthorYear {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter title of Book: ");
String nextLine = scan.next();
Book titleofBook = new Book(nextLine);
}
}
编辑--------------------------
好感谢所有的答复! 我进一步改进了我的代码,但仍无法获得正确的结果。我特别在更近的方法上遇到困难。我如何设置这些书的年份?这里是我的代码:
class Book {
private String title;
private String author;
private String yearofPub;
Book(String input) {
title = input.toString();
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getYearofPub() {
return yearofPub;
}
public void setYearofPub(String yearofPub) {
this.yearofPub = yearofPub;
}
public String toString() {
System.out.println("Book{" + "Title=" + title + " Author=" + author + " Year of
Publication=" + yearofPub + "}");
return " ";
}
//confused on this part :(
String moreRecent(Book Book1, Book Book2) {
if (Book1.getYearofPub>Book.getYearofPub) { //Is this correct? I'm not sure :/
}
}
}
public class Chpt2930BookTitleAuthorYear {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter title of Book: ");
String nextLineTitle = scan.nextLine();
Book titleofBook = new Book(nextLineTitle);
System.out.println("Enter author of the Book: ");
String nextLineAuthor = scan.nextLine();
titleofBook.setAuthor(nextLineAuthor);
System.out.println("Enter the date of publication of the Book: ");
String nextLineDate = scan.nextLine();
titleofBook.setYearofPub(nextLineDate);
titleofBook.toString();
}
}
谢谢!
EDIT 2 -----------------
Nvm'd我发现这个问题:) 感谢所有帮助,虽然
'包括如下的方法来获取和设置私有实例variables'做到这一点。然而,你不会在'MoreRecent()'里面需要它们。另外为什么'moreRecent'具有'int'参数而不是'Book'参数? –