Добавлять цены из массива в Java? - PullRequest
0 голосов
/ 23 ноября 2018

У меня есть несколько контрольных вопросов для предстоящего теста в моем классе 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;
    }
}

Я еще не настроил цикл пока, чтобы продолжать запрашивать ввод у пользователя, потому что я как-то застрял при сложении цен.Я мог бы предположить, что допустил ошибку в цикле for или, возможно, логическую ошибку?Вот результат, который я продолжаю получать, независимо от сделанного выбора:

Добро пожаловать в наше кафе!Пожалуйста, наслаждайтесь!
Средняя цена наших напитков: 3,99
Пожалуйста, введите выбор меню:
0. Маккиато - 6,99
1. Латте - 5,99
2. Americano -$ 2,99
3. Чай - $ 1,50
4. Cappichino - $ 2,50
4
Итого: 0,0

Любые идеи будут высоко оценены.

1 Ответ

0 голосов
/ 23 ноября 2018

Вы делаете следующее неправильно,

    if(choice == cafePrice[i]) {
        total += cafePrice[i];
    }

выбор - int, в то время как cafeprice [i] - double ... более того, они представляют разные вещи.Вы действительно хотите сделать следующее, я думаю,

total += cafePrice[choice];

вместо целого цикла for.

Этот код работает для меня,

    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
    total += cafePrice[choice];
    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;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...