我只是想知道是否可以将一个变量分配给整个循环,因为我将多次使用相同的确切变量。我是一个很菜鸟......不要硬上我...将变量分配给'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