2016-10-02 1 views
-1

나는 나이에 자바를 작성하지 않은, 내 질문은 정말 간단하지만, 내 인생에 대한 오류를 알아낼 수 없다는 것을 알고.약자 같은 자바 클래스의 메서드를 호출

아래 코드를 사용하여 배열에서 가장 작은 숫자를 찾으려고합니다. 이 알고리즘은 맞다,하지만 난 마지막 인쇄 문에서 사용하려고 오류가 발생

package runtime; 

import java.util.ArrayList; 

public class app { 


/** 
* @param args the command line arguments 
*/ 

public int findSmallElement(ArrayList<Integer> num) 
{ 
    int smElement; 
    smElement= num.get(0); 
    for(int i=0; i<num.size() ; i++) 
     if(num.get(i) < smElement) 
      smElement=num.get(i); 
    return smElement; 
} 

public static void main(String[] args) { 


    ArrayList<Object> num = new ArrayList<Object>(); 



    num.add(100); 
    num.add(80); 
    num.add(40); 
    num.add(20); 
    num.add(60); 

    System.out.println("The size of the list is " +num.size()); 
    System.out.println(num.findSmallElement()); 

} 

} 

답변

1

당신은 때이 방법이없는 ArrayList를 변수/객체에 메소드를 호출하기 위해 노력하고 대신 자신의 클래스 인스턴스에서 호출하려고합니다. 배열리스트를이 메소드에 전달해야합니다.

또 다른 옵션은 메서드를 정적으로 만들고 간단히 호출하여 다시 arraylist를 전달하는 것입니다.

// pass the ArrayList into your findSmallElement method call 
int smallestElement = findSmallElement(num); 
// display the result: 
System.out.println("smallest element: " + smallestElement); 
1

ArrayList하지 않는findSmallElement 방법이 있습니다 같은

// add the static modifier 
public static int findSmallElement(ArrayList<Integer> num) 

다음 호출합니다. 당신의 방법 static을 확인하고 또 다른 static라고한다 static 컨텍스트에서 호출 할 때

System.out.println(findSmallElement(num)); 

public static int findSmallElement(ArrayList<Integer> num) 
0

처럼 num 전달 호출.

그래서 그냥 같은 static로 당신의 funciton을 변경

public static int findSmallElement(ArrayList<Integer> num){...} 

팁 : 비 정적 함수에서 전역 정적 변수를 사용하려고 할 때 happeneds을 무엇을 볼 수도보십시오. 대신에 위에서 언급 한 모든 다른 사람처럼 정적을 당신의 방법을 만드는

1

, 객체를 생성하고 좀 더 편리하다고 생각하는 것을 통해 호출 할 수 있습니다

내가 아주 확실하지 않다
App app = new App(); 
int smallestElement = app.findSmallElement(sum); 
System.out.println("smallest element: " + smallestElement); 

, 그러나 나는 이것이 효과가 있다고 생각한다.

관련 문제