2014-02-13 56 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