2016-10-02 48 views
-1

我沒有在年齡段寫過java,而且我知道我的問題非常簡單,但我不能爲我的生活找出錯誤。不能在同一個java類中調用方法

我試圖找到一個數組中的最小數字,使用下面的代碼。該算法是正確的,但我得到試圖在最後的print語句使用它時,一個錯誤

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。

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

,然後調用,如:

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

ArrayListfindSmallElement方法。讓你的方法static,並調用它傳遞num

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

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

當從static方面,應該叫另一static調用。

所以只要改變你的功能可按爲static,如:

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

提示:也試着看看有什麼happeneds當你試圖使用全局靜態變量非靜態函數。

1

而不是使你的方法靜態的,上述的所有其他人一樣,你可以創建一個對象,並把它通過,我認爲這是更方便

App app = new App(); 
int smallestElement = app.findSmallElement(sum); 
System.out.println("smallest element: " + smallestElement); 

我不太清楚,但我認爲這是有效的。

相關問題