找到最大的变量

时间:2012-03-25 08:14:35

标签: java methods integer

我有五个以下的整数变量,在程序中,它们被随机分配了一些值。我想获得最大的变量名称,但不是变量值。我想知道它们中至少有两个是否具有相同的值。请举个例子。谢谢。

int politics_counter = 0;
        int economics_counter = 0;
        int foreign_counter = 0;
        int sport_counter = 0;
        int weather_counter = 0;

2 个答案:

答案 0 :(得分:1)

现在回答(有点)

public class MyThingie {

TreeMap<Integer, String> data = new TreeMap<Integer, String>();

public void doIt() {
    ...

    insertElement("politics_counter", politics_counter);
    insertElement("economics_counter", economics_counter);
    insertElement("foreign_counter", foreign_counter);
    insertElement("sport_counter", sport_counter);
    insertElement("weather_counter", weather_counter);

    System.out.println("Highest variable is "+data.lastEntry().getValue());
}

public void insertElement(String name, Integer i) {
    if (data.get(i) == null) {
        System.out.println("Element "+name+" has the name value as "+data.get(i));
    }
    else {
        data.put(name,i);
    }
}
}

现在有了一个更有趣的答案:

public class BiggestFinder {
    public void showBiggester(Object o) throws Exception {
        TreeMap<Integer, String> data = new TreeMap<Integer, String)();
        for (Field f  : o.getDeclaredFields()) {
            Object v = f.getValue(o);
            if (v instanceof Integer) {
                if (data.get(v)!=null) {
                    System.out.println("Value for "+f.getName()+" is the same as "+data.get(v));
                }
                else {
                    data.put((Integer)f.getValue(o), f.getName());
                }
            }
        }

        System.out.println("Largest is "+data.lastEntry().getValue());
    }
}

将询问一个对象并显示最大的字段,因为该对象具有所有整数的成员,并且该方法都可以访问。有一种方法可以捏造并改进它,使其更加“健壮”。

答案 1 :(得分:1)

正如@Max建议您可以使用地图存储变量,然后操纵地图以查找最大变量名称或值。

// Initialize your map
HashMap<String, Integer> vars = new HashMap<String,Integer>();

// Inserting a variable
vars.put("politics_counter", new Integer(0));

// Looking for biggest variable
String biggestVar = "";
for (String key : vars.keySet()) {
    if (key.length() > biggestVar.length)
        biggestVar = key;
}