Java基础问题(追加80分)

来源:百度知道 编辑:UC知道 时间:2024/06/14 19:36:01
帮忙看下一下代码``就是那个根据书名查询书籍这块``老出现错误``打印出来的书``老是,几本一块出``还会出现程序异常``真不知道怎么回事``麻烦大家``帮帮忙了`````
import java.util.*;
interface Book
{
public int getPrice();
public String getBookname();
public String getBookxin();
};
class Computer implements Book
{
private int price;
private String bookname;
private String bookxin;
public Computer(String bookname,int price,String bookxin)
{
this.setBookname(bookname);
this.setPrice(price);
this.setBookxin(bookxin);
}
public void setPrice(int price)
{
this.price = price;
}
public void setBookname(String book)
{
this.bookname = book;
}
public void setBookxin(String xin)
{
this.bookxin = xin;
}
public int getPrice()
{
return this.price;
}
public String getBookname()
{
return this.bookname;<

兄弟,你的 Bookshop 中的 bookname 方法写错了。

你运行的时候肯定是抛 ElementNotFound异常,对不对?

原来那个方法是这样的 :
public String bookname(String book)//根据书名查询书籍功能
{ String shu = null;
Iterator itr = this.fun().iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
Book b = (Book)itr.next();
if(b.equals(book))
{
shu = book;
break;
}
}
return shu ;
}

1)你在里面加了打印所有迭代过的书的toString方法值,所以,看到很多书。
2)其次你在while 循环中使用了两个 itr.next(), 而实际上 一次循环只判断一次。所以最后一定抛出异常。
3)你在匹配的时候应该是书名,而不是书对象本身,所以你根本没有找到你要找的书

我帮你修改了一下 bookname 方法:

public String bookname(String book)// 根据书名查询书籍功能
{
String shu = null;
Iterator itr = this.fun().iterator();

while (itr.hasNext()) {
Book b = (Book) itr.next();
//打印所有被匹配过的书的名字。
System.out.println("has searched book name : "+b.getBookname());