[英]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.