二维数组的列和行的总和

时间:2016-04-26 23:35:29

标签: java arrays multidimensional-array file-io

我上下搜索我的问题,但似乎都没有。一个特别的参考 - thisthis,尤其是this。但是,无论我如何实现它们,我都会收到OutOfBoundsError,这是我无法理解的。

该课程是课程的额外学分。事实上,这很简单 -

  

程序说明:使用二维数组解决以下问题。一家公司有四个销售人员(1到4人),他们销售五种不同的产品(1到5个)。每天一次,每个销售人员都会为每种不同类型的产品提供单据。每张单据包含:

     

销售人员编号
产品编号
当天销售的产品的总美元价值

     

因此,每个销售人员每天传递0到5个销售单。假设上个月所有单据的信息都可用。每条数据行包含3个数字(销售人员编号,产品编号,销售额)。

     

编写一个程序,读取上个月销售的所有信息,并按销售员按产品汇总总销售额。

提供的数据:

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

只有在尝试计算列时才会出现错误。我的行有效;无论我如何更改数组的行或列中的for循环或任何indeces,它都不起作用。我起初分别计算了我的行,然后我的列总和,它也没有用。我忽略了一些我忽略的东西。

这是我的代码:

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


}

非常感谢你的时间。我有一种感觉,我的计划已接近工作,但这个小错误让我超越了优势。

2 个答案:

答案 0 :(得分:2)

这是工作代码(我把它清理了一下):

你非常接近,你只需要在for循环中交换你的最大指标。这就是你获得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;
}

答案 1 :(得分:1)

为了好玩,我为此编写了面向对象的版本。 一旦系统需要其他功能,就更容易处理:

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

}