2013-10-20 2 views
0

2 차원 배열을 사용하여 5 행 4 열이 필요한 테이블을 만드는 프로그램에서 작업하고 있습니다. 나타나는 값의 오른쪽에있는 각 행의 합계와 아래의 각 열의 합계가 있어야합니다.Java - 2 차원 배열 내에서의 추가

   Emp. 1 Emp. 2 Emp. 3 Emp. 4 Product Totals 
Product 1 ----> 12  24  18  23   77 
Product 2 ----> 10  8  12  19   49 
Product 3 ----> 28  40  22  16   106 
Product 4 ----> 4  28  49  3   84 
Product 5 ----> 14  17  25  9   65 
////////////////////////////////////////////// 
Emp. Totals --> 68  117  126  70 

내가 가진 I가 행과 열을 추가하는 방법을 알아낼 수 있다는 것입니다 오전 문제가 : 여기처럼 보일 것입니다 것입니다. 지금까지 제가 가지고있는 코드는 다음과 같습니다.

public class TotalSales { 

    /** 
    * B. Stephens 
    * CSC-151 
    * This program will summarize the total sales by salesperson and product 
    */ 
    public static void main(String[] args) { 

     // create and assign values to multidimensional array 
     int [][] Sales = { {12,24,18,23}, {10,8,12,19}, {28,40,22,16}, {4,28,49,3}, {14,17,25,9} }; 

     // display categories 
     System.out.println("     Emp. 1 Emp. 2 Emp. 3 Emp. 4 Product Totals"); 

     // declare ProductCounter 
     int ProductCounter = 1; 

     // display array 
     for (int row = 0; row < Sales.length; row++){ 
      System.out.print("Product " + ProductCounter + " -----> "); 
      for (int column = 0; column < Sales[row].length; column++){ 
       System.out.printf(" %d\t", Sales[row][column]); 
      } 
      ProductCounter ++; 
      System.out.println(); 
     } 

     System.out.println("////////////////////////////////////////////////////////////////"); 
     System.out.println("Emp. Totals -->"); 

    } // end main 

} // end class 

제가 처음에 보여 주었던 표는 일반적인 형식입니다. 한 달 후에이 결과를 표시해야합니다. 그러면 어떻게 30 번 실행하고 모든 항목을 합산하여 월간 총계를 표시 할 수 있습니까? 카운터가 0 인 루프를 다른 루프에 추가해야합니까? 카운터 < 30만큼 길어야합니까? 그렇다면 어떻게 모든 결과를 추가 할 수 있습니까? 나는 매일의 총을 필요로하지 않는다. 나는 이것을 내가 필요한 형식의 예로서 사용하고 있었다.

답변

0
앱의 시작에서 int[] totals = {0, 0, 0, 0};

뭔가 제 for 루프의 처음에

int total = 0;, 제 for 루프 내부

total += Sales[row][column]; totals[column] += Sales[row][column];,

printf(total); 단지 제 종료 후 루프,

그리고 맨 끝에 :

for (int column = 0; column < totals.length; column++){ 
    System.out.printf(" %d\t", totals[column]); 
}