I am trying to store a value inside a variable depending on the input:
switch(pepperoni) {
case 'Y':
case 'y':
topping1 = 1;
break;
case 'N':
case 'n':
topping1 = 0;
break;
default:
{
System.out.print("This is not a valid response, please try again \n");
System.out.print("Do you want Pepperoni? (Y/N): ");
pepperoni = scan.next().charAt(0);
break;
}
I want the variable topping1 to store the value 1 if the input is 'Y' or 'y' and to store the value 0 if the input is 'N' or 'n'
If the input is neither 'Y', 'y', 'N' nor 'n' then I want it to repeat the question until a valid input is typed in.
The problem arises when I later in the program try to print the value 'because it might have not been initialized', which somewhat makes sense. (example below)
if(topping1 > 0)
System.out.println("Pepperoni");
// 243: error: variable topping1 might not have been initialized
I do realize there are other ways to do this, but as I am really wanting to learn Java I try to understand as much of the fundamentals as possible. Therefore would I be really happy if someone could tell me why this not work and if there is a way to do this with a switch statement or quick fixes.
If pepperoni
is not Y
, y
, N
, or n
, you never assign a value to topping1
, because the default
case never assigns it a value. E.g., if pepperoni
is not one of those four values, then the flow of control skips the other two cases and goes to default
, which never gives topping1
a value, so later when you try to use it, it's possible topping1
has never received a value at all.
The "workaround" is to correct the logic so that you never try to use topping1
without having assigned it a value. How you do that depends on logic you haven't shown us. You might assign it a value other than 0
or 1
(the values you assign in the other branches of the switch
), for instance.