用类的继承和多态特性、数组和欧式距离计算编写一个“已知数组中农产品的质量和体积, 判断农产品属于哪类农产品”的java代码
时间: 2023-05-19 11:06:48 浏览: 90
以下是示例代码:
```
public class FarmProduct {
protected double quality;
protected double volume;
public FarmProduct(double quality, double volume) {
this.quality = quality;
this.volume = volume;
}
public String getCategory() {
return "未知";
}
}
public class Vegetable extends FarmProduct {
public Vegetable(double quality, double volume) {
super(quality, volume);
}
@Override
public String getCategory() {
return "蔬菜";
}
}
public class Fruit extends FarmProduct {
public Fruit(double quality, double volume) {
super(quality, volume);
}
@Override
public String getCategory() {
return "水果";
}
}
public class FarmProductClassifier {
private static final int NUM_CATEGORIES = 2;
private static final double[][] CENTROIDS = {
{0.5, 0.5}, // 蔬菜的中心点
{0.8, 0.2} // 水果的中心点
};
public static String classify(FarmProduct product) {
double[] features = {product.quality, product.volume};
double minDistance = Double.MAX_VALUE;
int minIndex = -1;
for (int i = 0; i < NUM_CATEGORIES; i++) {
double distance = euclideanDistance(features, CENTROIDS[i]);
if (distance < minDistance) {
minDistance = distance;
minIndex = i;
}
}
switch (minIndex) {
case 0:
return "蔬菜";
case 1:
return "水果";
default:
return "未知";
}
}
private static double euclideanDistance(double[] a, double[] b) {
double sum = 0;
for (int i = 0; i < a.length; i++) {
double diff = a[i] - b[i];
sum += diff * diff;
}
return Math.sqrt(sum);
}
}
```
使用示例:
```
FarmProduct product = new Vegetable(0.8, 0.6);
String category = FarmProductClassifier.classify(product);
System.out.println(category); // 输出 "蔬菜"
```
这个示例代码中,我们定义了一个 FarmProduct 类作为基类,它包含了农产品的质量和体积两个属性,以及一个 getCategory 方法,用于返回农产品所属的类别。我们还定义了 Vegetable 和 Fruit 两个子类,它们分别重写了 getCategory 方法,返回蔬菜和水果两个类别。
我们还定义了一个 FarmProductClassifier 类,它包含了一个 classify 方法,用于根据农产品的质量和体积判断它所属的类别。这个方法使用了欧式距离计算两个特征向量之间的距离,并找到距离最近的中心点,从而确定农产品所属的类别。
阅读全文