编写一个Book类,该类至少有name和price两个属性。
package Test;
import java.util.ArrayList;
import java.util.Scanner;
public class Mybook {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 定义一个Book类的动态数组,用于存储放入的书
ArrayList<Book> book = new ArrayList<>();
System.out.println("input several Book,in the end #");
while(true){//循环判断,并读入存储数据
String input =in.nextLine();
if (input.equals("#")){
break;
}
String[] a = input.split(",");//题目要求以此为分界符号,被","分界的信息将存储在a数组中,a[0],a[1]....
String a1 = a[0];
int a2 = Integer.parseInt(a[1]);//转换为数字
Book b = new Book();
b.setName(a1);//set方法
b.setPrice(a2);
book.add(b);//添加到动态数组中
}
System.out.println("input a new Book:");
String input1 = in.nextLine();
String[] c = input1.split(",");
String c1 = c[0];
int c2 = Integer.parseInt(c[1]);
Book b1 = new Book();
b1.setName(c1);
b1.setPrice(c2);
b1.compareTo(b1,book);//调用方法
in.close();
}
}
class Book implements Comarable{
String name;
double price;
public void setName(String name) {
this.name = name;
}
public void setPrice(int price) {
this.price = price;
}
}
//定义接口,接口中定义方法
interface Comarable{
default void compareTo(Book b1,ArrayList<Book> books){
System.out.println("new book:<"+b1.name+">as same books");
// 循环遍历动态数组,并进行比对
for (Book book : books) {
if (b1.price == book.price) {
System.out.println(book.name + "," + book.price);
}
}
}
}