编写一个Book类,该类至少有name和price两个属性。

【问题描述】编写一个Book类,该类至少有name和price两个属性。该类要实现Comarable接口,在接口的compareTo()方法中规定两个Book类实例的大小关系为二者的price属性的大小关系。在主函数中,选择合适的集合类型存放Book类的若干个对象,然后创建一个新的Book类的对象,并检查该对象与集合中的哪些对象相等。

【输入形式】每一行输入一个Book类的对象,名字和价格之间用逗号分隔,集合类的输入结束符号是#,然后输入一个新的Book类对象。

【输出形式】
显示查找结果,如果找到了,就显示具体对象的信息,没找到,就不显示。

【样例输入1】
input several Book,in the end #
yuwen,10
shuxue,12
yingyu,11

input a new Book:
kexue,12

【样例输出1】
new book:kexue as same books
shuxue,12.0

【样例输入2】
input several Book,in the end #
yuwen,10
shuxue,12
waiyu,11

input a new Book:
kexue,13

【样例输出2】
new book:kexue as same books
可借鉴:

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);
             }
         }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_52050769/article/details/117308244
今日推荐