1

I'm trying to return all of the 'players and their goals' in a sports team using the following:

public String printPlayers(){        
    for (Player player : this.players){
        return player.toString();
    }
}

Netbeans says there is no return statement, which I presume is because it is within the for-each loop. But if I place it outside it will only return one item. Here is the test code:

    Team barcelona = new Team("FC Barcelona");

    Player brian = new Player("Brian");
    Player pekka = new Player("Pekka", 39);

    barcelona.addPlayer(brian);
    barcelona.addPlayer(pekka);
    barcelona.addPlayer(new Player("Mikael", 1));

    barcelona.printPlayers();

In the Player Object, here is what toString does:

public String toString(){
        return ("Player: "+this.name+", goals "+this.goals);
    }

4 Answers 4

2

Java allows you to return only a single object. It is not possible to return multiple objects. If you want to return multiple objects from a single method, you first have to collect them into a single object, for example an array, a List or a String, and then return that.

Let's look at your code. Netbeans complains about the missing return statement because it is possible that your players collection is empty. In that case the loop block is never executed and the method end without a return statement, which is not allowed. So let's repair your method as follows:

public String printPlayers(){        
    for (Player player : this.players){
        return player.toString();
    }
    return "";
}

Also now the method only returns a single object: it will convert the first player in your collection to a string and then return that. The other players are ignored. So you have to collect your players in a single object. Since you want to return a string, it makes sense to collect the strings in a single string:

public String printPlayers(){        
    String result = "";
    for (Player player : this.players){
        result += " " + player.toString();
    }
    return result;
}

Now you can try to make the result better, for example by removing the leading space for the first element, or by adding commas instead of spaces, etc. Also, for more performance you can use a StringBuilder for building your string (but think about performance once you have a working method!).

Sign up to request clarification or add additional context in comments.

2 Comments

You got my vote for at least explaining why the code doesn't compile and why returning in the loop is incorrect. I'd still prefer if you used a StringBuilder. That wouldn't make the code harder to understand or longer.
Thanks Hoopje. This makes total sense, and I've tested the other components of the code as I went and they have worked as intended, so the += string with a googled "\n" for formatting worked a charm. I also like the note on thinking about performance after it's working. Those tips help a lot as a beginning programmer! Thank you.
0
 public String printPlayers(){        
  String data="";
 for (Player player : this.players){
       data +=player.toString();
  }
      return data;
}

4 Comments

Never build a String using String + String in a loop. Use a StringBuilder.
it will keep creating strings on the back-end right? @Andreas
Andreas, @DanyalSandeelo That's not a valid point. Compiler will take care of it : codeinventions.blogspot.in/2014/08/…
@sᴜʀᴇsʜᴀᴛᴛᴀ not when it's in a loop. An even better option would be return players.stream().map(Player::toString).collect(Collectors.joining(", ");
0

Use a StringBuilder

public String printPlayers(){ 
    StringBuilder sb = new StringBuilder();       
    for (Player player : this.players){
      sb.append(player.toString());
    }
    return sb.toString();
}

Comments

0

Why netbeans complaining is, what if you not enter to for loop ?? So there should be a return always.

Coming to actual problem,

Just build a String and return

public String printPlayers(){   
        StringBuilder builder=new StringBuilder();     
        for (Player player : this.players){
            builder.append(player).append(" ");
        }
       return builder.toString();
    }

That's build a String with appending all players as String and return finally.

9 Comments

Never build a String using String + String in a loop. Use a StringBuilder.
@Andreas Who told ? That compiler will take care :) Give a read codeinventions.blogspot.in/2014/08/…
@sᴜʀᴇsʜᴀᴛᴛᴀ not when it's in a loop. It does that only when using a single instruction: String foo = bar + baz + ding;
@JBNizet ok, don't this fact. So, why is that and what difference it make when in a loop and for a normal statement ?
One more improvement inside loop: builder.append(player).append(' '); --- append(Object) automatically calls toString() and append(char) better than append(String). Minor considerations, but still. ;-)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.