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确实是 a,我想你通常会订购整瓶啤酒,所以你可以使用 aint而不是 adouble来表示啤酒的数量。因此,您可以像这样重构您的方法:

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 回答