根据类中的一个变量,对类数组进行排序
import *;
import java.util.*;
//商品类
class Goods{
private String name;
private int identifier;
private double price;
private int number;
public void setName(String n){
name=n;
}
public void setIdentifier(int i){
identifier=i;
}
public void setPrice(double p){
price=p;
}
public void setNumber(int n){
number=n;
}
public String getName(){
return name;
}
public double getPrice(){
return price;
}
public int getIdentifier(){
return identifier;
}
public int getNumber(){
return number;
}
}
public class Lianxi2 {
public static void main(String[] args) throws IOException{
Goods[] g=new Goods[2];
Goods[] goods=new Goods[2];
BufferedWriter f1 = new BufferedWriter(new FileWriter("goods.txt"));
File file= new File("goods.txt");
Scanner in=new Scanner(file);
Scanner input= new Scanner(System.in);
int i,j,t;
String name;
double price;
int number;
int identifier;
long sum;
String s;
//从键盘读取并写入文件中
for (i=0;i<2;i++){
g[i]=new Goods();
System.out.print("请输入商品编号:");
identifier=input.nextInt();
g[i].setIdentifier(identifier);
System.out.print("请输入商品名称:");
name=input.next();
g[i].setName(name);
System.out.print("请输入商品单价:");
price=input.nextDouble();
g[i].setPrice(price);
System.out.print("请输入商品数量:");
number=input.nextInt();
g[i].setNumber(number);
}
for(i=0;i<2;i++){
f1.write(g[i].getIdentifier()+" "+g[i].getName()+" "+ g[i].getPrice()+" "+ g[i].getNumber()+"\r\n");
}
f1.close();
/*
for(i=0;i<4;i++){
g[i].setIdentifier(0);
g[i].setName("");
g[i].setPrice(0);
g[i].setNumber(0);
}
*/
//从文件中读取
i=0;
while(in.hasNext()){
int a = in.nextInt();
String b = in.next();
double c= in.nextDouble();
int d = in.nextInt();
g[i].setIdentifier(a);
g[i].setName(b);
g[i].setPrice(c);
g[i].setNumber(d);
i++;
}
in.close();
//想实现根据价格对商品进行排序
for(i=0;i<3;i++){
goods[i]=new Goods();
for(j=i+1;j<4;j++){
if((g[i].getPrice())<(g[j].getPrice())){
t=j; j=i;i=t;
}
}
}
//打印
for(i=0;i<4;i++){
System.out.println(goods[i].getIdentifier()+" "+goods[i].getName()+" "+goods[i].getPrice()+" "+goods[i].getNumber() );
}
}
}