我只是想知道是否可以將一個變量分配給整個循環,因爲我將多次使用相同的確切變量。我是一個很菜鳥......不要硬上我...將變量分配給'For'循環?
for (m = 0 ; m<=Student2.size()-1; m++)
{
System.out.println(Student2.get(m));
}
我只是想知道是否可以將一個變量分配給整個循環,因爲我將多次使用相同的確切變量。我是一個很菜鳥......不要硬上我...將變量分配給'For'循環?
for (m = 0 ; m<=Student2.size()-1; m++)
{
System.out.println(Student2.get(m));
}
你應該閱讀這個: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));
}
}
我相信你想要的東西的技術術語是"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
是一個變量名,那麼它應該被小寫。
循環將很nicerthis方式:'for(int m = 0;米
放在一個方法是什麼? – sheltem
我不明白這個問題。你的代碼是完全合法的。 – hivert
你是指[for-each loop](http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html)? – amit