如何迭代多维数组的列[行]

9
我正在使用一个多维数组来存储特定销售人员(1至4名销售人员)销售的产品总量(产品范围为1至5)。
T将销售人员排列在1至4行,产品ID排列在1至5列。
唯一无法完成的是仅通过行迭代以获取每个产品的总和,即列1:行1至4的总和=产品1总数,列2:行1至4的总和=产品2总数等。
请参见测试salesTest应用程序代码,然后是Sales类。
/*
test application for sales class
*/
package salestest;

import SalesLibary.Sales;


public class SalesTest {


    public static void main(String[] args) {
        // pass monthly stats to 4r(salespesons) * c5(products 1 to 5) using initialization method
        int monthlySales [][]=  {{13, 23, 45, 67, 56},
                                {43, 65, 76, 89, 90},
                                {43, 45, 76, 98, 90},
                                {34, 56, 76, 43, 87}};
        //pass default values to constructor when creating object of class
        Sales companySales = new Sales("Monneys Inc.", monthlySales);
        companySales.displayMessage();
        companySales.displaySales();
        }//end main
    }//end SalesTest class

    //class Sales with associated methods 
/*
 Chapter 7: Practical Question 2
 */
package SalesLibary;


public class Sales {

//declare fields/members
private int salesTotals[][];
private String companyName;

//passs string and two dimensional array of sales stats to constructor from application object
public Sales(String name, int monthlySales[][]) {
    companyName = name;
    salesTotals = monthlySales;


}//end constructor

public void setCompanyName(String name) {
    companyName = name;

}

public String getCompanyName() {
    return companyName;
}

public void displaySales() {
    //table heading
    System.out.printf("The monthly sales stats for company %s are: ", companyName);
    System.out.println("                                                         ");//set columns headings
    //create column headings representing products sold 1 to 5 by looping thru each colmn of row(salsperson)
    System.out.print("            ");
    for (int product = 0; product < salesTotals[0].length; product++) {
        System.out.printf("Product %d  ", product + 1);
    }
    System.out.println("Total ");

    //create rows of table represnting salespersons 1 too 4, ten loop through array and print element
    for (int salesPerson = 0; salesPerson < salesTotals.length; salesPerson++) {
        System.out.printf("SalesPerson %2d", salesPerson + 1);


        //use nested for loop to output all results
        for (int total : salesTotals[salesPerson]) {
            System.out.printf("%10d", total);
        }
        //call method to get total for each sales person by passing
        //a row of products sold for each sales person to method
        double total = getTotal(salesTotals[salesPerson]);
        System.out.printf("%10.2f\n", total);


    }//end outer for
    System.out.println("Product Total: ");
    double productSum = getTotalProduct();
    System.out.printf("%10.2f", productSum);
    //enumerate through each column and get sum to represent product total


}//end method Display sales

//method to calculate total, argument is array of results
public double getTotal(int salesTotals[]) {
    int total = 0;
    //loop thru array passed
    for (int count : salesTotals) {
        total += count;
    }

    return total;
}// end get salesPerson tital

//display message
public void displayMessage() {
    System.out.printf("\nWlecome to %s monthly sales summaries!!!\n\n", getCompanyName());
}//end display message

//get total product sold
public double getTotalProduct() {
    int productTotal[];
    int totalProduct = 0;
    //loop through array passed
    for (int salesPerson = 0; salesPerson < salesTotals.length; salesPerson++) {
        //go through each column of row[row]
        productTotal = salesTotals[salesPerson];
        //loop thirugh product total and get sum
        for (int count : productTotal) {
            totalProduct += count;
        }

    }//end outer for loop   
    return totalProduct;
}// end get salesPerson total
}//end Sales class

相关:通过基本方向(下、上、左、右)自由遍历二维数组:http://stackoverflow.com/questions/22253140/how-to-freely-traverse-the-elements-in-a-two-dimensional-array-by-cardinal-direc - aliteralmind
4个回答

28

遍历二维数组中的单独一行 k

for (int j = 0; j < multiarray[k].length; j++)
    multiarray[k][j]; // do something

要在二维数组中迭代单列k

for (int i = 0; i < multiarray.length; i++)
    multiarray[i][k]; // do something

@shutefan,最重要的是最后的编辑,而我已经及时发现了错误。 - Óscar López
我知道这对结果来说并不重要,但为什么不考虑一下答案,然后再发送呢?这样做的好处是我可以多次重新输入评论以指出错误。 - shutefan
给那些能够提供一种简洁的方法,在一个循环中同时进行行和列迭代并重复//执行某些操作代码的人额外加分。 - MikeJfromVA

7
假设你有一个二维数组,如下所示:
int[][] salesData={{13, 23, 45, 67, 56},
                                {43, 65, 76, 89, 90},
                                {43, 45, 76, 98, 90},
                                {34, 56, 76, 43, 87}};

因此,这是一个4*5的矩阵

int[0]代表第一行,即{13,23,45,67,56}。如果需要单元格中的值,则需要使用两个for循环进行迭代。

    for (int[] rowData: salesData){
                for(int cellData: rowData)
                {
System.out.printn("the indiviual data is" +cellData);
                }
            }

1
首先,如果不需要,请勿使用所有代码。您只需要声明和可能需要一个for循环。
循环遍历列:
for(int i=0; i<monthlySales[salesPerson].length; i++) {
    monthlySales[i][salesPerson]; //do something with it!
}

0

明白了 :) 尝试将数组可视化有点困难,但最终成功了,感谢您的帮助

//loop thorugh each column to get total products sold
    for (int product = 0; product < salesTotals[0].length; product++) {
        int totalProduct = 0;
        for (int salePerson = 0; salePerson < salesTotals.length; salePerson++) {

            totalProduct += salesTotals[salePerson][product];

        }//end inner for
        System.out.printf("%10d", totalProduct);

    }//end outer for

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接