0
try
{
  System.out.println("Enter your name");
        Name = in.next();
}
catch (InputMismatchException exception) {
        System.out.println("Enter valid input");
    }

When user enters integer value, i need to pause my execution then need to display "Enter valid input" and again have to remuse my try block. How can i achieve this in java..

2 Answers2

2

Try this:

while(true)
{
    try
    {
      System.out.println("Enter your name");
            Name = in.next();
            break;
    }
    catch (InputMismatchException exception) {
            System.out.println("Enter valid input");

    }
    in.next();
    continue;
}
Mualig
  • 1,444
  • 1
  • 19
  • 42
Lucky
  • 106
  • 3
  • 9
0
int flag=0;
do{
try
{
  System.out.println("Enter your name");
        Name = in.next();
int num=Integer.parseInt(Name);//this line will generate exception if entered input is not integer
}
catch (InputMismatchException exception) {
        System.out.println("Enter valid input");
flag=1;//only run if the  Numberformatexception is generated(i.e integer was not entered)
    }
}while(flag==0);
nobalG
  • 4,544
  • 3
  • 34
  • 72