【发布时间】:2013-12-17 23:25:01
【问题描述】:
我有一个包含 4 个 Java 类的 Java 应用程序,它们是 Menu,LoanBook(超类), FictionBook(扩展loanBook), NonFictionBook(扩展loanBook)
我被困在一种方法上——该方法的目的是从我的阵列中向学生发行一本书。我的目标是搜索一本书并将学生详细信息添加到该书中。我无法弄清楚我哪里出错了,我只是无法理解这种方法。
请忽略任何额外的变量,但要考虑其他所有因素,如果需要更多信息,任何建议都会非常有帮助..
我的问题是让某人检查一下,告诉我不需要什么以及我哪里出错了。有没有更简单的方法来做到这一点?
PS 我已经从原始代码更改了以下代码,但是在添加名称后我得到了运行时错误
static void issueBook() {
int choice,x = 0;
String title,name,date;
boolean found = false;
System.out.println("1.Fiction or 2.NonFiction?");
choice = keyboard.nextInt();
if (choice == 1){
System.out.println("Please enter the title of the book to loan:");
title = keyboard.next();
System.out.println("Please enter your name:");
name = keyboard.next();
date = "todays date";
do {
if (fictionBooksArray[x].getTitle().equals(title)){
found = true;
fictionBooksArray[x].setOnLoan(true);
fictionBooksArray[location].setName(name);
fictionBooksArray[location].setDate(date);
System.out.println("Loan successful ");
}
else x++;
}
while ((x < fictionBooksArray.length)&& (!found));
if (!found){
System.out.println("This book title could not be located.");
}
}
【问题讨论】:
-
真正的问题是什么?
-
尝试重构为一个接受 LoanBook[] 和标题的方法,并返回匹配数组中的书籍。这应该使它更具可读性。
-
嗨,戴夫,我已经更新了这个问题。 User60561,我不确定你的意思
-
public static LoanBook find(LoanBook[] books, String title)。返回尚未借出的具有给定名称的书。看起来 if 语句的两端是相同的,因此这将减少重复并使其更易于推理。 -
从描述中不清楚是什么问题,在哪个类中是方法……但很明显,在 else 分支中增加索引是错误的。您对“for”循环和“do”“while”使用相同的变量。其实我不明白“for”循环的目的。
标签: java arrays superclass subclassing