Sum of columns and rows of a 2D array

I searched for a fix and fix for my problem, but none of them work. One specific link is this and this , and especially this . However, no matter how I implement them, I get an OutOfBoundsError that I cannot understand.

The program is an additional loan for the class. In truth, it’s very simple -

Program Description: Use a two-dimensional array to solve the following problem. The company has four sellers (1 to 4) who sell five different products (1 to 5). Once a day, each seller skips passes for each sold product of a different type. Each slip contains:

Number of sellers
Product number
The total dollar value of this product sold on that day

Thus, each seller passes from 0 to 5 sheets of trade per day. Suppose that information from all misses for the last month is available. Each data line contains 3 numbers (seller number, product number, sales).

Write a program that will read all this information over the last months of sales, and summarizes the total sales volume of the seller by product.

Data provided:

1 2 121.77 1 4 253.66 1 5 184.22 1 1 97.55 2 1 152.44 2 2 104.53 2 4 189.97 2 5 247.88 3 5 235.87 3 4 301.33 3 3 122.15 3 2 301.00 3 1 97.55 4 1 125.66 4 2 315.88 4 4 200.10 4 3 231.45 

The error only occurs when trying to calculate columns. My ranks are working; no matter how I modify the for loop or any of the indices in the row or column of the array, this does not work. At first I calculated my rows separately, then my sum of columns, and it didn't work either. There is something that I am missing, which I clearly do not notice.

Here is my code:

 import java.io.File; import java.io.FileNotFoundException; import java.text.DecimalFormat; import java.util.Scanner; public class prog480u { static Scanner inFile = null; public static void main(String[] args) { try { // create scanner to read file inFile = new Scanner(new File ("prog480u.dat")); } catch (FileNotFoundException e) { System.out.println("File not found!"); System.exit(0); } // make the array int x = 0; int y = 0; double[][] profits = new double[4][5]; while (inFile.hasNext()) { x = inFile.nextInt(); // use sales numbers as coordinates y = inFile.nextInt(); profits[x - 1][y - 1] = inFile.nextDouble(); } // check if it okay System.out.println(""); double[][] columnProfits = sums(profits); for (int a = 0; a < columnProfits.length; a++) { System.out.print((a+1) + "\t"); for (int b = 0; b < columnProfits[a].length; b++) { System.out.print(columnProfits[a][b] + "\t"); } System.out.println(""); } double[] bottomRow = columnSums(columnProfits); for (int a = 0; a < bottomRow.length; a++) { System.out.print("Total:" + bottomRow + "\t"); } } public static double[][] sums (double[][] q) { double[][] array = new double[5][6]; array = q; double sum = 0; for (int a = 0; a < array.length; a++) { for (int b = 0; b < array[0].length; b ++) { sum += array[a][b]; // add everything in the row } array[a][4] = sum; // set that row to the last column sum = 0; // reset sum to 0 } return array; } public static double[] columnSums (double[][]q) { double[][] array = new double[5][6]; array = q; double sum2 = 0; double[] columns = new double [5]; for (int a = 0; a < array.length; a++) { for (int b = 0; b < array[0].length; b ++) { sum2 += array[b][a]; columns[b] = sum2; } sum2 = 0; // reset sum to 0 } return columns; } } 

Thanks so much for your time. I have a feeling that my program is close to work, but this small mistake pushes me to the edge.

0
source share
2 answers

Here's the working code (I cleaned it up a bit):

You were very close, you just had to change your maximum values ​​in the for loop. That is why you got java.lang.ArrayIndexOutOfBoundsException

 public static double[] columnSums(double[][] q) { double[][] array = q; double[] columns = new double[5]; for (int a = 0; a < array[0].length; a++) { for (int b = 0; b < array.length; b++) { columns[a] += array[b][a]; } } return columns; } 
+2
source

Just for fun, I wrote an object-oriented version for this purpose. Easier to handle when the system requires additional features:

 import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map.Entry; class Sale { static public ArrayList<Sale> readSales(final String pSalesFileName) throws FileNotFoundException, IOException { final ArrayList<Sale> ret = new ArrayList<>(); try (final BufferedReader br = new BufferedReader(new FileReader(pSalesFileName))) { int lineIndex = 0; while (true) { ++lineIndex; final String line = br.readLine(); if (line == null) { System.out.println("Line #" + lineIndex + " is empty, skipping..."); break; } try { final String[] values = line.split("\\s"); final int salesPersonId = Integer.parseInt(values[0]); final int productId = Integer.parseInt(values[1]); final float sales = Float.parseFloat(values[2]); final Sale sale = new Sale(salesPersonId, productId, sales); ret.add(sale); } catch (final ArrayIndexOutOfBoundsException e) { System.err.println("Parse error in line #" + lineIndex + ": '" + line + "'"); } } } return ret; } private final int mSalesPersonId; private final int mProductId; private final float mSales; public Sale(final int pSalesPersonId, final int pProductId, final float pSales) { mSalesPersonId = pSalesPersonId; mProductId = pProductId; mSales = pSales; } public Integer getSalesPersonId_R() { return Integer.valueOf(mSalesPersonId); } public Integer getProductId_R() { return Integer.valueOf(mProductId); } public float getSales() { return mSales; } } class SalesPerson { private final HashMap<Integer, ArrayList<Sale>> mSalesMap = new HashMap<>(); private final int mId; public SalesPerson(final int pId) { mId = pId; } @Override public boolean equals(final Object pObj) { if (!(pObj instanceof SalesPerson)) return false; return ((SalesPerson) pObj).mId == mId; } @Override public int hashCode() { return mId; } public void addSale(final Sale pSale) { final Integer productId = pSale.getProductId_R(); ArrayList<Sale> salesList = mSalesMap.get(productId); if (salesList == null) { salesList = new ArrayList<>(); mSalesMap.put(productId, salesList); } salesList.add(pSale); } public Integer getId_R() { return Integer.valueOf(mId); } public HashMap<Integer, ArrayList<Sale>> getSalesMap() { return mSalesMap; } public float getSalesTotalByProductId(final Integer pProductId) { final ArrayList<Sale> sales = mSalesMap.get(pProductId); float accumulator = 0; for (final Sale sale : sales) { accumulator += sale.getSales(); } return accumulator; } } public class SalesFun { public static void main(final String[] args) throws FileNotFoundException, IOException { final ArrayList<Sale> sales = Sale.readSales("test/sales.txt"); final HashMap<Integer, SalesPerson> personMap = new HashMap<>(); for (final Sale sale : sales) { // find right salesperson or create new, then add sale to it final Integer salesPersonId = sale.getSalesPersonId_R(); SalesPerson person = personMap.get(salesPersonId); if (person == null) { person = new SalesPerson(salesPersonId.intValue()); personMap.put(salesPersonId, person); } person.addSale(sale); } printSales(personMap); } static private void printSales(final HashMap<Integer, SalesPerson> pPersonMap) { for (final SalesPerson person : pPersonMap.values()) { System.out.println("SalesMan ID: " + person.getId_R()); for (final Entry<Integer, ArrayList<Sale>> entry : person.getSalesMap().entrySet()) { final Integer productId = entry.getKey(); final float sales = person.getSalesTotalByProductId(productId); System.out.println("\tProduct ID: " + entry.getKey() + "\tSales: " + sales); } } } } 
+1
source

Source: https://habr.com/ru/post/1273205/


All Articles