简体   繁体   English

如何在一个方法中为多个数组创建一个foreach循环?

[英]How do I create a foreach loop for multiple arrays in a method?

I'm a beginner with code, so I apologize if my data structure and logic is poor practice. 我是代码的初学者,所以如果我的数据结构和逻辑不佳,我深表歉意。 I need to print out the total sale for each product . 我需要打印出每种产品总销售额 For example, for "mac" it would be labeled as Category 0, and "iphone" would be labeled as Category 1. 例如,对于“ mac”,它将被标记为类别0,而“ iphone”将被标记为类别1。

I am having trouble matching the index position for the categories with the sum of each respective category. 我在将类别的索引位置与每个类别的总和匹配时遇到麻烦。 I really just need some kind of for loop. 我真的只需要某种for循环。 I realize I can make a 2D array as well as use intstream, but I haven't learned it yet. 我意识到我可以制作2D数组,也可以使用intstream,但我还没有学过。 This is only a portion of the code, so using a 2D array would really complicate things. 这只是代码的一部分,因此使用2D数组确实会使事情复杂化。

Right now, I am trying the following: 现在,我正在尝试以下方法:

public static int[] totalSale( int[] mac, int[] iphone, int[] ipad, int[] ipod ){
    int[] totalSale = {0,0,0,0};
    int sum = 0;
    for (int i : mac) {
        sum += i;
    }
    for (int i = 0; i < totalSale.length; i++) {
        System.out.println("Total sale for category " + i + ": $" + sum);
    }
    return totalSale;
}

You could try to create a more general/reusable method. 您可以尝试创建更通用/可重用的方法。 Have your method calculate the total sale for only one product at a time. 让您的方法一次只计算一种产品的总销售额。

public static int totalSale( int[] salesFigures )
{
    int totalSale = 0;
    // calculate total sale of one product only. HINT: salesFigures.length
    return totalSale;
}

You could store all product arrays inside an ArrayList then call totalSale() inside a loop. 您可以将所有产品数组存储在ArrayList中,然后在循环内调用totalSale()。

for(/*number of products*/)
{
    //totalSales(productArray);
}

Look at the docs for java.util.Collections – foreach loops will start to become a lot more useful when it reads something like this... 看看java.util.Collections的文档–当读取这样的内容时,foreach循环将变得更加有用...

for( Product prod : productList ) // for each product in productList
{
    System.out.println( totalSales(prod) );
}

...in Java 8 and in the spirit of Object Orientation, Product will be its own class and it will @Override toString() (all classes implicitly extend java.lang.Object ) or will have its own method called printTotalSales()... ...在Java 8中,本着对象定向的精神,Product将是其自己的类,并且将@Override toString()(所有类都隐式扩展java.lang.Object )或具有其自己的名为printTotalSales()的方法。 ..

productList.foreach( Product::printTotalSales );

I would use BigDecimal class instead of ints for stroing prices. 我会使用BigDecimal类而不是ints来提高价格。

Also maybe it worth to create additional class whith two fields - categoryName and priceList. 同样值得创建带有两个字段的附加类-categoryName和priceList。 Then you will pass not arrays, but instances of this class to your method 然后,您将不传递数组,而是将此类的实例传递给您的方法

Additionally you can look into using of varargs. 另外,您可以研究使用varargs。 That allows you to use as many input parameter(of the same type) as you want. 这使您可以根据需要使用任意数量的输入参数(相同类型)。 Here is an example Java: Sending Multiple Parameters to Method 这是一个Java示例:向方法发送多个参数

The 2nd version (the earlier one) of 'totalSale' “ totalSale”的第二个版本(较早的版本)

public static int[] totalSale( int[] mac, int[] iphone, int[] ipad, int[] ipod ){

is not optimal but it is correct. 不是最佳选择,但它是正确的。 It will print out the right values. 它将打印出正确的值。
Try it here . 在这里尝试。

The output is: 输出为:

Total sale for category 0: $34500 0类的总销售额:34500美元
Total sale for category 1: $9500 第1类的总销售金额:$ 9500
Total sale for category 2: $4301700 类别2的总销售金额:4301700美元
Total sale for category 3: $25920 第3类的总销售金额:$ 25920

Consider using a Map . 考虑使用Map Here is an implmentation using 'Map': 这是使用“地图”的实现:

import java.util.HashMap;
import java.util.Map;

public class Test{

    public static void main(String[] arguments) {

        //map category to sales values
        Map<String, int[]> salesMap = new HashMap<>();

        //map category to sales totals
        Map<String, Integer> totalSalesMap = new HashMap<>();

        int[] mac = {11500,9000,13000,900,100};//total 34500
        salesMap.put("Mac",mac);
        int[] iphone = {1100,5000,3400,0,0};//total $9500
        salesMap.put("Iphone",iphone);
        int[] ipad = {900,4300000,0,800,0};
        salesMap.put("Ipad",ipad);
        int[] ipod = {0,300,120,500,25000};
        salesMap.put("Ipod",ipod);

        totalSalesMap = totalSale(salesMap);

        //print totals:
        for( String category : totalSalesMap.keySet()){
            System.out.println("Total sale for category "
                            + category + ": $" + totalSalesMap.get(category));
        }
    }

    public static Map<String, Integer> totalSale(Map<String, int[]> salesMap){

        //returned map holding sales totals
        Map<String, Integer> totalSalesMap = new HashMap<>();

        //iterate over sales map and sum values into totalSalesMap
        for( String category : salesMap.keySet()){

            int[] sales = salesMap.get(category);
            int salesSum = sumArray(sales);

            //add total to returned map
            totalSalesMap.put(category, salesSum);
        }

        return totalSalesMap;
    }

    private static int sumArray(int[] array) {

        int sum = 0;
        for(int i : array) {
            sum += i;
        }

        return sum;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM