There is a string consisting of numbers that are separated by a space, one number can not be more than 100. I need to check that the entered numbers are separated only by one space. If there is one space, I return true; if there is more than one, then I return false. I’ve made a check for the fact that the line contains only numbers and spaces, but the number of spaces doesn’t work. Here is what I could write:

private static boolean checkDigital(String word)throws Exception{ if (word == null) throw new Exception("Not text"); for (int i = 0; i < word.length(); i++) { char c = word.charAt(i); if (!Character.isDigit(c) && c != ' '){ return false; } } return true; } 

Tell me how to properly validate the number of spaces between numbers.

    2 answers 2

     char previousChar = '.'; for (int i = 0; i < word.length(); i++) { char c = word.charAt(i); if (!Character.isDigit(c) && c != ' '){ return false; } if (c == ' ' && c == previousChar) { return false; } previousChar = c; } 
    • In my case, after the digital symbol, there should be a space, and then again a digital symbol ... char previousChar = '.'; immediately returns false - YuriiS
    • char previousChar = '.' - it's just an assignment of a character that is not a space, it can not return anything. And the condition (c == ' ' && c == previousChar) returns false only if both the current character and the previous one are equal to a space, which is possible only with two spaces in a row. - Sergey Gornostaev
    • Thanks for the answer. Now we need to understand the essence of this decision. Simple and works. - YuriiS
     private static boolean checkDigital(String word)throws Exception{ if (word == null) throw new Exception("Not text"); char[] charArray = word.toCharArray(); boolean isSpace = false; for (char ch : charArray) { if (Character.isDigit(ch)) isSpace = false; else if (ch == ' ') { if (isSpace) return false; isSpace = true; } else return false; } return true; } 

    This way, you can verify that the string contains only digits separated by a single space. In all other cases, returns false