java数组--对象数组的随机赋值及其他
包含考点:
- 对象数组的随机赋值
- 浮点数的指定位数
- 换用思路进行对象数组的某一属性进行排序
现有Book类,定义如下:
private String author;
private String ISBN;//书号
private double price;
public String getAuthor() {return this.author;}
public void setAuthor(String author) {this.author = author;}
public String getISBN() {return this.ISBN;}
public void setISBN(String ISBN) {this.ISBN = ISBN;}
public double getPrice() {return this.price;}
public void setPrice(double price) {this.price = price;}
请用一个数组存放随机产生的10个书籍对象,并显示其中书价最高的书号(要求使用对象数组完成)
package javaPractice;
import java.text.*;
import java.util.*;
public class TestBook {
public static void main(String[] argsment) {
Book[] book = new Book[10];
int j=0,k=0;
String[] name1 = {"杨红云","吴军","屈婉玲","李开复","凡尔纳","王小波"};
String[] name2 = {"ISBN 962-215-001-2","ISBN 962-215-001-3","ISBN 962-215-001-4","ISBN 962-215-001-5","ISBN 962-215-001-6","ISBN 962-215-001-8","ISBN 962-215-002-21"};
Random random = new Random();
DecimalFormat df = new DecimalFormat( "0.00");
double[] arr = new double[10];
for(int i=0;i<book.length;i++) {
book[i] = new Book();
}
for(int i=0;i<book.length;i++) {
j = random.nextInt(name1.length);
k = random.nextInt(name2.length);
book[i].setAuthor(name1[j]);
book[i].setISBN(name2[k]);;
book[i].setPrice(random.nextDouble()*200);
arr[i] = book[i].getPrice();
}
for(int i=0;i<book.length;i++) {
System.out.print("author:"+book[i].getAuthor());
System.out.print(" "+book[i].getISBN());
System.out.println(" price:"+df.format(book[i].getPrice()));
}
Arrays.sort(arr);
for(int i=0;i<book.length;i++) {
if(book[i].getPrice() == arr[arr.length-1]) {
System.out.println("书价最高图书的书号为"+book[i].getISBN());
}
}
}
}
class Book{
private String author;
private String ISBN;//书号
private double price;
public String getAuthor() {return this.author;}
public void setAuthor(String author) {this.author = author;}
public String getISBN() {return this.ISBN;}
public void setISBN(String ISBN) {this.ISBN = ISBN;}
public double getPrice() {return this.price;}
public void setPrice(double price) {this.price = price;}
}