商店中有三种货物,建立一个货物类,包含货物名称,单价,建立桌布类,肥皂类,餐巾纸类继承货物类,并包含货量属性,按行依次输入桌布,肥皂,餐巾纸的单价和货量,中间以空格相隔,求出总价最大的商品,“XX货物总价最大为多少元”
输入用例:
51 221 54 5
输出用例:
餐巾纸总价最大,为270元
输入用例:
14 56 1 25 31 4
输出用例:
桌布总价最大,为784元
import java.util.Scanner;
// 定义货物类 Goods
class Goods {
private String name; // 货物名称
private double price; // 单价
// 构造函数
public Goods(String name, double price) {
this.name = name;
this.price = price;
}
// 获取货物名称
public String getName() {
return name;
}
// 获取单价
public double getPrice() {
return price;
}
// 计算总价(由子类实现)
public double getTotalPrice() {
return 0;
}
}
// 桌布类 TableCloth
class TableCloth extends Goods {
private int quantity; // 货量
// 构造函数
public TableCloth(double price, int quantity) {
super("桌布", price); // 调用父类构造函数
this.quantity = quantity;
}
// 计算总价
@Override
public double getTotalPrice() {
return getPrice() * quantity;
}
}
// 肥皂类 Soap
class Soap extends Goods {
private int quantity; // 货量
// 构造函数
public Soap(double price, int quantity) {
super("肥皂", price); // 调用父类构造函数
this.quantity = quantity;
}
// 计算总价
@Override
public double getTotalPrice() {
return getPrice() * quantity;
}
}
// 餐巾纸类 Tissue
class Tissue extends Goods {
private int quantity; // 货量
// 构造函数
public Tissue(double price, int quantity) {
super("餐巾纸", price); // 调用父类构造函数
this.quantity = quantity;
}
// 计算总价
@Override
public double getTotalPrice() {
return getPrice() * quantity;
}
}
// 主类
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// 输入桌布、肥皂、餐巾纸的单价和货量
double tableClothPrice = sc.nextDouble();
int tableClothQuantity = sc.nextInt();
double soapPrice = sc.nextDouble();
int soapQuantity = sc.nextInt();
double tissuePrice = sc.nextDouble();
int tissueQuantity = sc.nextInt();
// 创建对象
TableCloth tableCloth = new TableCloth(tableClothPrice, tableClothQuantity);
Soap soap = new Soap(soapPrice, soapQuantity);
Tissue tissue = new Tissue(tissuePrice, tissueQuantity);
// 计算总价
double tableClothTotal = tableCloth.getTotalPrice();
double soapTotal = soap.getTotalPrice();
double tissueTotal = tissue.getTotalPrice();
// 比较总价,找出最大值
if (tableClothTotal > soapTotal && tableClothTotal > tissueTotal) {
System.out.printf("桌布总价最大,为%.0f元\n", tableClothTotal);
} else if (soapTotal > tableClothTotal && soapTotal > tissueTotal) {
System.out.printf("肥皂总价最大,为%.0f元\n", soapTotal);
} else {
System.out.printf("餐巾纸总价最大,为%.0f元\n", tissueTotal);
}
}
}