[英]Java How to get the sum up all the of the values of each enum
我試圖了解如何獲取每個枚舉的所有值,並將它們全部添加到一個變量中。 我的代碼。
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);
}
我想知道如何添加每個枚舉的所有值並將其添加到一起。
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();
}
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());
OUTPUT:
BoxOfPaper
sum:1110
以下是您可能期望的完整代碼。
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
。
您首先需要一個訪問器方法來訪問整數值。 說.getInt()
。 一旦擁有它,請執行以下操作:
int sum = 0;
for (final Junk junk: Junk.values())
sum += junk.getInt();
// Now sum contains what you want
這段代碼不檢查溢出,但是您可以理解。
int total=0;
for (Junk j: Junk.values()) {
//retrieve each of the values and add it to total
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.