Inspired by a recent thread in the Help forum.
You wish to repeatedly prompt the user for a number, until a valid number is retrieved.
Which of the following do you prefer?
code: | class UtilityClass {
public static int getInt(Scanner input, String prompt) {
int result = 0;
while (true) {
try {
System.out.print(prompt + " ");
result = input.nextInt();
break;
}
catch (InputMismatchException e) {
}
}
return result;
}
public static int getInt(Scanner input, String prompt, String errorMessage) {
int result = 0;
while (true) {
try {
System.out.print(prompt + " ");
result = input.nextInt();
break;
}
catch (InputMismatchException e) {
System.out.println(errorMessage);
}
}
return result;
}
} |
code: | class IntGetter {
private Scanner inputScanner;
private String promptMessage;
private String errorMessage;
private boolean displayPrompt;
public IntGetter(Scanner input, String prompt) {
this.inputScanner = input;
this.promptMessage = prompt;
this.errorMessage = "";
this.displayPrompt = false;
}
public IntGetter(Scanner input, String prompt, String error) {
this.inputScanner = input;
this.promptMessage = prompt;
this.errorMessage = error;
this.displayPrompt = true;
}
public int get() {
int result = 0;
while (true) {
try {
System.out.print(promptMessage + " ");
result = inputScanner.nextInt();
break;
}
catch (InputMismatchException e) {
if (displayPrompt) {
System.out.println(errorMessage);
}
}
}
return result;
}
} |
The latter should probably have accessor methods, but I don't feel like writing that cruft, so imagine them. |