如何计算输入的一系列计算结果数组的平均值、最大值和最小值?

huangapple go评论79阅读模式
英文:

How to calculate the average and max/min of an array of calculations from input?

问题

import java.util.Scanner;

public class Store {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);

        int count = scan.nextInt();
        String[] itemName = new String[count];
        double[] itemPrice = new double[count];

        for (int i = 0; i < count; i++) {
            itemName[i] = scan.next();
            itemPrice[i] = scan.nextDouble();
        }

        int numCustomers = scan.nextInt();
        String[] fName = new String[numCustomers];
        String[] lName = new String[numCustomers];
        double[] costs = new double[numCustomers];

        for (int j = 0; j < numCustomers; j++) {
            fName[j] = scan.next();
            lName[j] = scan.next();
            int numItems = scan.nextInt();
            double totalCost = 0;  // Initialize the total cost for this customer

            for (int k = 0; k < numItems; k++) {
                int numItemBought = scan.nextInt();
                String nameOfItem = scan.next();

                for (int i = 0; i < count; i++) {  // Iterate through the items to find the price
                    if (nameOfItem.equals(itemName[i])) {
                        double price = itemPrice[i];
                        totalCost += price * numItemBought;  // Accumulate the total cost
                    }
                }
            }
            
            costs[j] = totalCost;  // Store the total cost for this customer
        }

        double sum = 0;
        for (int l = 0; l < costs.length; l++) {
            sum += costs[l];
        }
        double average = sum / costs.length;

        // Find the largest and smallest numbers
        double temp;
        for (int p = 0; p < costs.length; p++) {
            for (int j = p + 1; j < costs.length; j++) {
                if (costs[p] > costs[j]) {
                    temp = costs[p];
                    costs[p] = costs[j];
                    costs[j] = temp;
                }
            }
        }

        double smallest = costs[0];
        double biggest = costs[costs.length - 1];

        int indexOfSmallest = 0;
        int indexOfBiggest = 0;

        for (int index = 0; index < costs.length; index++) {
            if (costs[index] == smallest) {
                indexOfSmallest = index;
            }
            if (costs[index] == biggest) {
                indexOfBiggest = index;
            }
        }

        System.out.println("Biggest: " + fName[indexOfBiggest] + " " + lName[indexOfBiggest] + " (" + biggest + ")");
        System.out.println("Smallest: " + fName[indexOfSmallest] + " " + lName[indexOfSmallest] + " (" + smallest + ")");
        System.out.println("Average: " + average);
    }
}
英文:

I am trying to make a program that will read in items and its prices, and then produce the output reporting customers with the most and least money spent, as well as the average money they all spent and the corresponding customers' names.

I am having trouble calculating the accurate max/min/average. I suspect my error is when I calculate the total cost of all items purchased by customer (as stated in my comments).

I realize a hashmap, or using classes, may be easier but I have not learned it yet and our instructor does not allow for it so I am struggling with the technologies that I do know how to use. (for loops and arrays in this case)

This is what I have below:

import java.util.Scanner;
public class Store {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// Integer count of number of items in the store
int count = scan.nextInt();
// Create an array to store names and prices of each item
String[] itemName = new String[count];
double[] itemPrice = new double[count];
for (int i=0; i&lt;count; i++) {
// Scan name of each item and price
itemName[i] = scan.next();
itemPrice[i] = scan.nextDouble();
}
// Integer count for the number of customers
int numCustomers = scan.nextInt();
String[] fName = new String[numCustomers];
String[] lName = new String[numCustomers];
double[] costs = new double[numCustomers];
double sum = 0;
double average = 0;
for (int j=0; j&lt;numCustomers; j++) {
fName[j] = scan.next();
lName[j] = scan.next();
//Number of items bought
int numItems = scan.nextInt();
for (int k=0; k&lt;numItems; k++) {
// For each number of items bought, name and quantity
int numItemBought = scan.nextInt();
String nameOfItem = scan.next();
// Find prices of the items customer bought
for (int i=0; i&lt;numItems; i++) {
if (nameOfItem.equals(itemName[i])) {
double price = itemPrice[i];
// Calculate the total cost of all items purchased by customer
costs[i] = price * numItemBought;
}
}
}
}
// Calculate the sum and average
for (int l=0; l&lt;costs.length; l++) {
sum = sum + costs[l];
average = sum/costs.length;
}
// Find the largest and smallest numbers
double temp;
for (int p=0; p&lt;costs.length; p++) {
for (int j=p+1; j&lt;costs.length; j++) {
if(costs

&gt;costs[j]) { temp = costs

; costs

= costs[j]; costs[j] = temp; } } } double smallest = costs[0]; double biggest = costs[costs.length-1]; System.out.println(&quot;Biggest: &quot; + biggest + &quot;\nSmallest: &quot; + smallest + &quot;\nAverage: &quot; + average); } }

Example input:
6

Apple 0.25

Banana 0.75

Milk 3.15

Orange 1.25

Salami 2.50

Sponge 1.15

3

Carrie Brownstein 3 2 Banana 1 Orange 2 Milk

Corin Tucker 2 3 Banana 2 Sponge

Janet Weiss 1 5 Salami

Output:
Biggest: 6.3

Smallest: 0.0

Average: 2.85

When it should be

Biggest: Janet Weiss (12.50)

Smallest: Corin Tucker (4.55)

Average: 8.70

答案1

得分: 0

问题#1: 由于查找价格的循环具有错误的界限,您无法找到许多项目的价格:

// 查找客户购买的商品的价格
for (int i=0; i<numItems; i++) {

应更改为:

// 查找客户购买的商品的价格
for (int i=0; i<count; i++) {

问题#2: costs 数组仅保留最后一项的成本,而不是累加总成本,而且成本存储在项目的索引下,而不是客户的索引下:

// 计算客户购买的所有商品的总成本
costs[i] = price * numItemBought;

要累加客户的所有成本:

costs[customerIndex] = costs[customerIndex] + price * numItemBought;

最好将索引变量重命名,以便它们有意义:例如,使用 customerIndex 替代 jitemIndex 替代 i

英文:

Problem #1: You fail to find prices for many items because the loop to find the price has incorrect bound:

                // Find prices of the items customer bought
for (int i=0; i&lt;numItems; i++) {

Should be:

                // Find prices of the items customer bought
for (int i=0; i&lt;count; i++) {

Problem #2: costs array keeps only the cost for the last item, instead of adding up the total cost, and also the cost is stored under the index of item, instead of the index of the customer:

                        // Calculate the total cost of all items purchased by customer
costs[i] = price * numItemBought;

To add up all the costs for the customer:

                        costs[j] = costs[j] + price * numItemBought;

It would help to rename the indexing variables so that they make sense: for example customerIndex instead of j and itemIndex instead of i

答案2

得分: 0

我认为你的代码需要进行很多修正。举个例子,在这个代码块中:

// Find prices of the items customer bought
for (int i=0; i<numItems; i++) {
    if (nameOfItem.equals(itemName[i])) {
       double price = itemPrice[i];
       // Calculate the total cost of all items purchased by customer
       costs[i] = price * numItemBought;
    }
}

你为什么使用numItems来循环遍历整个目录?如果我购买了一个商品,你的循环只会执行一次,并且只会检查itemName数组中的第一个商品(所以很可能你找不到我的商品,因此不会更新cost)。你应该像这样做:

for (int i=0; i<itemName.length; i++) {
    if (nameOfItem.equals(itemName[i])) {
       double price = itemPrice[i];
       // Calculate the total cost of all items purchased by customer
       costs[i] = price * numItemBought;
    }
}

另一个问题(实际上有两个问题)出现在这一行:

costs[i] = price * numItemBought;
  • 每次执行时,你都会用新的价格覆盖先前计算的价格。但我想你想要的是将每个客户的所有商品费用存储在cost中。所以你应该做类似这样的操作:costs[i] = costs[i] + (price * numItemBought);

  • 你没有正确使用costs数组的索引。它被定义为一个包含每个客户费用的数组。所以你的索引应该代表一个客户。但你正在使用i,它是一个产品索引(正如你所见,因为你在做itemName[i])。所以你把一件事情弄错了,将一个东西与另一个东西混淆了。在你目前的代码中,j代表客户,所以如果你结合我的两个注意事项,你的代码应该是这样的:costs[j] = costs[j] + (price * numItemBought);

当然还有其他需要修正的地方,但这是第一步。我的主要建议是尝试理解每个你创建的变量确切代表什么。如果对你更容易的话,不要犹豫为它们取一个更有意义的名称。例如,将j替换为customerIndexi替换为itemBoughtIndexk替换为itemIndex。在你对循环和编程有更多经验之后,你可以回到传统的“单个字母命名”方式。

英文:

I think there's a lot to fix in your code.
For example, in this block:

// Find prices of the items customer bought
for (int i=0; i&lt;numItems; i++) {
if (nameOfItem.equals(itemName[i])) {
double price = itemPrice[i];
// Calculate the total cost of all items purchased by customer
costs[i] = price * numItemBought;
}
}

Why do you use numItems, which is the number of item bought by 1 customer, to loop other all your catalog. If I buy 1 product, you will only do 1 iteration in your loop and only check the 1st product in your itemName array (so most likely you will not find my product and therefore don't update cost.
You should have something like this:

for (int i=0; i&lt;itemName.length; i++) {
if (nameOfItem.equals(itemName[i])) {
double price = itemPrice[i];
// Calculate the total cost of all items purchased by customer
costs[i] = price * numItemBought;
}
}

An other issue (2 in fact) on this line:

costs[i] = price * numItemBought;
  • everytime it's executed, you will overwrite the previously calculated price with a new one. But I would say what you want is to have the cost of all the items for each customer in cost. So you should do something like costs[i] = costs[i] + (price * numItemBought);

  • And you're not using the correct index for your costsarray. It's define as an array containing the cost for each customer. So your index should represent a customer.
    But you're using i which is an index of product (as you can see because you're doing itemName[i]. So you're mistaking one thing for another and mix your data.
    In your current code, it's j which represent customer, so if you combine my 2 remarks, your code should be costs[j] = costs[j] + (price * numItemBought);

And there's surely others things to fix, but it's a first step.

My main advice would be to try to understand what exactly represent each variable you create. And don't hesitate to give them more meaningful name if it's easier for you. For example by replacing jby customerIndex, i by itemBoughtIndex and k by itemIndex. You can go back to the classical 'one letter naming' once you have more experience with loop and programming.

huangapple
  • 本文由 发表于 2020年8月19日 21:29:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/63488095.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定