這是您要求的Die類... Alex您是否可以進一步解釋在我的Die類中使用.getValue?Array和ArrayClass列表的總和
public class Die
{
private final int MAX = 6; // maximum face value
private int faceValue; // current value showing on the die
//-----------------------------------------------------------------
// Constructor: Sets the initial face value.
//-----------------------------------------------------------------
public Die()
{
faceValue = 1;
}
//-----------------------------------------------------------------
// Rolls the die and returns the result.
//-----------------------------------------------------------------
public int roll()
{
faceValue = (int)(Math.random() * MAX) + 1;
return faceValue;
}
//-----------------------------------------------------------------
// Face value mutator.
//-----------------------------------------------------------------
public void setFaceValue (int value)
{
faceValue = value;
}
//-----------------------------------------------------------------
// Face value accessor.
//-----------------------------------------------------------------
public int getFaceValue()
{
return faceValue;
}
//-----------------------------------------------------------------
// Returns a string representation of this die.
//-----------------------------------------------------------------
public String toString()
{
String result = Integer.toString(faceValue);
return result;
}
}
我使用不同的代碼來找到我的數組和ArrayList的總和嘗試...這裏是我的代碼。有人可以告訴我如何解決這個問題。
import java.util.ArrayList;
public class Driver {
public static void main(String[] args) {
// TODO Auto-generated method stub
final int SIZE = 10;
Die sumArray;
Die sumArrayList;
Die[] DieList = new Die[SIZE];
ArrayList<Die> DieList2 = new ArrayList<Die>();
for (int i = 0; i < SIZE; i++)
{
DieList[i] = new Die();
}
for (int i = 0; i < SIZE; i++)
{
DieList2.add(new Die());
}
for (int i = 0; i < SIZE; i++)
{
DieList[i].roll();
}
for (int i = 0; i < SIZE; i++)
{
DieList2.get(i).roll();
}
System.out.print("Array: ");
for (int i = 0; i < SIZE; i++)
{
System.out.print(DieList[i] + " ");
}
System.out.println();
System.out.println("ArrayList: " + DieList2); //.get(index) specific index value in the arrayList
for (Die i : sumArray){
sumArray+= i;
}
// sumArrayList = (DieList2(0) + DieList[1] + DieList[2] + DieList[3] + DieList[4] + DieList[5] + DieList[6] + DieList[7] + DieList[8] + DieList[9] + DieList[10]);
}
}
瞭解die類將有所幫助。 – 2014-12-12 23:45:38
我可以問爲什麼你在使用ArrayList和Array的時候同時使用它們呢? – 2014-12-12 23:46:11
考慮將前四個循環合併成一個循環,並使用四個語句的主體,更加簡潔和易讀... – RobP 2014-12-12 23:48:39