Reputation: 127
Why can't I send the appleArray, blueberryArray, and peanutArray to the calcTotalPies method?
final int MAX_PIES = 81;
final int MAX_PER_TYPE = 27;
String typeOfPie = getPieType();
while (!typeOfPie.equalsIgnoreCase("q")) {
if (typeOfPie.equalsIgnoreCase("apple")) {
String[] appleArray = fillApple(typeOfPie, MAX_PER_TYPE);
}
else if (typeOfPie.equalsIgnoreCase("blueberry")) {
String[] blueberryArray = fillBlueberry(typeOfPie, MAX_PER_TYPE);
}
else if (typeOfPie.equalsIgnoreCase("peanut")) {
String[] peanutArray = fillPeanut(typeOfPie, MAX_PER_TYPE);
}
typeOfPie = getPieType();
}
if (typeOfPie.equalsIgnoreCase("q")) {
int totalPies = calcTotalPies(appleArray, blueberryArray, peanutArray);
}
Upvotes: 0
Views: 37
Reputation: 2417
when your code execution reaches to your method, if else block scopes inside while loop within which your arrays are declared have ended and they are not reachable. So you need to initialize them outside the loop.
Try this
final int MAX_PIES = 81;
final int MAX_PER_TYPE = 27;
String[] peanutArray = null;
String[] blueberryArray = null;
String[] appleArray = null;
String typeOfPie = getPieType();
while (!typeOfPie.equalsIgnoreCase("q")) {
if (typeOfPie.equalsIgnoreCase("apple")) {
appleArray = fillApple(typeOfPie, MAX_PER_TYPE);
} else if (typeOfPie.equalsIgnoreCase("blueberry")) {
blueberryArray = fillBlueberry(typeOfPie, MAX_PER_TYPE);
} else if (typeOfPie.equalsIgnoreCase("peanut")) {
peanutArray = fillPeanut(typeOfPie, MAX_PER_TYPE);
}
typeOfPie = getPieType();
}
if (typeOfPie.equalsIgnoreCase("q")) {
int totalPies = calcTotalPies(appleArray, blueberryArray, peanutArray);
}
Upvotes: 0
Reputation: 20185
A local variable is always declared within a block and only alive in this block (note: a method body or the body of an if
or a loop is also a block).
You declared appleArray
, blueberryArray
and peanutArray
only in their surrounding if
-blocks, therefore they are not alive in the lowest if
-block. The compiler should tell you something of these arrays not being defined.
Upvotes: 1