2013-03-26 4 views
0

배열 개체의 배열을 전달하고 배열의 개체 평균 값을 반환하는 클래스 내에서 정적 메서드를 만들려고합니다.배열 값의 평균을 반환하는 메서드를 만드는 중

public static double calcAverage() { 
    int sum = 0; 
    for (int i=0; i < people.length; i++) 
      sum = sum + people[i]; 
    double calcAverage() = sum/people.length 
    System.out.println(people.calcAverage()); 
} 

코드가 컴파일 오류가 발생하지만 올바른 방향으로 가고 있습니까?

+0

일단 컴파일하면 무한 재귀가 발생하는 것처럼 보입니다. 'println'을 어딘가에 옮깁니다. 아마도'main'에서. – nattyddubbs

+1

double calcAverage()가 잘못되어 변수 double을 선언합니다. avgVal = sum/people.length; avgVal – Abi

+0

사람이 어떻게/어디에서 신고됩니까? –

답변

1
public static double calcAverage() { 
    int sum = 0; 
    for (int i=0; i < people.length; i++) 
      sum = sum + people[i]; 
    double calcAverage() = sum/people.length 
    System.out.println(people.calcAverage()); 
} 

변경

double calcAverage() = sum/people.length 

double average = sum/(double)people.length; 

(새로운 변수를 선언하는 올바른 방법)

변경에

 System.out.println(people.calcAverage()); 
,174 당신이 함수를 호출의 결과를 인쇄 할 경우

return average; 

-

(, 당신은 항상 기능, 예를 들어, 외부에서 수행해야)

을 함수를 호출하고 반환 된 결과를 저장 한 후 main에 그것을 그래서 우리는이 :

public static double calcAverage() { 
    int sum = 0; 
    for (int i=0; i < people.length; i++) 
    { 
     sum = sum + people[i]; 
    } 
    double average = sum/(double)people.length; 
    return average; 
} 
+0

흠 .. 왜 아직도 받아들이지 않고있다. .. 왜 – aiuna

+0

@aiuna 정확한 오류 메시지와 줄 번호는 무엇입니까? – Patashu

+0

고맙습니다. – aiuna

1

당신의 가까이. 나는 몇 가지 실수를 본다.

처음으로 sum = sum + people [i];

people [i] returns는 정수가 아닌 객체이므로 정수에 객체를 추가하면 작동하지 않습니다.

초, calcAverage 메서드 내에서 calcAverage()를 호출하고 있습니다.이 메서드는 아마도 원하는 작업이 아닙니다. 이 일을 재귀라고하지만 calcAverage() 외부에서 메서드를 호출해야한다고 생각합니다.

1
// pass people as a parameter 
public static double calcAverage(int[] people) { 
    // IMPORTANT: this must be a double, otherwise you're dividing an integer by an integer and you will get the wrong answer 
    double sum = 0; 
    for (int i=0; i < people.length; i++) { 
     sum = sum + people[i]; 
    } 
    // remove the() 
    double result = sum/people.length; 
    System.out.println(result); 

    // return something 
    return result; 
} 


// example 
int[] myPeople = {1,2,3,4,5,6,7,8}; 
double myPeopleAverage = calcAverage(myPeople); 
+0

은 내 물건을 고쳐야 만했다. 부분, 고마워요. – aiuna

관련 문제