在java语言中用继承,数组写一个已知某个农产品的质量和体积,计算平均质量和平均体积,判断农产品属于哪类农产品”的代码
时间: 2023-05-15 08:06:30 浏览: 79
以下是Java代码:
```
public class FarmProduct {
protected double quality;
protected double volume;
public FarmProduct(double quality, double volume) {
this.quality = quality;
this.volume = volume;
}
public double getQuality() {
return quality;
}
public double getVolume() {
return volume;
}
}
public class Grain extends FarmProduct {
public Grain(double quality, double volume) {
super(quality, volume);
}
}
public class Fruit extends FarmProduct {
public Fruit(double quality, double volume) {
super(quality, volume);
}
}
public class Main {
public static void main(String[] args) {
FarmProduct[] products = new FarmProduct[5];
products[0] = new Grain(10, 20);
products[1] = new Grain(15, 25);
products[2] = new Fruit(5, 10);
products[3] = new Fruit(8, 12);
products[4] = new Fruit(12, 15);
double totalQuality = 0;
double totalVolume = 0;
for (FarmProduct product : products) {
totalQuality += product.getQuality();
totalVolume += product.getVolume();
}
double avgQuality = totalQuality / products.length;
double avgVolume = totalVolume / products.length;
if (avgQuality > 10 && avgVolume > 15) {
System.out.println("这是高质量大体积的农产品");
} else if (avgQuality > 10 && avgVolume <= 15) {
System.out.println("这是高质量小体积的农产品");
} else if (avgQuality <= 10 && avgVolume > 15) {
System.out.println("这是低质量大体积的农产品");
} else {
System.out.println("这是低质量小体积的农产品");
}
}
}
```
这段代码定义了一个 FarmProduct 类,它有两个属性:quality 和 volume,分别表示农产品的质量和体积。然后定义了两个子类 Grain 和 Fruit,分别表示谷物和水果。在 Main 类中,创建了一个 FarmProduct 数组,包含了 5 个不同的农产品。然后遍历数组,计算出所有农产品的平均质量和平均体积,并根据平均质量和平均体积的大小判断农产品属于哪一类。
阅读全文