Good day everyone. I am a beginner, please do not kick much :)

There is a task: to write a program that enters a string of text from the keyboard. The program replaces the first letters of all words with capital letters in the text. Display the result on the screen.

Yes, it seemed to me a good solution:

public class Solution { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String s = reader.readLine(); s = s.toUpperCase().charAt(0) + s.substring(1); boolean sign = false; for (int i = 1; i < s.length(); i++) { char c = s.charAt(i); if (c == ' ') { sign = true; } if (sign && c != ' ') { s = s.substring(0, i) + s.toUpperCase().charAt(i) + s.substring(i + 1); sign = false; } } System.out.println(s); } } 

I understood the principle as follows: First, we immediately capitalize the first letter of the first word. Then we go through each character and as soon as we find a space and the next character is not a space, then we take what is already in the line + change the next character after the space to a capital letter.

Question: why does it work?

 if (c == ' ') {sign = true;} // если пробел "sign = true if (sign && c != ' ') // Почему это условие выполняется ??? Допустим мы вышли с первого условия с результатом sign = true. Тогда логично следующее условие предствить в виде if (с== ' ' && c != ' ') - но это бред! 

Help it to understand :)

    1 answer 1

    The value of the sign variable can affect the processing of a symbol on the next turns of the cycle. The code inside the loop can be written a little differently, then there will be no double check for space:

      char c = s.charAt(i); if (c == ' ') { sign = true; } else if (sign) { s = s.substring(0, i) + s.toUpperCase().charAt(i) + s.substring(i + 1); sign = false; } 

    In general, I don’t know how in Java, in Python, changing the list that is currently iterating is evil and results in many hard-to-catch bugs.