How to avoid infinite loop when using try/catch? - java

I have this code
public void askUserForStrategy(){
try{
System.out.println("What strategy do you want to use?\n");
System.out.println("1 = Math.random\t 2 = System time\t "
+ "3 = Sum of Math.random and System time");
int strategy = sc.nextInt();
selectStrategy(strategy);
}
catch(InputMismatchException Exception){
System.out.println("That is not an integer. Try again.\n");
askUserForStrategy();
}
}
What I want it to do is basically ask the user to type in an integer, and in case the user the users types a String for example, catch that exception and start the method again (ask the user to type in an integer value). But the method loops when the user types in a String.

When nextInt() throws an exception, the Scanner object tries to use the same string on the next call.
Try allocating a new Scanner Object within the try. Or try to call nextLine() within the catch, so you will discard the illegal line.
Please note that this method is not good, because after too many illegal inputs (very many, but the ideal is to have infinite tries) a stack overflow will occur.
I suggest you to use a do-while and return at the end of the try body.

Try this:
public void askUserForStrategy() {
for(int i=0; i<1; ++i) {
try{
System.out.println("What strategy do you want to use?\n");
System.out.println("1 = Math.random\t 2 = System time\t "
+ "3 = Sum of Math.random and System time");
int strategy = sc.nextInt();
selectStrategy(strategy);
break; //break loop when there is no error
}
catch(InputMismatchException Exception){
System.out.println("That is not an integer. Try again.\n");
//askUserForStrategy();
continue; //for clarity
}
}
}

Maybe you're looking for something like this
public void askUserForStrategy(){
Boolean loopFlag = true;
while(loopFlag) {
try{
System.out.println("What strategy do you want to use?\n");
System.out.println("1 = Math.random\t 2 = System time\t "
+ "3 = Sum of Math.random and System time");
int strategy = sc.nextInt();
Integer.parseInt(strategy);
loopFlag = false;
selectStrategy(strategy);
}
catch(Exception e){
//Parse has failed due to wrong input value, But loop will continue
}}}

This may be you are looking for..
public void askUserForStrategy() {
while (true) {
try {
Scanner sc = new Scanner(System.in);
System.out.println("What strategy do you want to use?\n");
System.out.println("1 = Math.random\t 2 = System time\t " + "3 = Sum of Math.random and System time");
int strategy = sc.nextInt();
System.out.println("Selected strategy : " +strategy);
break;
} catch (Exception e) {
System.out.println("That is not an integer. Try again.\n");
continue;
}
}
// selectStrategy(strategy);
}
If user selects String, then again it will ask for options..
If user selects Integer, then it will take user selected strategy option and continue the program flow.. (Means come out of the while loop with the help of break and then calling selectStrategy method)
Thanks

Related

More efficient way to handle user input data validation?

In Java, I have two while loops to validate user input and continuously prompt the user if they input the wrong data type. In this program, I only have 2 questions, but I can imagine a scenario where I have more than 10, at which point 10 while loops would be cumbersome code to read and maintain. Is there a more efficient way to check for errors while continuing to prompt the user? My initial thought is to package the while loop and error checks into a separate class function and call it when input is requested.
import java.util.*;
public class IncreaseAge {
public static void main(String args[]){
Scanner userInput = new Scanner(System.in);
boolean validInput = true;
String coolName = "Adam";
int coolAge = 0;
while(validInput){
try{
System.out.print("Hello, what is your first name? ");
coolName = userInput.nextLine();
validInput = false;
}
catch(Exception error){
System.out.println("Invalid input, try again!");
userInput.next();
}
}
validInput = true;
while(validInput){
try{
System.out.print("Hi "+ coolName + "! How old are you?");
coolAge = userInput.nextInt();
validInput = false;
}
catch(Exception error){
System.out.println("Invalid input, try again!");
userInput.next();
}
}
System.out.println("Hello "+ coolName + ", in ten years you will be " + (coolAge+10));
userInput.close();
}
}
Just implement private int getIntegerInput(String prompt) and private String getStringInput(String prompt), each of which will more or less be the same as the two loops you've already coded.
This is a common and frequent way to avoid code repetition - implement "helper" routines to be used in writing your intended functionality.
Even if you don't have repetition to worry about, it's a useful partitioning of code, making it easier to understand - for example, the "get an input" code is clearly distinct from the "process the input" code.
Example:
private String getStringInput(Scanner scanner, String prompt) {
String input = null;
boolean validInput = false;
while (!validInput) {
try {
System.out.print(prompt);
input = scanner.nextLine();
validInput = !input.isEmpty();
}
catch (Exception error) {
System.out.println("Invalid input, try again!");
}
}
return input;
}
Note that I fixed the use of 'validInput' to make sense, and I assume you want to reprompt on an empty input line.
Usage is then like
String coolName = getStringInput(userInput, "What is your first name? ");

How do I get user input to allow another input after cycling through a loop?

I'm fairly new to Java. I've done some C++ so I understand a lot of the concepts. I've been working on this code that allows me to ask for input on a tip calculator. I know some of the code is inconsistent but it's because I've been trying various methods to get it to display.
I can go through the program once asking for user input. However when I loop through it again, it just displays the same input I put in prior. I'm trying to get it to show then loop through, take new input and display that. I've been teaching myself this so it's a learning experience for me, however I'm stumped and not sure where to go from here. Any help is appreciated.
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.InputMismatchException;
import java.util.Scanner;
public class TipApp {
public static void main(String[] args) {
calculateTips();
}
public static void calculateTips () {
Scanner input = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
String pattern = "$##,###,###.00;"; // Pattern string for the decimal format
DecimalFormat moneyFormat = new DecimalFormat(pattern); // Decimal Money format
NumberFormat defaultFormat = NumberFormat.getPercentInstance();
defaultFormat.setMinimumFractionDigits(1);
String choice;
double theBill;
int theTip;
int thePartySize;
boolean isBillValid = true;
boolean isTipValid = true;
boolean isPartySizeValid = true;
TipCalculator tipCalculator1 = new TipCalculator();
System.out.println("*** Tip Calculator ***");
do {
System.out.print("\nEnter the bill amount: ");
while (isBillValid) {
try {
if (input.hasNextDouble()) {
theBill = input.nextDouble();
isBillValid = false;
tipCalculator1.setBillAmount(theBill);
}
} catch (InputMismatchException e) {
System.out.println(input.next() + " is not a valid number");
}
input.nextLine();
}
System.out.print("Enter your desired tip percentage (20 equals 20%): ");
while (isTipValid) {
if (input.hasNextInt()) {
theTip = input.nextInt();
isTipValid = false;
tipCalculator1.setTipPercentage(theTip);
} else {
System.out.println("Please enter a valid tip percentage.");
isTipValid = true;
}
input.nextLine();
}
System.out.print("Enter the size of your party: ");
while (isPartySizeValid) {
if (input.hasNextInt()) {
thePartySize = input.nextInt();
isPartySizeValid = false;
tipCalculator1.setPartyAmount(thePartySize);
} else {
System.out.println("Please enter a valid party size.");
isPartySizeValid = true;
}
input.nextLine();
}
System.out.println("*** Your Bill ***");
System.out.print("\nBill Amount: ");
System.out.println(moneyFormat.format(tipCalculator1.getBillAmount()));
System.out.print("Tip Percentage: ");
System.out.println(defaultFormat.format(tipCalculator1.getTipPercentage()));
System.out.print("Party Size: ");
System.out.println(tipCalculator1.getPartyAmount());
System.out.print("\nTotal Bill (with Tip): ");
System.out.print(moneyFormat.format(tipCalculator1.getTotalAmount()));
System.out.print("\nShare for Each Individual: ");
System.out.print(moneyFormat.format(tipCalculator1.getIndividualShare()));
System.out.print("\nAnother Bill? (y/n): ");
choice = scan.nextLine();
} while (choice.equalsIgnoreCase("y")) ;
System.out.println("\nGoodbye!");
}
}
public class TipCalculator {
private double billAmount;
private int tipPercentage;
private int partyAmount;
// Constructor that holds 3 arguments
public TipCalculator() {
setBillAmount(billAmount);
setTipPercentage(tipPercentage);
setPartyAmount(partyAmount);
}
public double getBillAmount() {
return billAmount;
}
public void setBillAmount(double billAmount) {
this.billAmount = billAmount;
}
public double getTipPercentage() {
return tipPercentage / 100f;
}
public void setTipPercentage(int tipPercentage) {
this.tipPercentage = tipPercentage;
}
public int getPartyAmount() {
return partyAmount;
}
public void setPartyAmount(int partyAmount) {
this.partyAmount = partyAmount;
}
public double getIndividualShare() {
return (getTotalAmount() / partyAmount);
}
public double getTotalAmount() {
return (billAmount * getTipPercentage()) + billAmount;
}
}
[1]: https://i.stack.imgur.com/5tHIs.png
First off, use only one Scanner object, you don't need more than that. Perhaps name is userInput.
The problem you are having is because you are not resetting some key variables for the next bill to be calculated, in particular those that are used in conditions for your loops.
Take the following variables:
boolean isBillValid = true;
boolean isTipValid = true;
boolean isPartySizeValid = true;
double theBill;
int theTip;
int thePartySize;
and move them to the top of your do loop (the main outer loop) and initialize the String variable choice to hold a null string (""), for example:
do {
choice = "";
boolean isBillValid = false;
boolean isTipValid = false;
boolean isPartySizeValid = false;
double theBill = 0.0d;
int theTip = 0;
int thePartySize = 0;
System.out.print("\nEnter the bill amount: ");
while (isBillValid) {
try {
//..... The rest of your code ....
This way the conditions for your loops will not already be set from the previous bill should the User enter 'y' to process another Bill.
In my opinion, every prompt which requires User input of some kind should ensure valid input and this would include the Another Bill? (y/n): prompt, for example:
while (choice.isEmpty()) {
System.out.print("\nAnother Bill? (y/n): ");
choice = userInput.nextLine();
// Is only a 'y' or a 'n' supplied (regardless of letter case)
if (!choice.matches("(?i)[yn]")) {
// No...inform User and have him her try again.
System.out.println("Invalid input - 'y' or 'n' only! Try again...");
choice = ""; // Reset the 'choice' variable to null string.
}
}
The if statement condition in the above code utilizes the String#matches() method along with a small Regular Expression (RegEx). Within the regex string, the (?i) means 'ignore letter case' and the [yn] means: matches only the 'y' or 'n' characters. So, if the supplied choice does not match either y, Y, n, or N then the condition is true.
This sort of validation should apply to all your prompts to the User so as to ensure a trouble free experience for the User, after all, typo's do happen. Take the Tip Percentage entry for example, what is to happen if the User enters -10?. This would be okay if your were applying a discount coupon or something but not so much for a tip. I think it might be best for the User to enter a value within a specific range like 0 to 100 (or whatever you like):
while (!isTipValid) {
System.out.print("Enter your desired tip percentage (0 to 100): --> ");
try {
theTip = userInput.nextInt();
// Is the tip percentage inclusively between 0 and 100?
if (theTip < 0 || theTip > 100) {
// No...
throw new java.util.InputMismatchException();
}
isTipValid = true;
tipCalculator1.setTipPercentage(theTip);
}
catch (java.util.InputMismatchException ex) {
System.out.println("Invalid tip percentage supplied (" + theTip + ")! Try again...");
}
userInput.nextLine();
}
In the above example loop code you will most likely notice a few things done differently here.
To begin with, the condition for the while loop better represents the name of the boolean variable isTipValid. The variable name is in a sense more like a question: Is the Tip Valid?. By default you have this variable initialized to true which is basically like saying "Yes, the Tip is Valid!" when in reality that hasn't been established yet. For better clarity I think this variable (and others like it) should be initialize to boolean false and then changed to boolean true only after it is definitely determined that the value supplied is indeed valid.
Another change you may have noticed is the fact that the displayed prompt string to the Console Window is placed within the while loop rather than above it. This ensures that if an invalid situation occurs and the prompt requires further input then the User will definitely know what is requested. It's a good idea that all of your prompt mechanism be contained within the while loop that pertains to it. The prompt string has also be modified to indicate to the User that a value within the range of 0 to 100 is expected.
Another change you may have noticed is the fact that the if (input.hasNextInt()) { line has been replaced with a Try/Catch mechanism. This actually provides a more definite means to ensure proper data entry since the Scanner#hasNextInt() method (and other hasNext...() methods) is better suited for tokenized input whereas a delimited series of integer numbers may be in or combined within that input. It can of course be used in this use-case but requires additional handling to accommodate all possible invalid situations.
You will also see an additional if statement that is used to check whether or not the value supplied is within the described range of 0 to 100. If it isn't then an InputMismatchException is thrown which forces the code-flow to immediately fall into the catch clause which ultimately indicates the problem to the User ans re-prompts for another value.
Doing the above similarly to your other Prompts will produce a much better outcome and you will know that the values supplied will be valid with the exception of the Bil Amount prompt:
while (!isBillValid) {
System.out.print("Enter the bill amount: --> ");
try {
theBill = userInput.nextDouble();
if (theBill < 0) {
throw new java.util.InputMismatchException();
}
isBillValid = true;
tipCalculator1.setBillAmount(theBill);
} catch (java.util.InputMismatchException e) {
System.out.println("Invalid Bill amount supplied (" + theBill + ")! Try again...");
}
userInput.nextLine();
}
This will work well for pretty much all invalid possibilities except for this simple typo: 3e4 example. This is considered a valid double value by the Scanner#nextDouble() method. The e or E within the supplied value is considered a value in Scientific E Notation and in its drawn out state is the same as a double value of 30000.0. So, instead of the intended $34 bill the 3e4 ends up being a real healthy bill of $30,000.00. To cover this situation a slightly different approach will need to be used. In the code below you will see not just how the Bill Amount prompt code is done using this different approach but also all other prompts:
public void calculateTips() {
Scanner userInput = new Scanner(System.in);
String pattern = "$##,###,###.00;"; // Pattern string for the decimal format
java.text.DecimalFormat moneyFormat = new java.text.DecimalFormat(pattern); // Decimal Money format
java.text.NumberFormat defaultFormat = java.text.NumberFormat.getPercentInstance();
defaultFormat.setMinimumFractionDigits(1);
String choice;
TipCalculator tipCalculator1 = new TipCalculator();
System.out.println("*** Tip Calculator ***");
do {
choice = "";
boolean isBillValid = false;
boolean isTipValid = false;
boolean isPartySizeValid = false;
double theBill = 0.0d;
int theTip = 0;
int thePartySize = 0;
boolean breakAll = false;
while (!isBillValid) {
System.out.print("Enter the bill amount: --> ");
String theBillStrg = userInput.nextLine().trim();
// Is 'c' or 'C' for CANCEL entered?
if (theBillStrg.equalsIgnoreCase("c")) {
// Set breakAll to true break out of this loop.
breakAll = true;
break;
}
// If the value starts with a decimal point then
// prefix it with a 0.
if (theBillStrg.startsWith(".")) {
theBillStrg = "0" + theBillStrg;
}
// If the value ends with a decimal point then
// postfix it with a 0.
else if (theBillStrg.endsWith(".")) {
theBillStrg += "0";
}
// Is the supplied value a string representation of a
// Integer or double type value?
if (theBillStrg.matches("\\d+(\\.\\d+)?")) {
// Yes it is...
// Parse the string value to a double type
theBill = Double.parseDouble(theBillStrg);
isBillValid = true;
tipCalculator1.setBillAmount(theBill);
}
else {
System.out.println("Invalid Bill amount supplied (" + theBillStrg + ")! Try again...");
}
}
while (!isTipValid && !breakAll) {
System.out.print("Enter your desired tip percentage (0 to 100): --> ");
String theTipStrg = userInput.nextLine();
// Is 'c' or 'C' for CANCEL entered?
if (theTipStrg.equalsIgnoreCase("c")) {
// Set breakAll to true break out of this loop.
breakAll = true;
break;
}
// Is a string representation of a Integer value supplied?
if (theTipStrg.matches("\\d+")) {
// Yes...Convert the string value to Integer
theTip = Integer.parseInt(theTipStrg);
// Is the tip percentage inclusively between 0 and 100?
if (theTip < 0 || theTip > 100) {
// No...
System.out.println("Out of Range tip percentage supplied (" + theTip + ")! Try again...");
continue;
}
isTipValid = true;
tipCalculator1.setTipPercentage(theTip);
}
else {
System.out.println("Invalid tip percentage supplied (" + theTipStrg + ")! Try again...");
}
}
while (!isPartySizeValid && !breakAll) {
System.out.print("Enter the size of your party: ");
String partySizeStrg = userInput.nextLine();
// Is 'c' or 'C' for CANCEL entered?
if (partySizeStrg.equalsIgnoreCase("c")) {
// Set breakAll to true break out of this loop.
breakAll = true;
break;
}
else if (partySizeStrg.matches("\\d+")) {
thePartySize = Integer.parseInt(partySizeStrg);
isPartySizeValid = true;
tipCalculator1.setPartyAmount(thePartySize);
}
else {
System.out.println("Invalid party size supplied (" + partySizeStrg + ")! Try again...");
}
}
if (!breakAll) {
System.out.println();
System.out.println("======================================");
System.out.println("*** Your Bill ***");
System.out.println();
System.out.print("Bill Amount: ");
System.out.println(moneyFormat.format(tipCalculator1.getBillAmount()));
System.out.print("Tip Percentage: ");
System.out.println(defaultFormat.format(tipCalculator1.getTipPercentage()));
System.out.print("Party Size: ");
System.out.println(tipCalculator1.getPartyAmount());
System.out.print("\nTotal Bill (with Tip): ");
System.out.println(moneyFormat.format(tipCalculator1.getTotalAmount()));
System.out.print("\nShare for Each Individual: ");
System.out.println(moneyFormat.format(tipCalculator1.getIndividualShare()));
System.out.println("======================================");
}
while (choice.isEmpty()) {
System.out.print("\nAnother Bill? (y/n): ");
choice = userInput.nextLine();
if (!choice.matches("(?i)[yn]")) {
System.out.println("Invalid input - 'y' or 'n' only! Try again...");
choice = "";
}
}
System.out.println();
} while (choice.equalsIgnoreCase("y"));
System.out.println("\nGoodbye!");
}

Having an incedibly tough time with a loop

I've copied part of the instructions below, and I can code pretty much every part on its own, but getting the control flow together is giving me massive doubts about my ability.
One of my biggest problems is the int gameChanger. Im supposed to immediately verify if it is a integer or not, and loop back if its not. But then Im also supposed to check to see if thebuser ever types "exit". But the input variable for my scanner instance is an integer... So Im stumped. I can use a try catch to check the missmatchexception once the input is being read in, but that doesnt solve the exit issue nor am I able to come up with solid logic to get the try catch to loop back if it indeed isnt an integer. Im thinking a do while loop but I havent gotten it to work.
Instructions:
You can whether the input is a number before attempting to consume it.
int num;
while (true) {
if (scanner.hasNextInt()) {
num = scanner.nextInt();
break;
} else {
// read whatever is there instead.
String line = scanner.nextLine();
if (line.equals("exit"))
System.exit(0);
System.out.println("Please enter a number");
}
}
System.out.println("Number entered " + num);
This gets the job done. Try it out.
import java.util.Scanner;
public class MyCode
{
public static void main(String[] args)
{
String gameInput = ".";
int gameNumber = 0;
boolean inputLoop = true;
Scanner input = new Scanner(System.in);
while(inputLoop == true)
{
try
{
System.out.print("Please enter a valid game number: ");
gameInput = input.next();
if(gameInput.equals("exit"))
{
System.out.println("Program will now end. Goodbye.");
inputLoop = false;
input.close();
}
gameNumber = Integer.parseInt(gameInput);
if(gameNumber >= 20001 && gameNumber <= 21230)
{
System.out.println("You have inputted a valid game number.");
inputLoop = false;
input.close();
}
}
catch(NumberFormatException e)
{
if(!gameInput.equals("exit"))
{
System.err.println("Invalid game number. Please try again.");
}
}
}
}
}

Java - try/catch infinite repeat

Requirement:
Accept 10 numbers, input them into an array and then invoke a method to calculate and return the smallest. This program is suppose to be error proof so when a user enters an invalid entry, it notifies the user and reprompts. I am trying to use try catch but when an invalid entry is entered, ie a character, the scanner won't reprompt.
Any ideas?
Tried:
//Variables
double [] doubleArray = new double[10];
Scanner input = new Scanner(System.in);
//Prompt
System.out.println("This program will prompt for 10 numbers and display the smallest of the group");
//Get values
for (int i = 0; i < doubleArray.length; i++) {
try {
System.out.println("Please enter entry "+ (i+1));
doubleArray[i] = input.nextDouble();
} catch (InputMismatchException e) {
// TODO: handle exception
System.out.println("Please enter a rational number");
i--;
}
}
//Invoke method and display result
System.out.println("The smallest value is: "+index(doubleArray));
I don't see any call to input.nextLine(), which means nothing is ever consuming the \n entered by the user. There's a good example on scanner.nextLine usage here. If you add a call to it in your catch block, you should be all set.
Try calling input.nextLine(); in your catch. Then the \n will be taken from the input which let's you enter the next new number.
for(int i = 0; i < doubleArray.length; ++i) {
try {
doubleArray[i] = input.nextDouble();
} catch(Exception e) {
input.nextLine();
--i;
}
}
Try something like (and make sure you consume the whole line unless you want to allow multiple numbers to be input on the same line
boolean validEntry = false;
System.out.println("Enter a rational number: ");
while (!validEnry) {
try {
double value = input.nextDouble();
validEntry = true;
doubleArray[i] = value;
} catch (Exception e) {
System.out.println("Entry invalid, please enter a rational number");
}
}
...
You have to discard the false inputted data, add input.nextLine() in the catch block.

Looping around a try catch

In the below code I am attempting to allow the program to catch an exception for an invalid input from user but still allow the program to loop back to the start of the method once exception has been caught. However in my example once there is an exception the program terminates. How can I rectify this? Thank a lot in advance!
public static void add() {
// Setting up random
Random random = new Random();
// Declaring Integers
int num1;
int num2;
int result;
int input;
input = 0;
// Declaring boolean for userAnswer (Defaulted to false)
boolean correctAnswer = false;
do {
// Create two random numbers between 1 and 100
num1 = random.nextInt(100);
num1++;
num2 = random.nextInt(100);
num2++;
// Displaying numbers for user and getting user input for answer
System.out.println("Adding numbers...");
System.out.printf("What is: %d + %d? Please enter answer below", num1, num2);
result = num1 + num2;
do {
try {
input = scanner.nextInt();
} catch (Exception ex) {
// Print error message
System.out.println("Sorry, invalid number entered for addition");
// flush scanner
scanner.next();
correctAnswer=false;
}
} while (correctAnswer);
// Line break for code clarity
System.out.println();
// if else statement to determine if answer is correct
if (result == input) {
System.out.println("Well done, you guessed corectly!");
correctAnswer = true;
} else {
System.out.println("Sorry incorrect, please guess again");
}
} while (!correctAnswer);
}// End of add
I'm not quite sure about the exceptions part, but have you maybe though about just using if statements?
Scanner has a method 'hasNextInt' which you can use to check that the the input is na int. For example:
Scanner scan = new Scanner(System.in);
int i=0;
boolean correctAnswer = false;
while(correctAnswer == false){
if(scan.hasNextInt()){
i = scan.nextInt(); correctAnswer = true;
}else{ System.out.println("Invalid entry");
correctAnswer = false;
scan.next();
}
System.out.println(i);
}
Sorry that it doesn't actually directly answer your question, but I though you might want to know about this possible way too. :)
Instead of throw an exception maybe you can use the method hasNextInt() which returns true if the token is a number.
But if you want absolutely use the try catch block, you have to remove the scanner.next() instrsctions because when nothings available on the buffer, it's throws an NoSuchElementException
I think solution i am giving can be improved but this is simple modification to fix your code: (just add new condition variable to check if further input/ans attempts required)
Hope it helps - MAK
public class StackTest {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws InterruptedException{
// Setting up random
Random random = new Random();
// Declaring Integers
int num1;
int num2;
int result;
int input;
input = 0;
// Declaring boolean for userAnswer (Defaulted to false)
boolean correctAnswer = false;
//MAK: Add new condition for checking need of input
boolean needAnswer = true;
do {
// Create two random numbers between 1 and 100
num1 = random.nextInt(100);
num1++;
num2 = random.nextInt(100);
num2++;
// Displaying numbers for user and getting user input for answer
System.out.println("Adding numbers...");
System.out.printf("What is: %d + %d? Please enter answer below",
num1, num2);
result = num1 + num2;
while(needAnswer){
try {
input = scanner.nextInt();
needAnswer = false;
} catch (Exception ex) {
// Print error message
System.out.println("Sorry, invalid number entered for addition");
// flush scanner
scanner.next();
needAnswer = true;
}
} ;
// Line break for code clarity
System.out.println();
// if else statement to determine if answer is correct
if (result == input) {
System.out.println("Well done, you guessed corectly!");
correctAnswer = true;
} else {
System.out.println("Sorry incorrect, please guess again");
needAnswer = true;
}
} while (!correctAnswer);
}
}
If you want to have the following:
1) Ask the user how much is x + y
2) Let the user answer
3) If answer is invalid (e.g. user typed in "www"), let the user type his answer to question 1) again
than you should replace your inner do-while loop with the following:
boolean validInput = true;
do {
try {
input = scanner.nextInt();
} catch (Exception ex) {
// Print error message
System.out.println("Sorry, invalid number entered for addition. Please enter your answer again.");
// flush scanner
scanner.next();
validInput = false;
}
} while (!validInput);

Categories

Resources