Reputation: 21
if (eyeColor == green)
{
System.out.println ("If your eyes are green I recommend buying .... ");
....
}
error says
variable green might not have been initialized
I can't display my whole code since it is for school, but I am just wondering how can I initialized it if the eyeColor from the user input (using scanner) is green?
Upvotes: 0
Views: 90
Reputation: 91
Initialise eyeColor before you compare it. If it is a string, simply initialise it as an empty string:
String eyeColor;
eyeColor = "";
Before you perform any checks to see what eyeColor has been specified, you may also want to check to make sure that is is NOT still ""..
Upvotes: 1
Reputation: 2037
Assuming that your variable eyeColor
is the input from the user. You could use the following
if("green".equals(eyeColor))
Since green is a string, and it will never change (it is always green), you can just use the string. It is also worth noting that in Java, you need to use .equals() when comparing string values, not '=='.
I would also suggest using .toLowerCase(), so that the comparison is no longer case sensitive. An example check is shown in the code below:
public static void main(String args[]) throws IOException {
String eyeColor = "Green";
if("green".equals(eyeColor.toLowerCase())){
System.out.println ("If your eyes are green I recommend buying .... ");
}
}
Upvotes: 0
Reputation: 68715
Not sure what is the type of green
but this is how you declare method local variables:
Object green = null;
or
Object green = SOME_DEFAULT_VALUE_BETTER_THAN_NULL;
Upvotes: 1