Hello all
I haven't used Java in years been pursuing a Black Belt in a traditional martial art and received an injury and have had a 'lot' of free time recently so I decided to play around with some Java programming again and it's changed a lot.
When I last used Java receiving user input wasn't handled with a scanner and there were no try/catch options. So I have used these things trying to get user input, and make sure a user enters a number, if not create a loop to go back and ask the user to enter again.
Now, if the user enters a number all good, but, I just can't figure why the code goes into an infinite loop if the user enters anything else. It doesn't stop and ask the user to enter a number again?!? It just repeats the catch message. Any help would be greatly appreciated.
And I used the following code: excuse the formatting I am coding in notepad and its not exactly the most readable:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; //needed for the InputMismatchError import java.util.* ; public class First { public static void main(String args[]) { System.out.println(" You have just run HelloWorld !"); //BufferedReader br = new BufferedReader(); Scanner numberScan=new Scanner(System.in); System.out.println("\nEnter a number"); //create system to ask for user input if entry is wrong boolean entryWrong = true; //get user input //this is totally weird; int userInt; //try/catch pairing exception error if user doesn't enter a number,ie int //in this case //while(userEntry==true){ while(true){ try{ userInt = numberScan.nextInt(); System.out.println("You Entered a number: "+ userInt); break; //userEntry = false; } catch (InputMismatchException e){ System.out.print("\nPlease enter a number"); //userEntry = true; }//end try catch }//end while repeat System.out.println("End Main"); }//end main }//end class