我的代码如下所示:
if (gasQuality==87){
double subtotal = unleaded * gallonsSold;
}else if (gasQuality==89){
double subtotal = unleadedPlus * gallonsSold;
}else if (gasQuality==91){
double subtotal = premium * gallonsSold;
}
但由于某种原因,编译器稍后将无法识别“小计”。例如,如果我想对代码下方的小计征税,则编译器将读取:
cannot find symbol
symbol : variable subtotal
location: class Paniagua_Invoice
final double cityTax = .0375 * subtotal;
我究竟做错了什么?
最佳答案
这是因为scoping
。变量存在于声明它们的块中(还有其他规则,因此您希望进一步了解它)。由于第一个subTotal
是在if
块中声明的(由{}
分隔),因此只能在该块内使用它。要解决此问题,您可以尝试在这些subtotal
语句之前声明if
:
double subtotal = 0; // declaration and initialization
if (gasQuality==87) {
subtotal = unleaded * gallonsSold; // don't declare again
}
else if (gasQuality==89)
...
另外,您可以使用switch语句代替那些
if-else if
语句:switch (gasQuality) {
case 87:
subtotal = ...;
break;
case 89:
subtotal = ...;
break;
default:
break;
}