简体   繁体   中英

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.

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. I realize I can make a 2D array as well as use intstream, but I haven't learned it yet. This is only a portion of the code, so using a 2D array would really complicate things.

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.

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...

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()...

productList.foreach( Product::printTotalSales );

I would use BigDecimal class instead of ints for stroing prices.

Also maybe it worth to create additional class whith two fields - categoryName and priceList. Then you will pass not arrays, but instances of this class to your method

Additionally you can look into using of 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

The 2nd version (the earlier one) of '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
Total sale for category 1: $9500
Total sale for category 2: $4301700
Total sale for category 3: $25920

Consider using a 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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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