Reputation: 57
I'm assigning my variables in an if
statement and trying to use them outside of it, but I can't figure out how. The error is in the very last if
statement stating that "local variable may not have been initialized".
int i,z;
if (st1.nextToken() == "Ace")
{
String Ace = "14";
i = Integer.parseInt(Ace);
}
else if (st2.nextToken() == "Ace")
{
String Ace = "14";
z = Integer.parseInt(Ace);
}
else if (st1.nextToken() == "King")
{
String King = "13";
i = Integer.parseInt(King);
}
else if (st2.nextToken() == "King")
{
String King = "13";
z = Integer.parseInt(King);
}
else if (st1.nextToken() == "Queen")
{
String Queen= "12";
i = Integer.parseInt(Queen);
}
else if (st2.nextToken() == "Queen")
{
String Queen= "12";
z = Integer.parseInt(Queen);
}
else if (st1.nextToken() == "Jack")
{
String Jack = "11";
i = Integer.parseInt(Jack);
}
else if (st2.nextToken() == "Jack")
{
String Jack = "11";
z = Integer.parseInt(Jack);
break;
}
else
{
i = Integer.parseInt(st1.nextToken());
z = Integer.parseInt(st2.nextToken());
}
if (i > z)
Upvotes: 0
Views: 2971
Reputation: 11975
The compiler must be satisfied that both i
and z
have been initialised before it will permit the comparison i > z
. Your code does not guarantee this as only some paths through your if..else
logic will initialise both variables.
You have a couple of options:
i
and z
at the very beginning, eg. to 0 or some other suitable defaulti
and z
in every if
blockA couple of other style issues:
equals()
to compare strings, not ==
, eg. st1.nextToken().equals("Ace")
Thus:
String Jack = "11";
i = Integer.parseInt(Jack);
can become:
i = 11;
or:
i = JACK; // where JACK is a constant set to 11
You may also have a bug with respect to the tokens being read. Each if
expression calls nextToken() which will cause the next token in the stream to be used. I imagine you want to compare the current token in each expression. If this is the case, then assign to two temporary variables to hold the next tokens for st1
and st2
before your if..else
logic and compare these to Ace, King, etc.
Upvotes: 1
Reputation: 649
I suggest using Integer class. If none of the conditions before last if statement satisfy, put a check if those Integers are initialized with null
check.
Upvotes: 0
Reputation: 1413
A more elegant solution for String compares, in this case, would be to use a switch/case statement
Upvotes: 0
Reputation: 5831
Replace:
int i,z;
with:
int i=0, z=0; //or whatever value you want
Or initialize both i
and z
to some value in all of your if-else
blocks.
You cannot do if(i>z)
unless both are initialized because you need to initialize local variables.
Upvotes: 2