编辑代码

import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedList;

class Main {
    public static void main(String[] args) {
        Greed_Law greed_Law=new Greed_Law();
        Fruit[] Fruits = {
                new Fruit("苹果", 15, 300),
                new Fruit("香蕉", 18, 180),
                new Fruit("橘子", 10, 150),
                new Fruit("猕猴桃", 9, 270),
        };
        Greed_Law.Printf(Fruits,20);

    }
}
class Fruit {
    public String name;
    public int Weight;
    public int Value;
    Fruit(String itemName, int weight, int value) {
        this.name = itemName;
        this.Weight = weight;
        this.Value = value;
    }
    Fruit(Fruit fruit) {
        this.name = fruit.name;
        this.Weight = fruit.Weight;
        this.Value = fruit.Value;
    }
}

class Greed_Law
{
       public static void Printf(Fruit[] fruitList,int weight) {
        LinkedList<Fruit> beans = packBean(weight, fruitList);
        int MaxPrices = 0;
        System.out.println("最终行使的策略如下:");
        for (int i = 0; i < beans.size(); ++i) {
            MaxPrices =MaxPrices+ beans.get(i).Value;
            System.out.println( "装入 " + beans.get(i).Weight+"Kg "+beans.get(i).name+"。");
        }
        System.out.println("最终的总价值为:" + MaxPrices+"元");

    }
    public static LinkedList<Fruit> packBean(int bagweight, Fruit[] FruitList){
        LinkedList<Fruit> beans = new LinkedList<Fruit>();
        Arrays.sort(FruitList, new Comparator<Fruit>() {
            @Override
            public int compare(Fruit F1, Fruit F2) {
                int left=F1.Value/ F1.Weight;
                int right=F2.Value/F2.Weight;
                if(left>right)
                {
                    return -1;
                }
                else if(left==right)
                {
                    return 0;
                }
                else{
                    return 1;
                }
            }
        });
        int leftpackcapacity=bagweight;
        for (int i = 0; i < FruitList.length; i++) {
            if(leftpackcapacity>FruitList[i].Weight){
                leftpackcapacity-=FruitList[i].Weight;
                beans.add(new Fruit(FruitList[i]));
            }
            else{
                int price=FruitList[i].Value/FruitList[i].Weight;
                int weight=leftpackcapacity;
                int value=weight*price;
                beans.add(new Fruit(FruitList[i].name,weight,value));
                leftpackcapacity=0;
                break;
            }
        }
        return beans;
    }
 

}