简体   繁体   中英

I am new to coding. if user give wrong input how can we ask to reenter input without exiting code?

My question is that when user gives wrong input it throw exception msg "wrong input" and exits the code. I want to ask again to enter the input without exiting code. I tried while loop but I didn't do it right, so please help with my doubt.

import java.util.Scanner;

public class A{

    public static void main(String[] args) {
      Scanner sc=new Scanner(System.in);
      
      try {  System.out.println("enter");
      int a=sc.nextInt();
      int b=sc.nextInt();
           System.out.println(a+b);
          
      } catch (Exception e) {
          //TODO: handle exception
          System.out.println("wrong input");
          System.out.println("enter again");
         
      }
   }
}

Use while loop and break.

while (true)
{
    try {
        System.out.println("enter");
        int a = sc.nextInt();
        int b = sc.nextInt();
        System.out.println(a + b);
        break;
       } catch (Exception e) {
            System.out.println("wrong input");
            System.out.println("enter again");
            sc.nextLine();
       }
}

Only when both a and b values are entered correctly, then it'll break out of while loop, otherwise it'll keep looping.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM