编辑代码

import java.util.ArrayList;  
import java.util.Collections;  
import java.util.Comparator;  
import java.util.List;  
  
public class FruitPacking {  
    public static void main(String[] args) {  
        List<Fruit> fruits = new ArrayList<>();  
        fruits.add(new Fruit("苹果", 15, 300));    
        fruits.add(new Fruit("香蕉", 18, 180));  
        fruits.add(new Fruit("橘子", 10, 150));  
        fruits.add(new Fruit("猕猴桃", 9, 270));  
          
        // 根据单位重量价值降序排序  
        Collections.sort(fruits, Comparator.comparingDouble(f -> -f.getValuePerWeight()));  
          
        int capacity = 20;  
        int totalValue = 0;  
        List<PackedFruit> packedFruits = new ArrayList<>();  
          
        for (Fruit fruit : fruits) {  
            if (capacity > 0) {  
                String name = fruit.getName();  
                int weight = fruit.getWeight();  
                int value = fruit.getValue();  
                if (weight <= capacity) {  
                    // 如果水果的重量小于等于背包剩余容量,全部装入  
                    packedFruits.add(new PackedFruit(name, weight));  
                    capacity -= weight;  
                    totalValue += value;  
                    // 实验人:陈文龙(学号:20052150)  
                } else {  
                    // 如果水果的重量大于背包剩余容量,装入部分  
                    double fraction = (double) capacity / weight;  
                    packedFruits.add(new PackedFruit(name, weight * fraction));  
                    totalValue += value * fraction;  
                    // 背包已满  
                    capacity = 0;  
                }  
            }  
        }  
          
        // 打印结果  
        System.out.println("装入背包的水果和它们的重量: " + packedFruits);  
        System.out.println("背包中水果的总价值: " + totalValue);  
    }  
}  
  
class Fruit {  
    private String name;  
    private int weight;  
    private int value;  
    public Fruit(String name, int weight, int value) {  
        this.name = name;  
        this.weight = weight;  
        this.value = value;  
    }  
    public String getName() {  
        return name;  
    }  
    public int getWeight() {  
        return weight;  
    }  
    public int getValue() {  
        return value;  
    }  
    public double getValuePerWeight() {  
        return (double) value / weight;  
    }  
}  
  
class PackedFruit {  
    private String name;  
    private double weight;  
    public PackedFruit(String name, double weight) {  
        this.name = name;  
        this.weight = weight;  
    }  
    @Override  
    public String toString() {  
        return "(" + name + ", " + weight + "kg)";  
    }  
}