2014-02-17 4 views
-1

이 질문을 다시 게시하려고하지만 자세한 설명이 필요합니다. 아래 코드를 볼 때 각 열과 각 행의 합계를 출력하고 싶습니다. 행 합계는 해당 행의 마지막 요소 오른쪽에 있어야하며 열 합계는 주어진 열의 마지막 요소 아래에 있어야합니다. 제 출력물을 원한다면 프로그램 시작 부분에있는 주석을보십시오. 어떻게이 일을 할 수 있습니까? 또한 주어진 사용자 입력 배열의 주요 대각선을 인쇄하고 싶습니다. 아래 코드에서 주 대각선은 {1,3,5}로 출력됩니다. 고맙습니다!Java에서 2D 배열로 작업

/* 
        1 2 3 Row 0: 6 
        2 3 4 Row 1: 9 
        3 4 5 Row 2: 12 
      Column 0: 6 
      Column 1: 9 
      Column 2: 12 

*/ 
import java.util.Scanner; 
import java.util.Arrays; 


public class Test2Darray { 

    public static void main(String[] args) { 


     Scanner scan =new Scanner(System.in); //creates scanner object 

     System.out.println("How many rows to fill?"); //prompts user how many numbers they want to store in array 
     int rows = scan.nextInt(); //takes input for response 

     System.out.println("How many columns to fill?"); 
     int columns = scan.nextInt(); 
     int[][] array2d=new int[rows][columns]; //array for the elements 

     for(int row=0;row<rows;row++) 
      for (int column=0; column < columns; column++) 
      { 
      System.out.println("Enter Element #" + row + column + ": "); //Stops at each element for next input 
      array2d[row][column]=scan.nextInt(); //Takes in current input 
      } 

     for(int row = 0; row < rows; row++) 
     { 
      for(int column = 0; column < columns; column++) 
       { 
       System.out.print(array2d[row][column] + " "); 
       } 
      System.out.println(); 
     } 

     System.out.println("\n"); 



     } 



    } 
} 
+0

편집하는 대신 같은 문제에 대한 새로운 질문을 게시의이 질문 http://stackoverflow.com/questions/21820588/summing-up-a-2d-array. –

답변

0
int[] colSums = new int[array2d.length]; 
int[] mainDiagonal = new int[array2d.length]; 

for (int i = 0; i < array2d[0].length; i++) { 
    int rowSum = 0; 
    for (int j = 0; j < array2d.length; j++) { 
     colSums[j] += array2d[i][j]; 
     rowSum += array2d[i][j]; 
     System.out.print(array2d[i][j] + " "); 
     if (i == j) mainDiagonal[i] = array2d[i][j]; 
    } 
    System.out.println(" Row " + i + ": " + rowSum); 
} 
System.out.println(); 
for (int i = 0; i < colSums.length; i++) 
    System.out.println("Column " + i + ": " + colSums[i]); 
System.out.print("\nMain diagonal: { "); 
for (Integer e : mainDiagonal) System.out.print(e + " "); 
System.out.println("}"); 
+0

절대 신경 쓰지 마세요. 결정된. –

+0

흥미 롭습니다. 무엇이 잘못 되었습니까? 또한 위의 내 의견 에서처럼 열 총계를 각 열과 정렬하는 것이 어려울까요? – user3294617

+0

i = array2d [i] .length는 ArrayIndexOutOfBoundsException을 생성했습니다. print 문에 적절한 수의 공백을 포함 시키면 출력의 서식을 너무 쉽게 지정해서는 안됩니다. –