2014-12-12 2 views
0

다음은 요청한 다이 클래스입니다 ... Alex는 내 다이 클래스에서 .getValue를 사용하는 것에 대해 더 자세히 설명 할 수 있습니까? 내 배열과 ArrayList에의 합을 찾기 위해 다른 코드를 사용하여 시도했습니다배열과 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; 
    } 
} 

는 ... 여기 내 코드입니다. 누군가가 어떻게 끝을 해결할 수 있는지 말해 줄래?

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]); 

    } 
} 
+0

다이 클래스를 아는 것이 도움이됩니다. –

+1

ArrayList와 Array를 사용하는 이유는 무엇입니까? –

+0

처음 4 개의 for 루프를 4 개의 명령문 본문이있는 하나의 루프로 축소하는 것을 고려하십시오. 훨씬 더 압축되고 읽을 수 있습니다. – RobP

답변

0

난 당신이 몇 가지 개념을 missunderstanding 있습니다 참조 :

  • Object 클래스 (모든 클래스가 상속되는 클래스)에서 정의 된 인쇄 방법은 객체가 아닌 모든 속성의 참조를 인쇄합니다. 인쇄 메소드가 인쇄 할 속성을 알 수 없으므로 (속성 및 참조 목록이 하나씩 객체에 저장되는 것이 아니기 때문에) 분명해야합니다. 내부 속성을 인쇄해야하는 경우 특별히 수행 할 메소드를 작성하거나 인쇄 메소드를 겹쳐 써야하지만 사전 정의 된 메소드를 겹쳐 쓸 충분한 이유가 없으면 수행하지 마십시오. getValue()를 호출하십시오. 즉,

  • sumArray는 객체 일 뿐이며 객체 목록이 아닙니다. 첫 번째 for 루프를 반복하는 방법은 하나의 객체 만 읽는 것입니다. sumArray는 목록이 아닌 Die 객체 중 하나입니다.

  • 문자열을 제외하고 연산자 +는 기본 유형 (int, boolean, float, ...)에만 사용됩니다. + = 귀하의 컴파일을 깨지 않는 경우, 나는 컴파일러가 단일 할당 작업으로 작업을 해석, 따라서 당신이 참조 sumArray 지금 가리 킵니다 ... sumArray 다시 이해합니다. 그 진술은 쓸모가 없다.

  • 마지막으로 주석 처리 된 행에 대해서는 위에서 설명한 이유 때문에 오브젝트를 더할 수 없습니다. 객체는 많은 속성과 메소드에 의해 복잡한 엔티티 컴파운드이며 컴파일러는 이러한 엔티티를 기본적으로 합하는 방법을 알 수 없습니다. 어떤 이유로 당신이 C에서 자바에 도착한 경우 연산자를 오버로드 할 수없는 awared 수 ++ (그러나 확실하게 그 사건이 아니다) 당신이 솔루션

    • (A getValue 정의를) 원하는 경우,

    그래서 메소드를 다이 클래스에 저장하여 저장된 값을 읽으십시오. 롤 값을 적절하게 코딩하여 값을 생성하고 저장한다고 가정합니다. 배열에서 모든 값을 합

할 :

int sums1=0;  
for (Die i : DieList){ 
sums1+= i.getValue(); 
} 

당신의 ArrayList에서 모든 값을 요약하면이 수행합니다 마지막으로

int sums2=0;  
for (int i=0;i<DieList2.size();i++){ 
    sums2+= DieList2.get(i).getValue(); 
} 

그리고 그들을 인쇄 :

System.out.println("Sum of array elements: "+sums1); 
System.out.println("Sum of ArrayList elements: "+sums2); 
0

롤링 한 후 배열의 합을 찾으려는 경우 전자 주사위를 사용하면 코드를 많이 줄일 수 있습니다!

이와 같이 하나의 루프에서 주사위를 추가, 롤링 및 합계 할 수 있습니다.

public static void main(String[] args) { 
    final int SIZE = 10; 
    int sumList1 = 0; 
    int sumList2 = 0; 
    Die[] DieList = new Die[SIZE]; 
    ArrayList <Die> DieList2 = new ArrayList <Die>(); 

    for (int i = 0; i < SIZE; i++) { 
     DieList[i] = new Die(); 
     DieList2.add(new Die()); 
     DieList[i].roll(); 
     DieList2.get(i).roll(); 
     sumList1 += DieList[i].getFaceValue(); 
     sumList2 += DieList2.get(i).getFaceValue(); 
    } 

    System.out.println("Sum of Array: " + sumList1); 
    System.out.println("Sum of ArrayList: " + sumList2); 
    System.out.println("Sum of both: " + (sumList1 + sumList2)); 
}