简体   繁体   English

仅当用户输入某些值时,如何使程序继续运行?

[英]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. 但是,当我输入的价格不是我的选择之一时就会出现问题,例如0.82 ,程序仍在运行。 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. 您可以使用某种循环( whiledo-whilefor ),它将继续执行代码,直到满足(或不满足)条件为止。

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纳( yourCondition == true ),该代码将回到code line 1 (将执行之间的代码块dowhile ),它会停止,一旦条件不满足( yourCondition == false )。 yourCondition could be any expression that returns a true/false result ( boolean ), such as 2+2==4 . yourCondition可以是任何返回true / false结果( boolean )的表达式,例如2+2==4

If you want to keep looping for as long as yourCondition isn't met, you can add a ! 如果要一直循环yourCondition则可以添加! before your expression, which will evaluate the opposite of your boolean like this (!yourCondition) . 在表达式之前,它将像这样(!yourCondition)评估boolean值的相反boolean

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. 如果您的价格发生变化,您所要做的就是更改最高价格,前提是仍可以将其除以0.25或条件价格检查。

Use BigDecimal (instead of double) to work with money. 使用BigDecimal(而不是double)可以省钱。 Its exact -- double isn't. 其确切-双重不是。 http://docs.oracle.com/javase/6/docs/api/java/math/BigDecimal.html 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 既然您喜欢@Sello,请回答为什么不将其与@MrD结合使用并得到类似

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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