繁体   English   中英

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

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

我的代码应该模拟类似于自动售货机的东西。 但是,当我输入的价格不是我的选择之一时就会出现问题,例如0.82 ,程序仍在运行。 如何只接受我的一种选择?

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

我尝试了类似的方法,但是没有用。 做这个的最好方式是什么。

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

是一张图片,如果您觉得它更易于阅读。

您可以使用某种循环( whiledo-whilefor ),它将继续执行代码,直到满足(或不满足)条件为止。

这是一个例子:

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

如果yourCondition纳( yourCondition == true ),该代码将回到code line 1 (将执行之间的代码块dowhile ),它会停止,一旦条件不满足( yourCondition == false )。 yourCondition可以是任何返回true / false结果( boolean )的表达式,例如2+2==4

如果要一直循环yourCondition则可以添加! 在表达式之前,它将像这样(!yourCondition)评估boolean值的相反boolean

现在,如果您了解了它的工作原理,则可以轻松地将其应用于代码。

如果您只想让用户输入您所显示的价格,我建议以下内容,您将根据自己的实际意愿进行编辑。

    //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

那将进行检查。 如果您的价格发生变化,您所要做的就是更改最高价格,前提是仍可以将其除以0.25或条件价格检查。

使用BigDecimal(而不是double)可以省钱。 其确切-双重不是。 http://docs.oracle.com/javase/6/docs/api/java/math/BigDecimal.html

我将编写一个函数来获取用户输入。 在用户输入允许值之前,它不会返回。

尽管我的真实答案是评论中的答案,但是您可以使用类似这样的内容。 递归检查是否给出了正确的值。

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


附录


既然您喜欢@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