簡體   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