1

Input i have to deal with:

2
2 3
3 3

My code:

Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();

int[][] array = new int[size][2];
Scanner scanner2 = new Scanner(System.in);

for (int i=0; i<size; i++) {
    for (int j=0; j<2; j++) {
        array[i][j] = scanner2.nextInt();
    }
}

2 is number of pairs that input contains. I want to put those pairs in 2D array but I need to get 2 first to declare size of an array. Above code works well in NetBeans where I give input like:

number 
enter 
pair 
enter
...

But all numbers come together in a format I posted above.

Any help?

Nicolas Filotto
  • 39,066
  • 11
  • 82
  • 105
dddeee
  • 237
  • 4
  • 11

1 Answers1

1
public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in).useDelimiter("\\n");
    System.out.println("Enter an integer");
    int size = scanner.nextInt();

    int[][] array = new int[size][2];

    for (int i = 0; i < size; i++) {
        String myInt = scanner.next();
        String[] myInts = myInt.split(" ");
        for (int j = 0; j < 2; j++) {
            array[i][j] = Integer.parseInt(myInts[j]);
        }
    }
    // print contents
    for (int i = 0; i < size; i++) {
        for (int j = 0; j < 2; j++) {
            System.out.println("[" + i + "]" + "[" + j + "] = " +array[i][j]);
        }
    }        
}