【问题描述】编写一个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
【样例说明】
输入和输出的格式要和指定格式严格匹配,否则不得分。
【评分标准】
结果完全正确得满分。
【备注】
从键盘读入一行字符串,可以用如下代码:
Scanner in = new Scanner(System.in);
name = in.nextLine();
可以用String.split(",")方法对字符串以逗号分成若干部分。
使用Scanner类,需要导入import java.util.Scanner;
package nine;
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(Object b) {
Book book=(Book)b;
return (int) (this.price-book.price);
}
}
public class One {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("input several Book,in the end #");
Scanner sc=new Scanner(System.in);
String a=sc.nextLine();
int i=0;
Book b[]=new Book[10];
for(int j=0;;j++)
{
String[] a1=a.split(",");
double d=Double.parseDouble(a1[1]);
b[i]=new Book(a1[0],d);
i++;
a=sc.nextLine();
String x="#";
if(a.equals(x)==true){
break;
}
}
System.out.println("input a new Book:");
a=sc.nextLine();
String[] a1=a.split(",");
double d=Double.parseDouble(a1[1]);
b[i]=new Book(a1[0],d);
System.out.println("new book:<"+b[i].name+">as same books");
for(int j=0;j<i;j++)
{
int t=b[i].compareTo(b[j]);
if(t==0)
{
System.out.println(b[j].name+","+b[j].price);
break;
}
}
}
}