Java如何总结每个枚举的所有值

时间:2011-12-24 01:12:38

标签: java enums sum

我试图了解如何获取每个枚举的所有值,并将所有值一起添加到一个变量中。我的代码。

enum Junk {

Wrapper(0),
SilverCoins(150), 
Dresser(250),
Sofa(250),
ChippedBat(0),
BrokenMicrowave(0),
SilverWare(35),
Newspapers(0),
Book(20),
Clothes(60),
Plates(40),
Cups(25),
DiningTable(200),
Chair(30),
BoxOfPaper(10),
BucketofPaint(10),
Watch(30);

}

我想知道如何添加每个枚举的所有值并将它们加在一起。

5 个答案:

答案 0 :(得分:1)

enum Junk {

    Wrapper(0),
    SilverCoins(150), 
    Dresser(250),
    Sofa(250),
    ChippedBat(0),
    BrokenMicrowave(0),
    SilverWare(35),
    Newspapers(0),
    Book(20),
    Clothes(60),
    Plates(40),
    Cups(25),
    DiningTable(200),
    Chair(30),
    BoxOfPaper(10),
    BucketofPaint(10),
    Watch(30);

    private int value;

    private Junk(int value){
        this.value = value;
    }

    public int getValue(){
        return value;
    }

}

获取枚举值:

int sofaValue = Junk.Sofa.getValue();

添加代码:

int junkSum = 0;

for(Junk junk : junk.values()){
    junkSum += junk.getValue();
}

答案 1 :(得分:1)

public class Brand{
    private static int sum;

    public static int getSum() {
        return sum;
    }

    public enum Junk  
    {
        Wrapper(0),
        SilverCoins(150), 
        Dresser(250),
        Sofa(250),
        ChippedBat(0),
        BrokenMicrowave(0),
        SilverWare(35),
        Newspapers(0),
        Book(20),
        Clothes(60),
        Plates(40),
        Cups(25),
        DiningTable(200),
        Chair(30),
        BoxOfPaper(10),
        BucketofPaint(10),
        Watch(30);
        private int value;

        private Junk (int value){
            this.value = value;
            sum = sum + value;
        }

        public int getValue(){
            return value;
        }
    }
 }
主要

System.out.println(Brand.Junk .BoxOfPaper);
System.out.println("sum:"+Brand.getSum());  

<强>输出:

BoxOfPaper
sum:1110

答案 2 :(得分:1)

以下是您可能期望的完整代码。

package enumtest;

enum Junk
{
    Wrapper(0),
    SilverCoins(150),
    Dresser(250),
    Sofa(250),
    ChippedBat(0),
    BrokenMicrowave(0),
    SilverWare(35),
    Newspapers(0),
    Book(20),
    Clothes(60),
    Plates(40),
    Cups(25),
    DiningTable(200),
    Chair(30),
    BoxOfPaper(10),
    BucketofPaint(10),
    Watch(30);

    private int value;

    private Junk(int value)
    {
        this.value=value;
    }

    public int getValue()
    {
        return(value);
    }
}

final public class Main
{
    public static void main(String...args)
    {
        int sum=0;

        for(Junk o:Junk.values())
        {
            sum+=o.getValue();
        }

        System.out.println("sum  = "+sum);
    }
}

如果您试一试,会在控制台上显示sum = 1110

答案 3 :(得分:0)

首先需要一个访问器方法来访问整数值。说,.getInt()。一旦你拥有它,做这样的事情:

int sum = 0;

for (final Junk junk: Junk.values())
    sum += junk.getInt();

// Now sum contains what you want

此代码不会检查溢出,但您明白了。

答案 4 :(得分:0)

int total=0;

for (Junk j: Junk.values()) {  
 //retrieve each of the values and add it to total
}