编辑代码

class Main {

    static class Commodity {
        String name;
        int weight;
        int price;

        public Commodity(String name, int weight, int price){
            this.name = name;
            this.weight = weight;
            this.price = price;
        }
    }

    public static void bestSelect(int maxWeight, Commodity[] commodity){
        int index = 0;
        int maxPrice = 0;
        for(int i = 0; i < Math.pow(2, commodity.length); i++){
            int pos = i; 
            int weight = 0;
            int price = 0;
            int j = 0;
            while(pos > 0){
                if((pos & 1) == 1){
                    weight += commodity[j].weight;
                    price += commodity[j].price;
                }
                pos = pos >> 1;
                j++;
            }

            if(weight <= maxWeight && price > maxPrice){
                index = i;
                maxPrice = price;
            }
        }

        for(int i = 0; index > 0; i++, index = index >> 1){
        	if((index & 1) == 1) {
        		System.out.println(commodity[i].name + ": 重量:"  + commodity[i].weight + ",价值:" + commodity[i].price);
        	}
        }
    }

	public static void main(String[] args) {
        
        Commodity commodity[] = {
            new Commodity("音响", 30, 3000),
            new Commodity("笔记本电脑", 20, 2000),
            new Commodity("吉他", 15, 1500)
        };

		bestSelect(35,commodity);
	}
}