I'm just starting out with Java, and trying to make a method to get a positive integer input from the console. My currently working implementation is this:
public static Scanner sc = new Scanner(System.in);
public static int getPositiveIntInput(String message) {
int n;
String error_message = "Error: input must be a positive integer.";
System.out.print(message);
while (true) { // This is often frowned upon?
// Check that input is integer
while (!sc.hasNextInt()) {
System.out.print(error_message + "\n" + message); // Gets repeated
sc.next();
}
n = sc.nextInt();
sc.nextLine();
// Check that input is positive
if (n > 0) {
return n;
} else {
System.out.print(error_message + "\n" + message);
}
}
}
In order to make my code more readable and concise, I attempted to rid myself of the while (true)
and several error message prints by combining the integer and positivity checks into one loop, but I'm not getting the behaviour I would expect:
public static int getPositiveIntInput(String message) { String error_message = "Error: input must be a positive integer."; System.out.print(message); // Check that input is integer and positive while (!sc.hasNextInt() || sc.nextInt() <= 0) { System.out.print(error_message + "\n" + message); sc.next(); } int n = sc.nextInt(); sc.nextLine(); return n; }
What would be an effective way of improving the readability and reducing repetition while achieving the same functionality as in my original implementation? Particularly regarding the while(true)
loop - I've seen it's use being discouraged in other SO threads. Would this be a case where a different looping structure could/should be considered?