【问题标题】:Assign a variable to a 'For' loop?将变量分配给“For”循环?
【发布时间】:2014-02-13 13:06:25
【问题描述】:

我只是想知道是否可以将变量分配给整个循环,因为我将多次使用完全相同的变量。我是个菜鸟……别对我太苛刻……

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

【问题讨论】:

  • 我不明白这个问题。你的代码是完全合法的。
  • 你指的是for-each loop吗?
  • 放入方法是更好的主意:) 可能会更简单易懂。:)
  • 我的意思是,我在代码中多次使用这个精确的循环。只是想知道有没有办法缩短它。和你不写5+5一样,你可以只分配一个变量:summ = 5+5...我不知道我是否解释得当

标签: java variables for-loop


【解决方案1】:

您应该阅读以下内容:http://docs.oracle.com/javase/tutorial/java/javaOO/methods.html 您不能将代码放入可以获取参数和返回值的方法/函数中,并且此函数是代码 sn-ps,您可以随心所欲地调用。示例:

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));
    }
}

【讨论】:

  • 我明白了……但在我的情况下,哪个是论点?
  • 在您的情况下,它的参数 Student2 它是一个对象,但我不知道类型。我想你把 student2 称为学生类对象的类,对吧?
  • 啊,好吧,这个列表包含哪种类型的数据?学生对象?还是字符串?
  • 我发布了您需要的函数,假设 ArrayList 包含字符串。
  • 它只包含字符串
【解决方案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 是一个变量名,那么它应该是小写的。

【讨论】:

  • 这样循环会更好:for (int m = 0 ; m&lt;Student2.size(); m++){ System.out.println(Student2.get(m));} }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-23
  • 2012-04-26
  • 1970-01-01
  • 1970-01-01
  • 2016-07-30
  • 2015-07-07
  • 2012-02-26
相关资源
最近更新 更多