Home > Back-end >  Using a nested for-loop & asking user to enter values without spaces for a matrix
Using a nested for-loop & asking user to enter values without spaces for a matrix

Time:09-14

Is it possible to ask the user to enter values WITHOUT SPACES and then fill up the matrix character for character? I know that people have answered "how to ask the user to fill up a matrix" but my question is considering filling up a matrix without spaces.

    char[][] rand = new char[3][3];
    Scanner scanner = new Scanner(System.in);
    
    for (int i = 0; i < 3; i  ) {
        for (int j = 0; j < 3; j  ) {
            rand[i][j] = scanner.next().charAt(0);
        }
    }
  
The problem with the code is that the user can enter with spaces
  2 3 1
  4 5 4
 I want the user to be able to enter without spaces but including enter so
 231
 454

If printing output should be: [[2,3,1],[4,5,4]]

CodePudding user response:

You could post an error, if a user enters a space and check it your Character with this static method of the Charakter Class, like:

Character.isWhitespace(characterToCheck)

CodePudding user response:

You can let the user type spaces.

Whether your code works or not, it's another topic, however, you can:

  • Trim spaces at the beginning and end of a string
String s = " 2 3 4 ";
String trimmed = s.trim(); // trimmed = "2 3 4"
  • Replace spaces with empty chars to eliminate them
String s = " 2 3 4 ";
String replaced = s.replace(" ", ""); // replaced = "234"
  • Split string straight into an array
String s = " 2 3 4 ";
String[] array = s.split(" ", -1); // array = [2, 3, 4]

// why is that parameter -1? check here for more [geeksforgeeks][1]
  • Related