Just want to know if there was any better way of doing this since it’s a lot of writing.
JavaScript
x
boolean isInputValid = false;
do {
System.out.print("Input: ");
final String input = sc.nextLine();
try {
age = Integer.parseInt(input);
} catch (NumberFormatException e) {
System.out.println("Invalid input. Try again");
continue;
}
if (input < 0 || 10 < input) {
System.out.println("Number outside of range.");
} else {
isInputValid = true;
}
} while (!isInputValid);
Advertisement
Answer
Well there are some things that can be ommited on a first look, but there is not much to remove.
- Reduced integer parsing in a single line and removed
input
variable. - Change
isInputValid
to its negationisInputInvalid
to remove else , Boolean assignment and negation in thewhile
clause. - Moved
if
into thetry
clause to make redundant and remove thecontinue
statement.
JavaScript
boolean isInputInvalid = true;
do {
System.out.print("Input: ");
try {
age = Integer.parseInt( sc.nextLine());
isInputInvalid = input < 0 || 10 < input;
if (isInputInvalid) {
System.out.println("Number outside of range.");
}
} catch (NumberFormatException e) {
System.out.println("Invalid input. Try again");
}
} while (isInputInvalid);