I have a JAVA question...
I can't figure out how to combine a try/catch block with a do-while loop... I have a user input prompt (where the user is supposed to enter a number); if the user doesn't enter a number (but a letter, for example, instead), the catch block catches it, but I need it to repeat the request for that number input - I can't get it figured out, and ... I tried doing it in C# because I thought how to do it there, but I can't figure that out either anymoreNow I'm not even sure anymore if a do-while is the right way to go...
Here's the code I'm talking about
In addition to displaying that "You must enter a number!" message, it should ask the user again to input that first number... I've tried the following (and a bunch of other possibilities), but it doesn't work...Code:String inputString1; // The number entered int number1 = 0; // The input will be parsed as int BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in)); try { System.out.print("Please enter the first number: "); // User prompt for the first number inputString1 = br1.readLine(); // User input first number number1 = Integer.parseInt(inputString1); // User's input parsed as an integer } catch(NumberFormatException n) { System.out.print("You must enter a number!"); }
Any suggestions?Code:do { try { System.out.print("Please enter the first number: "); // User prompt for the first number inputString1 = br1.readLine(); // User input first number number1 = Integer.parseInt(inputString1); // User's input parsed as an integer } catch(NumberFormatException n) { System.out.print("You must enter a number! Value initialized to zero!\n "); } } while(false);




Now I'm not even sure anymore if a do-while is the right way to go...
Reply With Quote