Search code examples
javaarraysfor-loopmultidimensional-arrayuser-input

Multidimensional arrays from standard input


I'm trying to figure out how to read in a multidimensional array from standard input given the user provides the row and col size followed by integers of the array

e.g. Input:

        2 3      <= row, col of array
        8 3 10   < array integers
        7 9 6

My code is currently:

    int colA = scan.nextInt();
    int rowA = scan.nextInt();        

    int[][] array = new int[rowA][colA];

    for (int i = 0; i <rowA;i++){
        for (int j=0; j<colA;j++){
            array1[i][j] += scan.nextInt();
        } 
    }

And the output of my array is: [[8,3,10,7,9,6]] but what I'd like to do is output [[8,3,10],[7,9,6]]


Solution

  • Here first the row and col value got from users is reversed that is the only mistake i could see import java.util.Arrays; import java.util.Scanner;

    public class TwoDimensionalArray {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int rowA = scan.nextInt();
        int colA = scan.nextInt();
    
        int[][] array = new int[rowA][colA];
    
        for (int i = 0; i < rowA; i++) {
            for (int j = 0; j < colA; j++) {
                array[i][j] += scan.nextInt();
            }
        }
        for (int[] innerArray : array) {
            System.out.println(Arrays.toString(innerArray));
        }
    }
    

    } This is a working one