0

I want to make a matrix which has M rows and N columns using the scanner.
If i try to do it this way:

Scanner input = new Scanner(System.in);
int m=input.nextInt();
int n=input.nextInt();
String[][] matrix = new String[m][n];
for(int i=0;i<m;i++){
  for(int j=0;j<n;j++){
   matrix [i][j] = input.nextLine();
  }
}

It won't work.

How can i make this work?
Simple example of a matrix i want:

3 4
* * * *
* * * *
* * * *
CupidONO
  • 66
  • 6

1 Answers1

1

You need to add this code line: input.nextLine(); directly under your int n=input.nextInt(); line of code so as to consume the newline character still contained within the Scanner buffer when the ENTER key was hit from the last .nextInt() method otherwise the following .nextLine() method will consume it and take it as input giving the effect that is was skipped over.

For example:

Scanner input = new Scanner(System.in);
int m = input.nextInt();
int n = input.nextInt();
input.nextLine();
String[][] matrix = new String[m][n];
for (int i = 0; i < m; i++) {
    for (int j = 0; j < n; j++) {
        matrix[i][j] = input.nextLine();
    }
}
    
for (int i = 0; i < matrix.length; i++) {
    System.out.println(Arrays.toString(matrix[i]));
}
DevilsHnd - 退職した
  • 8,739
  • 2
  • 19
  • 22