2014-02-13 178 views
0

我只是想知道是否可以將一個變量分配給整個循環,因爲我將多次使用相同的確切變量。我是一個很菜鳥......不要硬上我...將變量分配給'For'循環?

for (m = 0 ; m<=Student2.size()-1; m++) 
{ 
    System.out.println(Student2.get(m)); 
} 
+1

放在一個方法是什麼? – sheltem

+0

我不明白這個問題。你的代碼是完全合法的。 – hivert

+0

你是指[for-each loop](http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html)? – amit

回答

2

你應該閱讀這個:http://docs.oracle.com/javase/tutorial/java/javaOO/methods.html 你不能把你的代碼放入方法/函數,它可以得到參數的返回值,這個函數是你可以調用的代碼片段。例如:

public static void main(String[] args) throws Exception { 

    doCalculation(3,5); //call the method with two arguments 
    doCalculation(7,2); //call the method again with other arguments 

} 

//define a method in this way: visibilty, return typ, name, arguments 
public static int doCalculation(int numb1, int numb2) { 
    int result = numb1 * numb2;       
    return result; 
} 

你的功能應該像(假設字符串類型的列表保持的對象):

public static void main(String[] args) throws Exception { 

    printStudents(Student2); 

} 

public static void printStudents(ArrayList<String> studentList) { 
    for (int m = 0; m <= studentList.size()-1; m++) 
    { 
     System.out.println(studentList.get(m)); 
    } 
} 
+0

我看到...但在我的情況下,這將是自變量? – Heneko

+0

在你的情況下,它的參數Student2是它的一個對象,但我不知道類型。我認爲你把班級稱爲student2是學生班的對象,對吧? – kai

+0

student2實際上是一個ArrayList。我剛剛開始使用面向對象... – Heneko

2

我相信你想要的東西的技術術語是"Extract Method"

public static void printStudents(Student Student2) { 
for (int m = 0 ; m<=Student2.size()-1; m++){ 
      System.out.println(Student2.get(m));} 
} 

然後你只需要調用此方法,你想:

printStudents(x); 

一個側面說明:如果Student2是一個變量名,那麼它應該被小寫。

+1

循環將很nicerthis方式:'for(int m = 0;米 StephaneM