import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
public class Commodity {
static class Fruit {
String name;
int weight;
int value;
public Fruit(String name, int weight, int value) {
this.name = name;
this.weight = weight;
this.value = value;
}
}
public static void getMaxValueAndPrintSelection(Fruit[] fruits, int capacity) {
Arrays.sort(fruits, Comparator.comparingDouble(fruit -> (double) fruit.value / fruit.weight));
Collections.reverse(Arrays.asList(fruits));
double totalValue = 0;
System.out.println("选择的水果及其重量:");
for (Fruit fruit : fruits) {
if (capacity >= fruit.weight) {
totalValue += fruit.value;
capacity -= fruit.weight;
System.out.println(fruit.name + " " + fruit.weight);
} else {
double fraction = (double) capacity / fruit.weight;
totalValue += fraction * fruit.value;
System.out.println(fruit.name + " " + capacity);
break;
}
}
System.out.println("总价值: " + totalValue);
}
public static void main(String[] args) {
Fruit[] fruits = {
new Fruit("苹果", 15, 300),
new Fruit("香蕉", 18, 180),
new Fruit("橘子", 10, 150),
new Fruit("猕猴桃", 9, 270)
};
int capacity = 20;
getMaxValueAndPrintSelection(fruits, capacity);
}
}