对象比较 价值计算


题:
某游戏中的对象具有属性:
1. 材质: 木材,钢铁,合金,塑料
2. 颜色: 红 黑 黄 白
3. 形状: 方 圆 三角 五边
4. 尺寸: 整数 1 ~ 1000
请设计该对象的价值计算方法。属性的重要性从上到下减小。同一属性的值的重要性从左到右减小。
即: 材质好的不管颜色、尺寸,肯定有更高价值。
其它相同,红色的比黑色价值高
尺寸越小越值钱。

源码GameCompare.java


import java.util.Comparator;
import java.util.HashMap;
import java.util.TreeSet;
import java.util.Set;

class Game {
    private String material;
    private String color;
    private String shape;
    private int size;
    public Game(String m, String c, String s, int t) {
        this.material = m;
        this.color = c;
        this.shape = s;
        this.size = t;
    }
    public String getMaterial() {
        return material;
    }
    public String getColor() {
        return color;
    }
    public String getShape() {
        return shape;
    }
    public int getSize() {
        return size;
    }
    
    public String toString() {
        return "("+material+","+color+","+shape+","+size+")";
    }
}

class K implements Comparator<Object> {

    public int compare(Object a, Object b) {
        if (a instanceof Game == false || b instanceof Game == false) {
            return 0;
        }
        Game g1 = (Game) a;
        Game g2 = (Game) b;
        
        // Material
        HashMap<String, Integer> ma = new HashMap<String, Integer>();
        ma.put("木材", 1);
        ma.put("钢铁", 2);
        ma.put("合金", 3);
        ma.put("塑料", 4);
        int c1 = ma.get(g1.getMaterial()).compareTo(ma.get(g2.getMaterial()));
        if (c1!=0) {
            return c1;
        }
        // Color
        HashMap<String, Integer> co = new HashMap<String, Integer>();
        co.put("红", 1);
        co.put("黑", 2);
        co.put("黄", 3);
        co.put("白", 4);
        int c2 = co.get(g1.getColor()).compareTo(co.get(g2.getColor()));
        if (c2!=0) {
            return c2;
        }
        // Shape
        HashMap<String, Integer> sh = new HashMap<String, Integer>();
        sh.put("方", 1);
        sh.put("圆", 2);
        sh.put("三角", 3);
        sh.put("五边", 4);
        int c3 = sh.get(g1.getShape()).compareTo(sh.get(g2.getShape()));
        if (c3!=0) {
            return c3;
        }
        // Size
        int c4 = g1.getSize()-g2.getSize();
        if (c4!=0) {
            return c4;
        }
        return 0;
    }
}

public class GameCompare {
    public static void main(String[] args) {
        Set<Game> t=new TreeSet<Game>(new K());
        t.add(new Game("合金", "白", "三角", 1));
        t.add(new Game("钢铁", "白", "三角", 1));
        t.add(new Game("木材", "白", "三角", 1));
        t.add(new Game("木材", "白", "三角", 10));
        t.add(new Game("钢铁", "红", "三角", 1));
        t.add(new Game("钢铁", "红", "圆", 3));
        t.add(new Game("塑料", "红", "三角", 1));
        System.out.println(t);
    }
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注