In the first case, we use the same Scanner, in the second case, after each error, a new one is created. Inside, the Scanner is designed in such a way that, after reading it with the help of the next or nextSomething method, and if it fails, it will retain what it was not possible to assign to the variable after the reading — in itself. The next time you call the next or nextSomething method on the same Scanner, the old information will try to be assigned to the next variable, which we are trying to return the result of the next or nextSomething method, and if the data type fits, everything will be assigned.
For example, if we change the order of the input name and number, next and nextInt, make a mistake when entering the number, an infinite loop will occur, which will throw an error back to the beginning of the cycle, and try to assign incorrectly entered data that is not an int - variable int, or t .d:
import java.util.Scanner; public class A { public static void main(String[] args) { scan_info_play(); } static player scan_info_play() { Scanner in = new Scanner(System.in);//1 Variant player player__; String name; int num; while (true) { try { //Scanner in = new Scanner(System.in);//2 Variant System.out.print("Data:\n"); System.out.print("No:"); num = in.nextInt(); System.out.print("Na:"); name = in.next(); break; } catch (java.util.InputMismatchException e) { System.out.println("UNCORRECT DATA !"); continue; } } player__ = new player(num, name, false); return player__; } } class player { // Результат "[Бесконечный цикл]" player(int num, String name, boolean b){ System.out.println(num + " " + name + " " + b); } }
In the second, swap the next and nextInt, do as in your case, make a mistake when entering int, incorrectly entered data that should have been int, will be easily assigned to the String type in the next iteration, after the next () method is executed;
import java.util.Scanner; public class A { public static void main(String[] args) { scan_info_play(); } static player scan_info_play() { Scanner in = new Scanner(System.in);//1 Variant player player__; String name; int num; while (true) { try { //Scanner in = new Scanner(System.in);//2 Variant System.out.print("Data:\n"); System.out.print("Na:"); name = in.next(); System.out.print("No:"); num = in.nextInt(); break; } catch (java.util.InputMismatchException e) { System.out.println("UNCORRECT DATA !"); continue; } } player__ = new player(name, num, false); return player__; } } class player { player(String name, int num, boolean b){ System.out.println(name + " " + num + " " + b); // Результат ["неправильно введённый в первый раз int", "int на второй итерации", "false"] } }