public class Test { public static boolean check(String bet) { Pattern p = Pattern.compile("^[0-9]{1,9}$"); Matcher m = p.matcher(bet); return m.matches(); } public static void main(String[] args) { System.out.println("Введите число"); Scanner scanner = new Scanner(System.in); String bet = scanner.nextLine(); if (check(bet)) { выполняется код } else { System.out.println("Некорректный ввод, попробуйте снова"); } } } 

Just learning. Tell me, is it possible to register in elsewhere a code that automatically sends to the beginning, and you really try again without restarting?

    4 answers 4

    Your idea can be implemented using cycles (for example, using the do-while ):

     boolean isCorrect; do { System.out.println("Введите число"); Scanner scanner = new Scanner(System.in); String bet = scanner.nextLine(); isCorrect = check(bet); } while (!isCorrect); // Код, который должен выполняться при корректном вводе 

      Wrap everything that you have in the main method in a separate method that returns a boolean , and then write to main :

       while(!ваш_метод()) {} 

      This cycle will work until your method returns true , and it returns it only in the case of correct input. More precisely, you yourself will tell him to return labor when necessary

        It is enough to enter one variable and use it in the condition of the do-while . for example

         public static void main(String[] args) { boolean success = false; do { System.out.println("Введите число"); Scanner scanner = new Scanner(System.in); String bet = scanner.nextLine(); success = check(bet); if ( success ) { //выполняется код } else { System.out.println("Некорректный ввод, попробуйте снова"); } } while ( !success ); } 

          I did this:

           boolean success=false; int 1 =0; Scanner 2 = new scanner(system.in); if(1==5){ success= true }else{ success=false} do{ 1=(scanner.nextInt()); if(success){ System.out.print("Good"); }else{ System.out.print("Try again"); } }while(!success); 
          • What is this esoteric programming language? - Enikeyschik
          • It turned out nonsense - the algorithm is not working. - Enikeyschik