简体   繁体   中英

How to exit the program when a user enters a negative value - Java

Scanner input = new Scanner(System.in);

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

This because your tests are performed only after getting the 3 double values . You should move the tests corresponding to each variable just after getting its value thanks to input.nextDouble() .

Your code should rather be:

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.");
...

NB: No need to explicitly call System.exit(0) simply use return .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM