- 定义一个类表示上表中的商品
- 创建5个对象存储上面表的信息
- 创建一个数组,存储这5个对象。
- 在创建一个方法,遍历(toString())这个数组,打印表的信息。
- 创建一个方法:查询最终购买价,大于指定数字的所有商品
import java.util.Scanner;
class Commodity {
private int id;
private String name;
private String model;
private int price;
private double discount;
public Commodity(int id, String name, String modle, int price, double discount) {
this.id = id;
this.name = name;
this.model = modle;
this.price = price;
this.discount = discount;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getPrice() {
return price;
}
public void setPice(int price) {
this.price = price;
}
public double getDiscount() {
return discount;
}
public void setDiscount(double discount) {
this.discount = discount;
}
@Override
public String toString() {
return "Commodity{" +
"id=" + id +
", name='" + name + '\'' +
", model='" + model + '\'' +
", price=" + price +
", discount=" + discount +
'}';
}
}
public class TwoDimensionalArray {
public static void main(String[] args) {
Commodity comm1 = new Commodity(01, "苹果手机", "IPhone13 Pro Max", 10000, 0.9);
Commodity comm2 = new Commodity(02, "华为手机", "P40", 8000, 0.8);
Commodity comm3 = new Commodity(03, "苹果电脑", "iMac", 12000, 0.7);
Commodity comm4 = new Commodity(04, "华为电脑", "L480", 13000, 0.8);
Commodity comm5 = new Commodity(05, "小米手机", "红米60", 7000, 0.9);
Commodity[] commoditie = {comm1, comm2, comm3, comm4, comm5};
selectByprice(commoditie, 5000);
printComms(commoditie);
}
public static void selectByprice(Commodity[] commodities, int price) {
System.out.println("************商品查询*************");
System.out.println("最终购买价大于" + price + "的商品如下");
for (Commodity dity : commodities) {
double resultPrice = dity.getPrice() * dity.getDiscount();
if (resultPrice > price) {
System.out.println(dity.getName() + "最终购买价" + resultPrice);
}
}
}
public static void printComms(Commodity[] commodities) {
System.out.println("ID\t名称\t\t\t\t型号\t\t价格\t\t折扣");
for (Commodity idity : commodities) {
System.out.println(idity.getId() + "\t" +
idity.getName() + "\t\t" +
idity.getModel() + "\t" +
idity.getPrice() + "\t" +
idity.getDiscount());
}
for (Commodity ity : commodities) {
System.out.println(ity.toString());
}
System.out.println("请输入你想要的价格:");
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
System.out.println("高于这个价格的有");
for (Commodity commodity : commodities) {
if (commodity.getPrice() * commodity.getDiscount() > a) {
System.out.println(commodity.toString());
}
}
}
}