如何在用户输入负值时退出程序 - Java

时间:2016-10-14 17:10:09

标签: java

扫描仪输入=新扫描仪(System.in);

    System.out.print("How much can you afford for meals per day? Enter it now ");
    double mealAmount = input.nextDouble();  

1 个答案:

答案 0 :(得分:2)

这是因为您的测试仅在获得3个双倍值后才会执行。由于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