I am wondering how to do it in a way so that the user can both opt out of entering integers, and so that if the user does not enter an integer, it will catch it and re-prompt th
Start by breaking you're requirements down.
First, you need to be able to read both text and int
values from the user. You need to be able to do this because you need to check for the "exit" condition. So, instead of using Scanner#nextInt
, you should probably be using Scanner#nextLine
instead.
String input = scan.nextLine();
Next, you need to check the input from the user to see if it's meets the "exit" condition or not. If it doesn't, you need to try and convert the input to an int
value and process any conversion issues which might occur
Integer value = null;
//...
if (escape.equalsIgnoreCase(input)) {
exit = true;
} else {
try {
value = Integer.parseInt(input);
} catch (NumberFormatException exp) {
System.out.println("!! " + input + " is not a valid int value");
}
}
Okay, once you have this working okay, you need to wrap it in side of a loop, now, because we HAVE to loop at least once, a do-while
would be suitable (checking the exit condition of the loop at the end of the loop instead of the start)
Integer value = null;
boolean exit = false;
do {
System.out.print(prompt);
String input = scanner.nextLine();
if (escape.equalsIgnoreCase(input)) {
exit = true;
} else {
try {
value = Integer.parseInt(input);
} catch (NumberFormatException exp) {
System.out.println("!! " + input + " is not a valid int value");
}
}
} while (value == null && !exit);
So, when the loop exists, either value
will be a valid integer or null
. You might be thinking why this is important. null
lets us know that their are no more valid values from the user, otherwise you would need to have come up with a int
exit value, but what happens if the user chooses to use that value as their input?
Okay, now, we need to ask the user to do this a lot of times, so, this calls for a method!
public Integer promptForInt(String prompt, Scanner scanner, String escape) {
Integer value = null;
boolean exit = false;
do {
System.out.print(prompt);
String input = scanner.nextLine();
if (escape.equalsIgnoreCase(input)) {
exit = true;
} else {
try {
value = Integer.parseInt(input);
} catch (NumberFormatException exp) {
System.out.println("!! " + input + " is not a valid int value");
}
}
} while (value == null && !exit);
return value;
}
Now, you can simply use another loop to call the method as many times as you need to
List values = new ArrayList<>(25);
Integer value = null;
do {
value = promptForInt("Please enter a series of integers. If you wish to stop, enter 'quit'. ", new Scanner(System.in), "quit");
if (value != null) {
values.add(value);
}
} while (value != null);
System.out.println("You have input " + values.size() + " valid integers");