Java 中的变量初始化错误
Variable initialization error in Java
我有以下方法:
private static double mailTypeOne(double oz) {
double total;
if (oz <= 16) {
total = 3.50;
} else if (oz > 16 && oz <= 32) {
total = 3.95;
} else if (oz > 32) {
total = 3.95 + (Math.ceil((oz - 32) / 16) * 1.20);
}
return total;
}
编译我的代码时,我得到了这个编译错误:
the variable 'total' might not have been initialized
我的代码的哪一部分触发了错误?
你的 else if(s) 不一定被遵循(给编译器)。你需要像
这样的东西
private static double mailTypeOne(double oz) {
double total;
if (oz <= 16) {
total = 3.50;
} else if (oz <= 32) {
total = 3.95;
} else {
total = 3.95 + (Math.ceil((oz-32)/16) * 1.20);
}
return total;
}
你也可以像这样简化上面的内容
private static double mailTypeOne(double oz) {
if (oz <= 16) {
return 3.50;
} else if (oz <= 32) {
return 3.95;
}
return 3.95 + (Math.ceil((oz-32)/16) * 1.20);
}
声明与初始化不同。就说
double total = 0;
您的 if else 语句应以 else 语句结尾,这确保无论 oz
的值如何,都必须初始化变量 total
另一种方法是在声明时将total
初始化为0.0。也就是说,而不是 double total;
做 double total = 0.0;
我有以下方法:
private static double mailTypeOne(double oz) {
double total;
if (oz <= 16) {
total = 3.50;
} else if (oz > 16 && oz <= 32) {
total = 3.95;
} else if (oz > 32) {
total = 3.95 + (Math.ceil((oz - 32) / 16) * 1.20);
}
return total;
}
编译我的代码时,我得到了这个编译错误:
the variable 'total' might not have been initialized
我的代码的哪一部分触发了错误?
你的 else if(s) 不一定被遵循(给编译器)。你需要像
这样的东西private static double mailTypeOne(double oz) {
double total;
if (oz <= 16) {
total = 3.50;
} else if (oz <= 32) {
total = 3.95;
} else {
total = 3.95 + (Math.ceil((oz-32)/16) * 1.20);
}
return total;
}
你也可以像这样简化上面的内容
private static double mailTypeOne(double oz) {
if (oz <= 16) {
return 3.50;
} else if (oz <= 32) {
return 3.95;
}
return 3.95 + (Math.ceil((oz-32)/16) * 1.20);
}
声明与初始化不同。就说
double total = 0;
您的 if else 语句应以 else 语句结尾,这确保无论 oz
total
另一种方法是在声明时将total
初始化为0.0。也就是说,而不是 double total;
做 double total = 0.0;