Reputation: 333
I am trying to implement a method whose return value is defined into the for loop. However I always get eclipse telling me that I have to initialize it. But if I do this, and set it to say, null, it always stays null... What am I doing wrong?
public String getPoints(String team){
String teamName;
String outcome;
for ( FootballClub club : league )
{
teamName = club.getName();
if ( teamName.trim().toLowerCase().equals( team ) )
{
outcome = ( team + " " + club.getPoints() ) + " Points";
}
}
return outcome;
}
Upvotes: 3
Views: 870
Reputation: 7730
As Local variables are not given default initial values. They must be initialized explicitly before they are used which is why your innocent Eclipse is doing his duty to inform you about the compilation Error .
Initialize outcome with null , it will not always be null , If team for which you are calling getPoints() present in league collection then your outcome will definately change .
public String getPoints(String team){
String teamName;
String outcome=null; // Initialization is must
for ( FootballClub club : league )
{
teamName = club.getName();
if ( teamName.trim().toLowerCase().equals( team ) )
{
outcome = ( team + " " + club.getPoints() ) + " Points";
}
}
return outcome;
}
Upvotes: 1
Reputation: 448
use this, get rid of extra variables, of course if there will be no more operations with outcome
:
public String getPoints(String team){
String teamName;
for ( FootballClub club : league )
{
teamName = club.getName();
if ( teamName.trim().toLowerCase().equals( team ) )
{
return ( team + " " + club.getPoints() ) + " Points";
}
}
return "null or some string if .equals( team ) false for all clubs";
}
Upvotes: 1
Reputation: 5028
You can also use break
:
if ( teamName.trim().toLowerCase().equals( team ) )
{
outcome = ( team + " " + club.getPoints() ) + " Points";
break;
}
And when you're expecting to outcome
value, you will need to:
if (outcome != null)
Upvotes: 0
Reputation: 393781
Since the league
Collection/array (whatever it is) you are iterating over may be empty, outcome
may not be initialized (since the body of the loop will never be entered in this case).
Just give it an initial value :
String outcome = null;
Upvotes: 1