在我的Java类中有一个即将到来的测试的一些复习问题,我现在正在做的一个要求我们用两个数组创建一个咖啡馆菜单,一个菜单项,另一个是价格。我们必须先打印出所有价格的平均值,然后再向用户询问他们想要的菜单项,最后再打印出这些项的总数。
我的代码:
import java.util.Scanner;
public class cafeMenu {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int choice;
double total = 0;
//Array for storing prices
double [] cafePrice = new double[5];
cafePrice[0]= 6.99;
cafePrice[1]= 5.99;
cafePrice[2]= 2.99;
cafePrice[3]= 1.50;
cafePrice[4]= 2.50;
//Menu item array
String [] cafeDrink = new String[5];
cafeDrink[0] = "Macchiato";
cafeDrink[1] = "Latte";
cafeDrink[2] = "Americano";
cafeDrink[3] = "Tea";
cafeDrink[4] = "Cappichino";
//Welcome user and gather their menu selection
System.out.println("Welcome to our cafe! Please enjoy!");
System.out.printf("The average pricing for our drinks is: %.2f \n", + cafeAvg( cafePrice));
System.out.println("Please enter a menu selection:\n"
+ "0. Macchiato -- $6.99\n"
+ "1. Latte -- $5.99\n"
+ "2. Americano -- $2.99\n"
+ "3. Tea -- $1.50\n"
+ "4. Cappichino -- $2.50");
choice = input.nextInt();
//Add up the total
for(int i = 0; i < cafePrice.length; i++ ) {
if(choice == cafePrice[i]) {
total += cafePrice[i];
}
}
System.out.println("Your total is: " + total);
}
//Method for average menu price
public static double cafeAvg(double[] array) {
double sum = 0;
double sum2 = 0;
for(int i = 0; i < array.length; i++) {
sum += array[i];
sum2 = sum /array.length;
}
return sum2;
}
}
我还没有建立一个do-while循环来继续向用户请求输入,因为我一直坚持把价格加在一起。我可以想象我在for循环中出错了,或者可能是逻辑错误?
这是我不断得到的结果,不管做出什么选择:
欢迎来到我们的咖啡馆!请欣赏!
我们饮料的平均价格是:3.99
请输入菜单选项:
0。马奇亚托——6.99美元
1。拿铁5.99美元
2。美国——2.99美元
三。茶——1.50美元
4。卡皮奇诺——2.50美元
四
您的总数是:0.0
任何想法都会受到极大的赞赏。