编辑代码

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


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

        };
        strategy.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 Strategy
{
    public static LinkedList<Fruit> packBean(int bagweight, Fruit[] Fruits){
        LinkedList<Fruit> beans = new LinkedList<Fruit>();
        Arrays.sort(Fruits, new Comparator<Fruit>() {
            @Override
            public int compare(Fruit o1, Fruit o2) {
                int left=o1.Value/ o1.Weight;
                int right=o2.Value/o2.Weight;
                if(left>right)
                {
                    return -1;
                }
                else if(left==right)
                {
                    return 0;
                }
                else{
                    return 1;
                }
            }
        });
        int leftpackcapacity=bagweight;
        for (int i = 0; i < Fruits.length; i++) {
            if(leftpackcapacity>Fruits[i].Weight){
                leftpackcapacity-=Fruits[i].Weight;
                beans.add(new Fruit(Fruits[i]));
            }
            else{
                int price=Fruits[i].Value/Fruits[i].Weight;
                int weight=leftpackcapacity;
                int value=weight*price;
                beans.add(new Fruit(Fruits[i].name,weight,value));
                leftpackcapacity=0;
                break;
            }
        }
        return beans;
    }
    public static void Printf(Fruit[] fruits,int weight) {
        LinkedList<Fruit> beans = packBean(weight, fruits);
        int maxvalue = 0;
        System.out.println("装水果策略如下,可以获得最大价值,必定取胜:");
        for (int i = 0; i < beans.size(); ++i) {
            maxvalue =maxvalue+ beans.get(i).Value;
            System.out.println( "装入 " + beans.get(i).Weight+"个"+beans.get(i).name );
        }
        System.out.println("这样做可以得到的总价值:" + maxvalue);

    }

}