[英]Initializing doubles in a loop giving error “variable might not have been initialized”
这个程序应该从用户那里得到一些邮件的重量并计算它的成本。 100g后,成本增加2.5美元/50g。 但是,当我尝试运行该程序时,它说“可变成本可能尚未初始化”。 这是因为我在 if 语句中初始化它吗? 我知道有些人有错误,因为他们在 if 语句中声明了变量,但我在 if 语句之外声明了我的变量。 我究竟做错了什么。
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double mailWeight;
double cost;
System.out.println("How much does your mail weigh (g)");
mailWeight = in.nextDouble();
in.close();
if (mailWeight > 0 && mailWeight <= 30) {
cost = 4;
}else if (mailWeight > 30 && mailWeight <= 50) {
cost = 5.50;
}else if (mailWeight > 50) {
double x = mailWeight - 100;
if (x >= 50) {
double y = x/50;
Math.ceil(y);
double z = y * 2.5;
cost = z + 7;
}
}
System.out.println(cost);
}
}
除了variable not initialized
的问题,还有一些地方需要改进:
System.in
的Scanner
无需关闭Scanner in = new Scanner(System.in);
System.out.println("How much does your mail weigh (g)");
double mailWeight = in.nextDouble();
double cost;
if (mailWeight <= 0) {
cost = 0;
} else if (mailWeight <= 30) {
cost = 4;
} else if (mailWeight <= 50) {
cost = 5.50;
} else {
cost = 7;
if (mailWeight > 100) {
double y = Math.ceil((mailWeight - 100) / 50.0);
cost += 2.5 * y;
}
}
System.out.println(cost);
正如错误中所说,您尚未初始化这两个变量“mailWeight”和“cost”
由于它们是局部变量(在方法内),因此您需要在访问它们之前对其进行初始化。 您通过赋予初始值进行初始化:
double mailWeight=0;
double cost=0;
如果最后一个 else if 语句出现并且 x < 50 或者当没有任何 if 语句导致 mailWeight 为 true 时,它不会被初始化。 您可以预先初始化成本。 (double cost = 0) 或者您可以添加所有缺少的 else 块。 在读取变量之前,您需要在所有可能的情况下初始化变量。
这可能会起作用:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double mailWeight;
double cost;
System.out.println("How much does your mail weigh (g)");
mailWeight = in.nextDouble();
in.close();
if (mailWeight > 0 && mailWeight <= 30) {
cost = 4;
} else if (mailWeight > 30 && mailWeight <= 50) {
cost = 5.50;
} else if (mailWeight > 50) {
double x = mailWeight - 100;
if (x >= 50) {
double y = x/50;
Math.ceil(y);
double z = y * 2.5;
cost = z + 7;
} else {
cost = 0; // Or whatever you want to set it to in this case
}
} else {
cost = 0; // Or whatever you want to set it to in this case
}
System.out.println(cost);
}
或预初始化成本值:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double mailWeight;
double cost = 0; // Or whatever you want it to be if none of the cases match
System.out.println("How much does your mail weigh (g)");
mailWeight = in.nextDouble();
in.close();
if (mailWeight > 0 && mailWeight <= 30) {
cost = 4;
} else if (mailWeight > 30 && mailWeight <= 50) {
cost = 5.50;
} else if (mailWeight > 50) {
double x = mailWeight - 100;
if (x >= 50) {
double y = x/50;
Math.ceil(y);
double z = y * 2.5;
cost = z + 7;
}
}
System.out.println(cost);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.