![](/img/trans.png)
[英]How can I make a loop in java with user input and have variables that are the last input and previous input?
[英]How can I make a loop that keeps going based on user input
對於 class,我必須編寫一個簡單的程序,允許用戶輸入 package 的重量,然后告訴用戶與該重量相關的運費。 這不是家庭作業所必需的,但我正在嘗試添加一個 do-while 循環,如果用戶想輸入另一個權重,則要求用戶在循環末尾輸入字母 y,然后 while 部分測試是否 keepGoing 變量等於 y 重新開始循環。 我不知道為什么,但無論用戶輸入什么,循環都不會重新啟動。 即使用戶輸入y程序剛剛結束,任何人都可以幫忙。 導入 java.util.Scanner;
public class HwkChp4 {
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
double packageWeight;
double underTwo = 1.10;
double twoToSix = 2.20;
double sixToTen = 3.70;
double overTen = 3.80;
String msg1 = "How much does the package weigh?";
String msg2 = "The shipping cost is ";
String keepGoing = "y";
packageWeight = getDouble(msg1);
do {
if(packageWeight <= 2) {
System.out.println(msg2 + "$" + underTwo);
}
if(packageWeight > 2 && packageWeight <= 6) {
System.out.println(msg2 + "$" + twoToSix);
}
if(packageWeight > 6 && packageWeight <= 10) {
System.out.println(msg2 + "$" + sixToTen);
}
if(packageWeight > 10) {
System.out.println(msg2 + "$" + overTen);
}
System.out.println("Please enter y if you would like to enter another weight");
System.out.println("otherwise please enter n");
keepGoing = keyboard.next();
} while (keepGoing == "y");
}
public static double getDouble(String msg1) {
double decimal;
System.out.println(msg1);
decimal = keyboard.nextFloat();
return decimal;
}
}
在 Java 中,只能使用==
運算符對原始數據類型( int
、 char
、 boolean
等,基本上以小寫開頭的數據類型)進行測試。 字符串和其他數據類型的存儲方式大不相同, ==
運算符調用變量 memory 地址,而不是它們保存的數據。 因此,您不能使用相等運算符,因為無論您如何努力, keepGoing
將始終存儲在與"y"
或您嘗試將其設置為的任何其他變量不同的 memory 地址中。 (當然,除非您故意將它們都設置為相同的引用,但這總是會導致 true)。 所以你需要做的是使用 String 的內置equals()
function,如下所示:
TLDR:將keepGoing == y
更改為keepGoing.equals(y)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.