Skip to content

Instantly share code, notes, and snippets.

@RustyKnight
Created November 8, 2021 01:39
Show Gist options
  • Save RustyKnight/150cd82fb8e093dda66dbbb6922aea44 to your computer and use it in GitHub Desktop.
Save RustyKnight/150cd82fb8e093dda66dbbb6922aea44 to your computer and use it in GitHub Desktop.
Java Scanner prompt helper
import java.util.Scanner;
/*
I see to often people using Scanner to get user input and just, plainly, screwing it.
People don't seem to realise that they can use multiple Scanners to make life easier
for themselves, for example, the primary Scanner can just be used to get the next line
of text input by the user, then a secondary Scanner can be used to parse the input
based on their needs. The following is a simple example to prompt the user for a int
value, with a optional exit value and error message
*/
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
Scanner scanner = new Scanner(System.in);
ScannerHelper.getInt(scanner, "Please enter a interger value or [q] to quite: ", "I didn't think it was that hard", "q");
}
public class ScannerHelper {
public static String prompt(Scanner scanner, String prompt, String acceptableExitValue) {
System.out.println(prompt);
String nextLine = scanner.nextLine();
if (nextLine.equalsIgnoreCase(acceptableExitValue)) {
return null;
}
return nextLine;
}
public static Integer getInt(Scanner scanner, String prompt, String errorPrompt, String acceptableExitValue) {
Integer value = null;
do {
String text = prompt(scanner, prompt, acceptableExitValue);
if (text == null) {
return null;
}
Scanner parser = new Scanner(text);
if (!parser.hasNextInt()) {
System.out.println(errorPrompt);
} else {
value = parser.nextInt();
}
} while (value == null);
return value;
}
}
}
@RustyKnight
Copy link
Author

Obviously you could simply this and not pass in the prompt/error message or instead use a interface to define callbacks to handle extended validation (for example, when prompting for range), the point is, you don't need to rely on a single Scanner and you can wrap a lot of the "common" functionality up to remove repeated boiler plate

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment