如何在return方法的循环内返回值? [英] How to return a value inside a loop in a return method?

查看:494
本文介绍了如何在return方法的循环内返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难从方法中的循环返回值.

I have troubles returning a value from a loop in method.

我已经尝试过这种方式:(它返回classname,我的初始化字符串而不是classes.get(i).className)

I've tried this way: (which returns classname, my initialise String instead of classes.get(i).className)

public String getClassName(){
    String cName = "classname";
    for (int i=0; i<classes.size(); i++){
        cName = classes.get(i).className;
    }
return cName;
}    

,我也尝试过此方法:(返回c而不是classes.get(i).className)

and I've tried this as well: (which returns c instead of classes.get(i).className)

public String getClassName(){
    String cName = "classname";
    String c = "c";
    for (int i=0; i<classes.size(); i++){
        c = classes.get(i).className;
    }
    cName = c;
    return cName;
}    

请告诉我如何退回classes.get(i).className!非常感谢:P

Please tell me how to return classes.get(i).className!! Thanks a lot :P

推荐答案

没有存储在类中.确保您认为自己所做的一切.尝试将其放入for循环中以查看发生了什么:

There is nothing stored in classes. Make sure you have in there what you think you do. Try putting this inside the for loop to see what's going on:

System.out.print("class name = " + cName);

如果从不打印出来,则说明类为空.在 循环中的任何时间,您都可以调用 return ,例如,如果类名与您可以在 if 语句中测试的东西匹配

If this never prints out, you know that classes is empty. At any time inside the for loop, you can call return, for example if the class name matches something you can test for in an if statement.

for (int i=0; i<classes.size(); i++){
    cName = classes.get(i).className;
    return cName;
}

此外,您是否可以投票或将某人标记为正确? (我是新来的,很乐意标出一些好的答案:))

Also, could you upvote, or mark someone as correct? (I'm new and would love to have some good answers marked as such :) )

这篇关于如何在return方法的循环内返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆