variable might not have been initialized Help!
Part of a servlet i am working on gets values from a select box off an html page, i am trying to use if else statement so depending what value the select a int variable is assigned a number.
if ( levelForm.equals("0"))
{
numRental = 3;
}
elseif (levelForm.equals("1"))
{
numRental = 1;
}
elseif (levelForm.equals("2"))
{
numRental = 2;
}
elseif (levelForm.equals("3"))
{
numRental = 3;
}
String insert ="INSERT INTO customers(first_name,last_name,email,user_name,password,level, num_rentals) VALUES('" + firstNameForm +"','" + lastNameForm +"','" + emailForm +"','" + userForm +"','" + passwordForm +"','" + levelForm +"','" + numRental +"')";
System.out.println(insert);
When i compile i get the an error saying numRental might not have been initialized, can anybody help me solve this?
[1672 byte] By [
ajrobsona] at [2007-11-26 15:00:55]

# 3
Just to expound a bit, you have:
if ( levelForm.equals("0")) //...
else if ( levelForm.equals("1")) //...
else if ( levelForm.equals("2")) //...
else if ( levelForm.equals("3")) //...
What happens if levelForm.equals("4")? or "5", or null? It may be 'impossible' from your point of view, knowing how the value gets set, but the compiler can't know that and needs a default value, such as:
int numRental=3;
if ( levelForm.equals("0")) //...
else if ( levelForm.equals("1")) //...
else if ( levelForm.equals("2")) //...
else if ( levelForm.equals("3")) //...
Or
if ( levelForm.equals("1")) numRental = 1;
else if ( levelForm.equals("2")) numRental = 2;
else numRental = 3;
So the compiler knows that there will be exactly 3 options, and one of them will come true (if all the others fail, the last else will be executed).
ps One of the best reasons to use .equals with Strings is to prevent null pointer errors.The way you have it is backwards to protect against the null pointer. A safer method when comparing a variable of type string versus a constant string would be to put the constant String first:
if("1".equals(levelForm))
since you know the constant String can't be null. Just a pointer.
Message was edited by:
stevejluke