Java – Multidimensional arrays using scanners

Multidimensional arrays using scanners… here is a solution to the problem.

Multidimensional arrays using scanners

package practice;

import java.util.*;
import java.util.ArrayList;
import java.util.Iterator;

public class Practice {

public static void main(String[] args){

Scanner input = new Scanner(System.in);
    StringBuilder output = new StringBuilder();

System.out.println("Enter the number of rows & columns: ");

System.out.print("Enter the number of rows: ");
    int row = input.nextInt();
    System.out.print("Enter the number of columns: ");
    int columns = input.nextInt();

int [][]nums = new int[row][columns];

for (int i = 0; i < row; i++)
    {
        for (int j = 0; j < columns; j++)
        {
            System.out.print("Number " + (j + 1) + ": ");
            nums[i][j] = input.nextInt();
            output.append("\n").append(nums[i][j]);
        }
        System.out.println( " " );

}

System.out.println(output);

}

}

I

have a problem with the code above, I’m practicing multidimensional arrays. What I want is to make a list of numbers separated by rows and columns, example: if I enter 3 in the row and 4 in the column, the output numbers should be arranged like this.

10 20 30 40
50 60 70 80
90 100 101 102

But the problem is that the output shows a long string of consecutive numbers.
Can anyone help me with this,

Thanks,

Solution

When switching to the next line, you must add a new line to the output:

public static void main(String[] args) {

Scanner input = new Scanner(System.in);
    StringBuilder output = new StringBuilder();

System.out.println("Enter the number of rows & columns: ");

System.out.print("Enter the number of rows: ");
    int row = input.nextInt();
    System.out.print("Enter the number of columns: ");
    int columns = input.nextInt();

int[][] nums = new int[row][columns];

for (int i = 0; i < row; i++) {
        for (int j = 0; j < columns; j++) {
            System.out.print("Number " + (j + 1) + ": ");
            nums[i][j] = input.nextInt();
            output.append(" ").append(nums[i][j]);
        }
        output.append("\n");
        System.out.println("\n");

}

System.out.println(output);

}

Related Problems and Solutions