以下是几本计算机书籍的基本信息
编号 书名 价格 出版社
1 JAVA基础 32 清华大学出版社
2 JAVA WEB开发 40 电子工业出版社
3 面向对象程序设计 28 清华大学出版社
4 Struts开发 30 人民邮电出版社
5 C语言基础 18 机械工业出版社
6 JAVA基础 32 电子工业出版社
请编写JAVA代码,按书名进行升序排序,如书名相同按价格升序排序,如书名与价格都相同则按出版社升序排列,并将排序后的书籍信息(包括编号,书名,价格,出版社)输出到屏幕。
package com.tiger.practice;
import java.util.Comparator; public class Homework7 { public class BookInfo{ private String bookname;
private String press;
private int price;
private int num; public BookInfo()
{} public BookInfo(String bookname, String press, int price,int num)
{
this.bookname = bookname;
this.press = press;
this.price = price;
this.num=num; } public String getBookname() {
return bookname;
} public String getPress() {
return press;
} public int getPrice() {
return price;
} public int getNum() {
return num;
}
//获取各个字段的值 public void setBook(String bookname, String press, int price,int num) { this.bookname = bookname;
this.press = press;
this.price = price;
this.num=num; }
//重置各个字段的值 public void show()
{
System.out.println(this.getBookname()+" "+this.getPrice()+" "+this.getPress()+" "+this.getNum());
}
} public class BookComparator implements Comparator<BookInfo>{
public int compare(BookInfo o1, BookInfo o2) {
//当然可以用其他成员变量来作为衡量比较的标准 int x =o1.getBookname().compareTo(o2.getBookname());
int y = o1.getPrice() - o2.getPrice();
int z = (o1.getPress().compareTo(o2.getPress())); if (x != ) {
return x > ? :-;
}
if (y != ) {
return y > ? :-;
}
if(z!=) {
return z > ? -:;
}
return o1.bookname.compareTo(o2.bookname);
}
} }
Test
import com.tiger.practice.Homework7.BookInfo; 改成自己对应的。
package com.tiger.practice;
import java.util.Arrays;
import com.tiger.practice.Homework7.BookInfo; public class Text5 { public static void main(String args[])
{ Homework7 sortbook=new Homework7();
BookInfo [] bookInfo;
bookInfo=new BookInfo[]; bookInfo[]=sortbook.new BookInfo();
bookInfo[]=sortbook.new BookInfo();
bookInfo[]=sortbook.new BookInfo();
bookInfo[]=sortbook.new BookInfo();
bookInfo[]=sortbook.new BookInfo();
bookInfo[]=sortbook.new BookInfo(); bookInfo[].setBook("JAVA基础","清华大学出版社 ",,);
bookInfo[].setBook("JAVAWEB开发","电子工业出版社 ",,);
bookInfo[].setBook("面向对象程序设计","清华大学出版社 ",,);
bookInfo[].setBook("Struts开发","人民邮电出版社",,);
bookInfo[].setBook("C语言基础","机械工业出版社 ",,);
bookInfo[].setBook("JAVA基础","电子工业出版社",,); Arrays.sort(bookInfo,sortbook.new BookComparator()); for(int i=;i<bookInfo.length;i++) {
bookInfo[i].show();
} } }