编辑代码

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);//调用子程序开始计算
    }
}