title: Try/Catch inside While in static main method
body: <p>I don't understand the logic to this. If I run this code and enter a non-int such as the letter f, I get stuck in an infinite loop outputting the two println's and I am not given another chance to input an int to the scanner...it just keeps spitting out words to the console.</p>
  
  <pre><code>public static void main(String[] args) {
  
      Scanner scan = new Scanner(System.in);//&lt;&lt;&lt;&lt;&lt;SCANNER HERE
      int opponents = 0;
      boolean opponentsCreated = false;
      while(opponentsCreated == false)
      {
          try
          {
              System.out.print("How many players: ");
              int tempOpponents = scan.nextInt();
              if(tempOpponents &gt; 0)
              {
                  opponents = tempOpponents;
                  opponentsCreated = true;
              }   
          }
          catch(InputMismatchException notAValidInt)
          {
              System.out.println("Not valid - must be a number greater than 0 ");
          }   
      }
  }
  </code></pre>
  
  <p>But if I simply change the Scanner to be declared inside the while loop, all of a sudden the program works as expected: </p>
  
  <pre><code>public static void main(String[] args) {
  
      int opponents = 0;
      boolean opponentsCreated = false;
      while(opponentsCreated == false)
      {
          Scanner scan = new Scanner(System.in);//&lt;&lt;&lt;&lt;&lt;SCANNER HERE
          try
          {
              System.out.print("How many players: ");
              int tempOpponents = scan.nextInt();
              if(tempOpponents &gt; 0)
              {
                  opponents = tempOpponents;
                  opponentsCreated = true;
              }   
          }
          catch(InputMismatchException notAValidInt)
          {
              System.out.println("Not valid - must be a number greater than 0 ");
          }   
      }
  }
  </code></pre>
  
  <p>I honestly just sat here for 2 hours trying to figure out what the heck was wrong with my program only to find out it was a matter of where I declared my Scanner even though in both versions of the code the Scanner was not out of scope. So now I'm really curious why it works this way</p>