How to code a repetitive respond in a Try/Catch?

New learner. I am learning try/catch today. It’s a simple code asking to enter a number and if it’s not a number, I want to ask the user another time to add a number. Can I add a code repeat asking user to add a number if they keep putting the non-number input with a try/catch? Thx!

public static void main (String[]args) {		
	Scanner keyBoardInput = new Scanner(System.in);
        System.out.println("enter a number: ");
	try { double num = keyBoardInput.nextDouble ();
	      System.out.println (num);			
	}
	catch (Exception e) {			  
	 System.out.println("Invalid,please enter a number:");
	}

Yes you can. Have you learned about while loops? They repeat a section of code as long as a condition is true. For example in your code you could surround your try/catch in a while loop that will keep looping until the user has successfully entered a number.

public static void main(String[]args) { 
  Scanner keyBoardInput = new Scanner(System.in);
  System.out.println("enter a number: ");
  boolean success = false;
  while (!success) {
    try {
      double num = keyBoardInput.nextDouble ();
      System.out.println (num);
      success = true;
    }
    catch (Exception e) {		
      System.out.println("Invalid,please enter a number:");
      keyBoardInput.next ();
    }    
  }   
}

Thank you! I just started to learn the loops, I have a question regarding the boolean success:
I would assume the logics for ‘boolean success = false’ is that the user does not enter a number, that’s why it’s false? while !success in the while parenthesis already equals true, do I still need to illiterate ‘success = true’ in the try parenthesis?

You need to set success = true in the try to indicate that the user has successfully entered a number, otherwise you’ll be stuck in the loop forever. Once success is true, then !success will be false and you’ll break out of the while (!success) loop.

And there are other ways to do this same sort of thing, for example a do while loop might be more straightforward here.

public static void main(String[]args) { 
  Scanner keyBoardInput = new Scanner(System.in);
  System.out.println("enter a number: ");
  boolean isInvalid;
  do {
    isInvalid = false;
    try {
      double num = keyBoardInput.nextDouble ();
      System.out.println (num);
    }
    catch (Exception e) {
      isInvalid = true;
      System.out.println("Invalid,please enter a number:");
      keyBoardInput.next ();
    }    
  } while (isInvalid);  
}