栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Comparable接口实现

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Comparable接口实现

【问题描述】编写一个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: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:as same books   【样例说明】 输入和输出的格式要和指定格式严格匹配,否则不得分。   【评分标准】 结果完全正确得满分。
代码

import java.util.ArrayList;

import java.util.Iterator;

import java.util.Scanner;

 

class Book implements Comparable {

 String name;

 double price;

 public Book(String name,double price){

  this.name=name;

  this.price=price;

 }

 public int compareTo(Book b) {

  return (int)(this.price-b.price);

 }

 

}

public class TestBook{

 public static void main(String[] s) {

  String str;

  System.out.println("input several Book,in the end #");

  Scanner in = new Scanner(System.in);

  ArrayListlist=new ArrayList();

  //可修改动态数组,类型为Book

  while(true) { //无限循环

   str=in.nextLine();

   if("#".equals(str)) {

    break; //"#"结束循环

   }

   String[] info=str.split(",");

   String name=info[0];

   double price=Double.parseDouble(info[1]);

   list.add(new Book(name,price));

  }

  //获取迭代器

  Iteratorit=list.iterator();

  

  System.out.println("input a new Book:");

  str=in.nextLine();

  String[] info=str.split(",");

  String name=info[0];

  double price=Double.parseDouble(info[1]);

  Book book=new Book(name,price);

  

  System.out.println("new book:<"+name+">as same books");

  while(it.hasNext()) { //当前集合还有元素

   Book b=it.next();

   if(book.price==b.price) {

    System.out.println(b.name+","+b.price);

   }

  }

  

 }

}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/925146.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号