以下是几本计算机书籍的基本信息
编号 书名 价格 出版社
1 JAVA基础 32 清华大学出版社
2 JAVA WEB开发 40 电子工业出版社
3 面向对象程序设计 28 清华大学出版社
4 Struts开发 30 人民邮电出版社
5 C语言基础 18 机械工业出版社
6 JAVA基础 32 电子工业出版社
请编写JAVA代码,按书名进行升序排序,如书名相同按价格升序排序,如书名与价格都相同则按出版社升序排列,并将排序后的书籍信息(包括编号,书名,价格,出版社)输出到屏幕。
1 package com.tiger.practice; 2 import java.util.Comparator; 3 4 5 public class Homework7 { 6 7 public class BookInfo{ 8 9 private String bookname; 10 private String press; 11 private int price; 12 private int num; 13 14 public BookInfo() 15 {} 16 17 public BookInfo(String bookname, String press, int price,int num) 18 { 19 this.bookname = bookname; 20 this.press = press; 21 this.price = price; 22 this.num=num; 23 24 } 25 26 public String getBookname() { 27 return bookname; 28 } 29 30 public String getPress() { 31 return press; 32 } 33 34 public int getPrice() { 35 return price; 36 } 37 38 public int getNum() { 39 return num; 40 } 41 //获取各个字段的值 42 43 44 public void setBook(String bookname, String press, int price,int num) { 45 46 this.bookname = bookname; 47 this.press = press; 48 this.price = price; 49 this.num=num; 50 51 } 52 //重置各个字段的值 53 54 public void show() 55 { 56 System.out.println(this.getBookname()+" "+this.getPrice()+" "+this.getPress()+" "+this.getNum()); 57 } 58 } 59 60 public class BookComparator implements Comparator<BookInfo>{ 61 public int compare(BookInfo o1, BookInfo o2) { 62 //当然可以用其他成员变量来作为衡量比较的标准 63 64 65 int x =o1.getBookname().compareTo(o2.getBookname()); 66 int y = o1.getPrice() - o2.getPrice(); 67 int z = (o1.getPress().compareTo(o2.getPress())); 68 69 if (x != 0) { 70 return x > 0 ? 1:-1; 71 } 72 if (y != 0) { 73 return y > 0 ? 1:-1; 74 } 75 if(z!=0) { 76 return z > 0 ? -1:1; 77 } 78 return o1.bookname.compareTo(o2.bookname); 79 } 80 } 81 82 83 }
Test
import com.tiger.practice.Homework7.BookInfo; 改成自己对应的。
1 package com.tiger.practice; 2 import java.util.Arrays; 3 import com.tiger.practice.Homework7.BookInfo; 4 5 6 public class Text5 { 7 8 public static void main(String args[]) 9 { 10 11 Homework7 sortbook=new Homework7(); 12 BookInfo [] bookInfo; 13 bookInfo=new BookInfo[6]; 14 15 16 bookInfo[0]=sortbook.new BookInfo(); 17 bookInfo[1]=sortbook.new BookInfo(); 18 bookInfo[2]=sortbook.new BookInfo(); 19 bookInfo[3]=sortbook.new BookInfo(); 20 bookInfo[4]=sortbook.new BookInfo(); 21 bookInfo[5]=sortbook.new BookInfo(); 22 23 bookInfo[0].setBook("JAVA基础","清华大学出版社 ",32,1); 24 bookInfo[1].setBook("JAVAWEB开发","电子工业出版社 ",40,2); 25 bookInfo[2].setBook("面向对象程序设计","清华大学出版社 ",28,3); 26 bookInfo[3].setBook("Struts开发","人民邮电出版社",30,4); 27 bookInfo[4].setBook("C语言基础","机械工业出版社 ",18,5); 28 bookInfo[5].setBook("JAVA基础","电子工业出版社",32,6); 29 30 Arrays.sort(bookInfo,sortbook.new BookComparator()); 31 32 for(int i=0;i<bookInfo.length;i++) { 33 bookInfo[i].show(); 34 } 35 36 } 37 38 }