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方法中的beerPrice方法。每当程序提示用户他们想要什么类型的啤酒时,将该类型的啤酒添加到总量中,然后再次询问该问题的次数等于用户想要的啤酒数量。我很确定我解决了用户提示相同次数相当于他们想要的啤酒数量的问题,我只是没有得到我想要的输出。
如果有人知道如何捕获这种类型的啤酒并将其添加到总数中,那么我将非常感激,因此我可以使用总价格来计算折扣价格和最终价格。我不想使用任何数组或任何更复杂的数组,因为这是一个没有涉及数组等的章节测试的练习程序。非常感谢您给予的任何帮助。
答案 0 :(得分:4)
您可以保留有效的那一行:
beeer = beerPrice(beerType);
但是,您需要在每次循环时将价格添加到总计中,因此请将相应的行重新带入您的行中:
while (count <= theNumBeers) {
beerTypeStr = JOptionPane.showInputDialog(...);
beerType = Double.parseDouble(beerTypeStr);
beeer = beerPrice(beerType);
total += beeer;
count++;
}
最好尽可能地限制变量的范围 - 而你真的是for
,我想你通常会订购整瓶啤酒,所以你可以使用{{1}而不是啤酒数量的int
。你可以像这样重构你的方法:
double
注意:我没有检查你的其余代码。