Sue
Sue

Reputation: 189

How to return a value inside a loop in a return method?

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

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

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

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

Upvotes: 1

Views: 6354

Answers (4)

Josh T
Josh T

Reputation: 564

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

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 :) )

Upvotes: 1

Ankit Rustagi
Ankit Rustagi

Reputation: 5637

That should be because you dont enter the for loop mainly because you list "classes" is empty. You can check it this way-

if(classes.size()==0)
   System.out.println("Classes is empty");

Upvotes: 0

rolfl
rolfl

Reputation: 17707

While Maroun is right bout the code only returning the last value in the classes collection, the reality is that in your example the collection is always empty, and thus the for loop does not execute even once. Make sure the classes collection contain what you think it should!

Upvotes: 0

Maroun
Maroun

Reputation: 96016

I don't know what are you trying to do, but your code is equivalent to:

public String getClassName() {
    return classes.get(classes.size() - 1).className;
}

Are you sure this is what you want to return? You should be careful in case classes is empty as you might get ArrayIndexOutOfBoundsException.

Upvotes: 0

Related Questions