![](/img/trans.png)
[英]How to exit a do-while loop using a Scanner in Java when the user enters the word “exit”?
[英]How to exit the program when a user enters a negative value - Java
掃描儀輸入=新的Scanner(System.in);
System.out.print("How much can you afford for meals per day? Enter it now ");
double mealAmount = input.nextDouble();
這是因為僅在獲得3個double值之后才執行測試。 input.nextDouble()
獲得值之后,應立即移動與每個變量相對應的測試。
您的代碼應該是:
System.out.print("How much can you afford for meals per day? Enter it now ");
double mealAmount = input.nextDouble();
if (mealAmount <0)
System.exit(0);
else if (mealAmount < 15.00 && mealAmount >=0)
System.out.println("No meal for you. Tough luck.");
else if (mealAmount >= 15.00 && mealAmount < 30.00)
System.out.println("You can afford bronze meals.");
else if (mealAmount >= 30.00 && mealAmount < 60.00)
System.out.println("You can afford silver meals.");
else if (mealAmount >= 60.00)
System.out.println("You can afford gold meals.");
...
注意:無需顯式調用System.exit(0)
即可,只需使用return
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.