简体   繁体   中英

How do I make my program continue only if the user enters certain values?

My code is supposed to simulate something similar to a vending machine. But there is a problem when I enter a price that is not one of my options, eg 0.82 the program still runs. How do I get it to only accept one of my options?

import java.util.Scanner;

public class VendingMachine 
{
    public static void main (String[] args)
    {
        double price;
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Choose your price. Your options are: ");
        double i;
        for (i=0.25; i<=1.25; i+=0.25)
             System.out.printf("$%.2f\n", i );

        System.out.println("Enter your selection now: ");
        price=keyboard.nextDouble();
        System.out.printf("You chose the $%.2f option. ",price);    
        double deposit;

        if (price<=1.00) {
            System.out.println("Please insert 1 dollar. *This machine only accepts Loonies*");
            deposit=1;
        } else {
            System.out.println("Please insert 2 dollars.*This machine only accepts Loonies*");
            deposit=2;
        }

        System.out.println("Please press 'Enter' to simulate inserting money. ");
        new Scanner(System.in).nextLine();

        double change;
        change = deposit-price;
        System.out.printf("Your change is $%.2f\n",change);
    }
}

I tried something like this but it doesn't work. What is the best way to do this.

if (price==i)
    System.out.println("You entered " + price);
else {
    System.out.println("Invalide choice. Please try again.")
    System.exit(0);
}

Here is an image if you find it easier to read.

You can use some sort of loop ( while , do-while , for ), which will continue to excecute the code until a condition is (or isn't) met.

Here is an example:

do {
   code line 1;
   code line 2;
   code line 3;
   ...
} while(yourCondition);

If yourCondition is satisfied ( yourCondition == true ), the code will go back to code line 1 (will perform the code block between do and while ) and it'll stop once the condition isn't satisfied( yourCondition == false ). yourCondition could be any expression that returns a true/false result ( boolean ), such as 2+2==4 .

If you want to keep looping for as long as yourCondition isn't met, you can add a ! before your expression, which will evaluate the opposite of your boolean like this (!yourCondition) .

Now, if you understood how that works, you can easily apply it to your code.

If you want the user to enter only your displayed prices, I suggest the following, you shall edit to your exact desires.

    //given you an open scanner
    boolean isCorrectPrice = false;

    System.out.println("enter price");
    price = in.nextDouble();
    while(!isCorrectPrice)
    {
       if(price%0.25==0 && price<=1.25 && price>0)
       {
          System.out.println("you entered "+price);
          IsCorrectPrice = true;
          continue;
       }
       System.out.println("incorrect price, re-enter ");
       price = in.nextDouble();
    }
   //your code after user enters correct price

That will do the check. If your prices change, all you have to do is change the maximum price provided its still dividable with 0.25 or the condition price check.

Use BigDecimal (instead of double) to work with money. Its exact -- double isn't. http://docs.oracle.com/javase/6/docs/api/java/math/BigDecimal.html

I would write a function to get the user input. It would not return until the user had entered an allowed value.

Although my real answer is the one on the comments, you can use something like this. To check recursively if the correct value was given.

import java.util.Scanner;

public class VendingMachine {

    static Scanner keyboard = new Scanner(System.in);

    public static void main(String[] args) {
        System.out.println("Choose your price. Your options are: ");
        for (double i = 0.25; i <= 1.25; i += 0.25) {
            System.out.printf("$%.2f\n", i);
        }

        double price = checkMultipleValues(0.25,1.25, 0.25);

        System.out.printf("You chose the $%.2f option. ", price);

        double deposit;
        if (price <= 1.00) {
            System.out.println("Please insert 1 dollar. *This machine only accepts Loonies*");
            deposit = 1;
        } else {
            System.out.println("Please insert 2 dollars.*This machine only accepts Loonies*");
            deposit = 2;
        }

        System.out.println("Please press 'Enter' to simulate inserting money. ");
        new Scanner(System.in).nextLine();

        double change;
        change = deposit - price;
        System.out.printf("Your change is $%.2f\n", change);
    }

    private static double checkMultipleValues(double initial,double last,double step) {

        System.out.println("Enter your selection now: ");
        double price = keyboard.nextDouble();

        for (double i = initial; i <= last; i += step) {
            if (price == i) {
                return price;
            }
        }

        return checkMultipleValues( initial, last, step);
    }
}


ADDENDUM


Since you like @Sello answer why don't you combine it with @MrD and have something like

do {
    System.out.println("enter price");
    price = in.nextDouble();
//    System.out.println("you entered " + price);
} while (!(price % 0.25 == 0 && price <= 1.25 && price > 0));

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