Reputation: 71
public class Help
{
public static void main (String[] args)
{
if (index = 1)
{
String greeting = "hello";
}
else
{
String greeting = "goodbye";
}
}
callAMethod(greeting);
}
When I define the String within the if statement I get a 'cannot find symbol' error. How can I get around this and still be able to create a string depending upon an above condition?
Upvotes: 3
Views: 2015
Reputation: 2203
How about
public static void main (String[] args){
String greeting;
if( index == 1){
greeting = "hello";
}else{
greeting = "goodbye";
}
}
callAMethod(greeting);
}
Upvotes: 4
Reputation: 2971
You can define the greeting variable before the statement:
String greeting;
if (index == 1) {
greeting = "hello";
} else {
greeting = "bye";
}
System.out.println(greeting);
Upvotes: 1
Reputation: 15916
Declare it outside the scope -
String greeting = "goodbye";
if( index == 1)
{
greeting = "hello";
}
callAMethod(greeting);
Upvotes: 2
Reputation: 32851
Declare the variable outside of the if
block.
Right before the if
statement, you can say String greeting = "";
Then, inside the if
and else
blocks, you say greeting = "hello";
and so on.
So you have separated declaring the variable from assigning the value to it.
Upvotes: 1