[英]Using a do while loop with a user inputted String
目前我正在為我的 Java class 解決一個問題,我正在做 do-while 循環,當我的 while 條件與用戶輸入的字符串有關時我遇到了麻煩。 代碼可以編譯,但無論我輸入什么,它都會使 while 條件失敗並再次執行循環。 這甚至發生在我硬編碼 unit 的值時。
我嘗試在線查找解決方案,但我能找到的每個示例都使用用戶輸入的 int 值而不是 String
public class unit {
public static void main (String[] args) {
String prompt = "Please enter your preferred unit of mass (kg, lb, g or oz): ";
System.out.println(preferredUnit(prompt));
}
public static String preferredUnit(String prompt) {
Scanner sc = new Scanner(System.in);
String unit = "";
do{
if (!unit.equals("")) {
System.out.println("Sorry but " + unit + " is not a valid unit type");
}
System.out.println(prompt);
unit = sc.nextLine();
} while(!unit.equals("kg") || !unit.equals("lb") || !unit.equals("g") || !unit.equals("oz") );
return "Unit of mass: " + unit;
}
}
!=A || !=B
不是你要找的。 如果我輸入A,它不是B,所以它失敗了。 如果我輸入B,它不是A,所以它失敗了。 相反,您正在尋找!=A && !=B
例如
while(!unit.equals("kg") || !unit.equals("lb") || !unit.equals("g") || !unit.equals("oz"))
應該
while(!unit.equals("kg") && !unit.equals("lb") && !unit.equals("g") && !unit.equals("oz"))
兩種可能解決您的問題。
單程:
public static void main (String[] args) {
String prompt = "Please enter your preferred unit of mass (kg, lb, g or oz): ";
System.out.println(preferredUnit(prompt));
}
public static String preferredUnit(String prompt) {
Scanner sc = new Scanner(System.in);
String unit = "";
do{
if (!unit.equals("")) {
System.out.println("Sorry but " + unit + " is not a valid unit type");
}
System.out.println(prompt);
unit = sc.nextLine();
} while(!unit.equals("kg") && !unit.equals("lb") && !unit.equals("g") && !unit.equals("oz") );
return "Unit of mass: " + unit;
}
第二種方式:
public static void main (String[] args) {
String prompt = "Please enter your preferred unit of mass (kg, lb, g or oz): ";
System.out.println(preferredUnit(prompt));
}
public static String preferredUnit(String prompt) {
Scanner sc = new Scanner(System.in);
String unit = "";
do{
if (!unit.equals("")) {
System.out.println("Sorry but " + unit + " is not a valid unit type");
}
System.out.println(prompt);
unit = sc.nextLine();
} while(!(unit.equals("kg") || unit.equals("lb") || unit.equals("g") || unit.equals("oz")) );
return "Unit of mass: " + unit;
}
do-while
循環說: do something while a condition is true
。 你的條件是:
!unit.equals("kg") || !unit.equals("lb") || !unit.equals("g") || !unit.equals("oz")
並且退出do-while
循環必須為false
。
如果你輸入kg
,第一個條件( .unit.equals("kg")
)是false
的,這是你想要的,但不幸的是,因為下一個條件( .unit.equals("lb")
)是true
,它在OR ( ||
) 中,無論您的輸入是什么,您都將留在do-while
循環中。
您需要使用AND ( &&
) 更改條件:
!unit.equals("kg") && !unit.equals("lb") && !unit.equals("g") && !unit.equals("oz")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.