title: How can I check for invalid input and loop until the input is valid?
body: <p>I am trying to find the smallest number in the list from user input. I need to ask the user how many numbers are going to be in the list (and only accept positive numbers and no letters) and then ask them what the numbers are in the list (accepting only numbers). How can I check for this and keep looping until the numbers are valid?</p>
  
  <pre><code>public class SmallestInt {
  
      /**
       * @param args the command line arguments
       */
      public static void main(String[] args) {
  
  
          // Initialize a Scanner to read input from the command line
          Scanner input = new Scanner(System. in );
          int totalIntegers = 1;
          int num = 0;
          int smallest = 0;
          boolean inputValid = false;
  
          /* Prompt the user and validate their input to ensure they've entered a positive (greater than zero) integer. Discard/ignore any other data.
           */
  
          while (!inputValid)
  
          {
              System.out.print("How many integers shall we compare? (Enter a positive integer): ");
  
              try {
                  totalIntegers = input.nextInt();
                  inputValid = true;
  
              } catch (NumberFormatException e) {
                  System.out.println("Invalid input!");
              }
  
  
              /* Read in the candidates for smallest integer
               * Validate this input as well, this time ensuring that the user has provided a valid int (any int will do at this point) and discarding any other data
               */
              for (int ii = 1; ii &lt;= totalIntegers; ii++) {
  
                  // Prompt 
                  System.out.print("Enter value " + ii + ": ");
  
                  num = input.nextInt();
  
                  if (ii == 1) smallest = num;
                  else if (num &lt; smallest) smallest = num;
  
              }
  
  
              // display smallest int
  
              System.out.println("The smallest number entered was: " + smallest);
          }
      }
  }
  </code></pre>