大家好,又见面了,我是你们的朋友全栈君。
importjava.util.*;importjava.io.*;abstractclassGood{Stringname;doubleprice;Good(Stringname,doubleprice){this.name=name;this.price=price;}}classBookextendsGood{Stringname;…
import java.util.*;
import java.io.*;
abstract class Good{
String name;
double price;
Good(String name,double price){
this.name=name;
this.price=price;
}
}
class Book extends Good{
String name;
double price;
int passage;
Book(String name,double price,int passage){
super(name,price);
this.passage=passage;
}
public String toString(){
return “name:”+name+” price:”+price+” passage:”+passage;
}
}
class NoGoodException extends Exception{
public NoGoodException(String msg){
super(msg);
}
}
interface Shopper{
void add(Good good);
void buy(String n) throws NoGoodException;
}
class Shop implements Shopper {
private List bookArrayList = new ArrayList<>();
@Override
public void add(Good good) {
if (good instanceof Book) {
addBook((Book) good);
}}
private void addBook(Book book) {
bookArrayList.add(book);
}
public void buy(String n) throws NoGoodException {
for (Book book : bookArrayList) {
if (book.name == n) {
System.out.println(“You buy it!!! ” + book.toString());
bookArrayList.remove(book);
return;
}
}
throw new NoGoodException(n + ” no found”);}
}
public class a {
public static void main(String[] args) throws Exception {
Good book1 = new Book(“book1”, 10, 155);
Good book2 = new Book(“book2”, 12, 168);
Shop shop = new Shop();
shop.add(book1);
shop.add(book2);
try {
shop.buy(“book1”);
shop.buy(“book20”);
} catch (NoGoodException a) {
System.out.println(a.getMessage());
}
}
}
只能输出一行。。。而且输出的结果明显不是我想要的
展开
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/151907.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...