Java filling char matrix from user without space

Viewed 35

I want to be able to ask the user to fill the matrix. The code works but the problem is that if the user dont enter values with space the output will be wrong.

enter code here
    char [][] matrix = new char[2][2];
    Scanner scanner = new Scanner(System.in);
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            matrix[i][j] =scanner.next().charAt(0);
        }
    };

   // the user can enter with space: 
      a b
      c d
   
 // however when the user enters without space the program dont stop and the matrix dont get filled in the right way:
      ab
      cd

// expected output should fill out the matrix with given values from the user without space.
 
1 Answers

It requires a space with this code because the default delimiter of Scanner is whitespace. Meaning that Scanner splits up the input at whitespace (like spaces) and scanner.next() returns the next chunk. In order to not require spaces, you have to override the default delimiter using

scanner.useDelimiter("");

before you call scanner.next() (i.e. before the for loops).

Related