I'm trying to understand how this solution works with a validator (nested in 'do' while). I just can not understand the order of execution of the code.

I do not understand why age = s.nextInt (); goes below the loop. In what order here what is performed?

void setAge() { Scanner s = new Scanner(System.in); do { while (!s.hasNextInt()) { System.out.println("Некорректное значение, попробуйте еще раз: "); s.next(); } age = s.nextInt(); System.out.println("Устанавливается возраст..."); if (age < 0) { System.out.println("Некорректное значение, введите еще раз: "); } if (age > 150) { System.out.println("Слишком большое значение, введите еще раз: "); } } while (age < 0 || age > 150); System.out.println("Вы установили возраст - " + this.age); } 
  • To some extent, everything is logical. Until the next value turns out to be a number, an error message is displayed. As soon as we reached the number, we left the loop and wrote down this value in age and continue to work with this variable. It is a shame not to understand this. - Nikolaj Sarry
  • This is all clear. I do not understand, roughly speaking, the following: at what point is the input initialized (the scanner object is not created, but exactly the moment when it is necessary to enter)? Why, when running while, it does not immediately display "Incorrect value, try again:"? Because the NEXT methods only respond to the next input stream? and so there was a question where in the code the indication to the first input. ps I have a week in java, I apologize for my incorrectness, which may not be visible to me - Vladislav
  • Then look for the desired code snippet and bring it. Within this fragment, there is no such code as you see. So there is another function, and maybe a class that processes input. - Nikolaj Sarry
  • Immediately the message is not displayed: "Invalid value, try again." Because at the beginning the input line is empty. - Vyacheslav Mischenko
  • 1. A scanner is created. - Vyacheslav Mischenko

1 answer 1

You have a string:

 age = s.nextInt(); 

Included in the cycle:

  do {/*тело цикла*/} while (age < 0 || age > 150); 

Such a cycle is executed at least once, then the condition is checked. By the way, the condition: "(age <0)" is starting from zero. Age can it be zero? In the condition you probably need to put: "(age <= 0)".