1

I want to take string inputs in java which is separated by spaces in a 2D array and display all the items in a separate line.

e.g:
input:

item1 3 5
item2 7 4

output:

item1
3
5
item2
7
4

Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
String array_of_items[][] = new String[a][b];
for(int i=0;i<a;i++)
{ 
  String str = sc.nextLine(); 
  String[] lineVector = str.split(" ");
  for(int j=0;j<b;j++)
  {
    array_of_items[i][j] = lineVector[j];
  }
}

for(int i=0;i<a;i++)
{
  for(int j=0;j<b;j++)
  {
    System.out.println(array_of_items[i][j]);
  }
}

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1

Avi
  • 2,611
  • 1
  • 14
  • 26
  • 1
    Possible duplicate of [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – Cardinal System Aug 20 '19 at 15:12
  • 1
    Your "input" and "output" are the same in the example, is it what you intended to write? – gmoshkin Aug 20 '19 at 15:16
  • You get `lineVector` by splitting a string. It seems to me that there may be not enough elements in it, which may be causing the out of bounds exception. You should check the length of `lineVector` before accessing it's elements (or catch the exception somewhere). – gmoshkin Aug 20 '19 at 15:20
  • Yes I want the same elements in output. Thanks... It is working now. – Debojit Chowdhury Aug 20 '19 at 15:58

1 Answers1

0

The first String str = sc.nextLine(); reads the new line from int b = sc.nextInt(); so your lineVector is empty => ArrayIndexOutOfBoundsException when you try to access lineVector[j]. The fix is to consume that line by adding a sc.nextLine(); after int b = sc.nextInt();.

Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
sc.nextLine();
String array_of_items[][] = new String[a][b];
for (int i = 0; i < a; i++) {
    String str = sc.nextLine();
    String[] lineVector = str.split(" ");
    for (int j = 0; j < b; j++) {
        array_of_items[i][j] = lineVector[j];
    }
}
for (int i = 0; i < a; i++) {
    for (int j = 0; j < b; j++) {
        System.out.println(array_of_items[i][j]);
    }
}

Input

2
3
1 2 3
4 5 6

Output

1
2
3
4
5
6
Butiri Dan
  • 1,759
  • 5
  • 12
  • 18