0

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;
}
9
  • You seem to be assuming that all your arrays int[] mac, int[] iphone, int[] ipad, int[] ipod have the same length. Is it the case? And what do they represent? Commented Oct 8, 2016 at 17:53
  • @Alain sorry about that. I added example input values. But the arrays should represent a list of cost for the days listed Commented Oct 8, 2016 at 17:56
  • And what error do you get when you run your first version? Commented Oct 8, 2016 at 18:01
  • It prints: Total sale for category 0: $34500 Total sale for category 1: $34500 Total sale for category 2: $34500 Total sale for category 3: $34500 So I am guessing it only prints what I typed for mac, but I am not sure how to make it apply to the other arrays as well. Commented Oct 8, 2016 at 18:04
  • By first I meant earliest. The second one you listed. It looks fine to me. Commented Oct 8, 2016 at 18:07

3 Answers 3

1

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 );
Sign up to request clarification or add additional context in comments.

Comments

0

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;
    }
}

3 Comments

It works! But the problem is if there are more than 4 input values-- it doesn't print out properly. So it's useless because the methods should be able to take inputs up to 31 values.
If it works for 4 it will work for 31. You need to pass 31 arrays to ` totalSale` and make int[] totalSale size of 31. Very cumbersome of course, hence my suggestion to use map.
I added an implementation using Map which is more scaleable.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.