1

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();     
    }
}

3 Answers 3

1

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);
    }
}   
Sign up to request clarification or add additional context in comments.

4 Comments

Hello. I tried doing it. But it is showing the same error. Can you run the code on your computer and paste the code here
@AnwesaRoy You use in.nextInt() to read the first entry. This does not consume the newline character. It will be consumed by in.nextLine() later on, returning an empty string. Add an extra in.nextLine() after you read the first number with in.nextInt().
One more question. As Mr. Hogenboom pointed out that since we are taking the integer input first and followed by string inputs, it may cause a problem because the nextInt() method perhaps doesn't take "nextLines" into account. Will that cause a problem here?
Right, I will consider it.
0

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).

Comments

0

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);
                }
            }
        }
    }

1 Comment

Thanks sir for your insights. I shall upvote your answer once I reach a reputation of 15.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.