0
public static double numBeers()
{
    String numBeersStr;
    double numBeers;

    numBeersStr = JOptionPane.showInputDialog("How many beers would you like?");

    numBeers = Double.parseDouble(numBeersStr);

    if (numBeers < 3 || numBeers > 6)
    {
        numBeersStr = JOptionPane.showInputDialog("You must pick 3-6 beers");
        numBeers = Double.parseDouble(numBeersStr);
    }

    return numBeers;
}

public static double beerPrice(double theBeerBrand)
{

    double beer = 0;
    final double LAGIMRED = 1.90;  
    final double DESINIPA = 2.00;
    final double BELBEBRN = 1.80;
    final double SCHOATST = 2.50;
    final double BOULFHSAISN = 2.75;
    final double GANDANCPRTR = 1.75;


    if (theBeerBrand == 1)
        beer = LAGIMRED;

    else if (theBeerBrand == 2)
        beer = DESINIPA;

    else if (theBeerBrand == 3)
        beer = BELBEBRN;

    else if (theBeerBrand == 4)
        beer = SCHOATST;

    else if (theBeerBrand == 5)
        beer = BOULFHSAISN;

    else 
        beer = GANDANCPRTR;        

    return beer;

}


public static double beerBrand(double theNumBeers )
{   
    String beerTypeStr;
    double count = 1, total = 0, beerType, beeer = 0;

    while (count <= theNumBeers)
    {    
        beerTypeStr = JOptionPane.showInputDialog("Please choose between these fine selections:\n1 - Lagunitas Imperial Red - $1.90\n2 - Deschutes Inversion IPA - $2.00\n3 - Bell's Best Brown Ale - 1.80\n4 - Schlafly's Oatmeal Stout - $2.50" +"\n5 - Boulevard's Farmhouse Saison - $2.75\n6 - Gandy Dancer Porter - $1.75");

            beerType = Double.parseDouble(beerTypeStr);
            // method to be invoked/called------> beeer = beerPrice(beerType);


        count++;
    }    

    total += beeer;

    return total;

beerBrandメソッドwhileループ内でbeerPriceメソッドを呼び出そうとしています。プログラムがユーザーに希望するビールの種類を尋ねるたびに、その種類のビールが合計に追加され、ユーザーが希望するビールの数と同じ回数だけ質問が再度行われます。ユーザーが望むビールの数と同じ回数だけユーザーにプロンプ​​トを表示するという問題を解決したと確信しています。希望する出力が得られないだけです。

その種類のビールをどうやってキャプチャして合計に加えるかを誰かが考えてくれれば幸いです。そうすれば、割引価格と最終価格の合計を処理することができます。配列などに触れていないチャプターテストの練習プログラムなので、配列など複雑なものは使いたくありません。助けてくれてありがとう。

4

1 に答える 1

4

有効な行を保持できます。

beeer = beerPrice(beerType);

ただし、ループするたびに合計に価格を追加する必要があるため、対応する行をwhileに戻します。

while (count <= theNumBeers) {    
    beerTypeStr = JOptionPane.showInputDialog(...);
    beerType = Double.parseDouble(beerTypeStr);
    beeer = beerPrice(beerType);
    total += beeer;

    count++;
}

変数の範囲を可能な限り制限することもお勧めします。for実際には、ビール全体を注文するので、ビールの数にint代わりにを使用することもできますdouble。その後、次のようにメソッドをリファクタリングできます。

public static double beerBrand(int theNumBeers) {   
    double total = 0;

    for (int count = 0; count < theNumBeers; count++) {    
        String beerTypeStr = JOptionPane.showInputDialog(...);
        double beerType = Double.parseDouble(beerTypeStr);
        total += beerPrice(beerType);
    }

    return total;
}

注:残りのコードはチェックしていません。

于 2012-11-11T18:31:49.920 に答える