Anwesa Roy
Anwesa Roy

Reputation: 41

How to take inputs for 2 Dimensional dynamic array in Java?

I am writing a code where inputs will be taken from the user and stored in a 2-Dimensional dynamic array. We know the no. of rows of the array. But the number of columns of the array is dynamic.

The input will be in the form as shown below:

3

sghjhlklj

ghgh

ytyhuj

Since 3 is entered first, there would be three subsequent strings which have to be stored in an array.

Following is the code snippet that I have written. But it shows array index out of bounds exception.

import java.util.Arrays;
import java.util.Scanner;

class Main
{
    // Read a String from the standard input using Scanner
    public static void main(String[] args)
    {
        
        Scanner in = new Scanner(System.in); 
  
        Integer no = in.nextInt(); 
        System.out.println("You entered string "+no); 
        int z = 0,y=0 ;
        
        char[][] arr = new char[no][];
        
        for(z=0 ; z<no ; z++)
        {
            String s = in.nextLine(); 
            String[] arrOfStr = s.split("");
            for( y =0 ; y<arrOfStr.length ; y++)
            {
                arr[z][y]=arrOfStr[y].charAt(0);
                
            }
            
            
            
        }     
        
    
        in.close();     
    }
}

Upvotes: 1

Views: 718

Answers (3)

Omri Attiya
Omri Attiya

Reputation: 4037

You have 3 issues with your code:

  1. You never initialize the inner arrays. Do it with arr[z] = new char[s.length()];.
  2. The way you define arrOfStr. You split the string by the blank sub-string. Instead just use s use charAt like this: arr[z][y] = s.charAt(y);
  3. As the comments suggested, there is the issue with nextInt that does not take into account the \n (enter) char. So use int no=Integer.parseInt(in.nextLine());, instead of using nextInt.

The final code should look like this:

for(z=0 ; z<no ; z++)
{
    String s = in.nextLine(); 
    arr[z] = new char[s.length()];
    for( y =0 ; y<s.length() ; y++)
    {
        arr[z][y]=s.charAt(y);
    }
}   

Upvotes: 1

Stephan Hogenboom
Stephan Hogenboom

Reputation: 1573

Try this code:

The first problem was you did not initalize the inner array. Furthermore you used both nextInt() and nextLine(). The nextInt() method does not take into account your \n (newLine symbol) . So the nextLine() method will directly consume it and does not take into account your subsequent input.

public static void main(String[] args) {
        try (Scanner in = new Scanner(System.in)) {
            Integer no;
            do { // this is some flaky code but it works for this purpose
                try {
                    no = Integer.parseInt(in.nextLine());
                    break;
                } catch (Exception e) {
                    System.out.println("please enter only a numeric value");
                }
            } while (true);

            System.out.println("You entered string " + no);
            int z = 0, y = 0;

            char[][] arr = new char[no][];

            for (z = 0; z < no; z++) {
                String s = in.nextLine();
                String[] arrOfStr = s.split("");
                arr[z] = new char[arrOfStr.length];
                for (y = 0; y < arrOfStr.length; y++) {
                    System.out.println();
                    arr[z][y] = arrOfStr[y].charAt(0);
                }
            }
            for (char[] charArr : arr) {
                for (char c : charArr) {
                    System.out.println(c);
                }
            }
        }
    }

Upvotes: 0

Oleg Cherednik
Oleg Cherednik

Reputation: 18245

In java 2D array is initially 1D array of arrays. This is not C++:

  • You have to know the number of rows only;
  • Each sub-array (a line) could have a different length.

String[][] matrix = new String[3][]; // declare an 2D array with 3 rows and not define column length
matrix[0] = new String[5]; // 1st line has 5 columns; matrix[0][4] is the last column of 1st row
matrix[1] = new String[10]; // 2nd line has 10 columns; matrix[1][9] is the last column of 2nd row
// matrix[2] == null -> true // 3rd line is not initialized

String[][] matrix = new String[2][2]; // declare 2D array and initialize all rows with 1D sub-array with 2 columns (i.e. we have a square).

Upvotes: 0

Related Questions