import java.util.Scanner;
public class PromptInRange
{
public static int promptIntInRange( String prompt, int min, int max, String minError,
String maxError )
{
Scanner user_input = new Scanner(System.in);
int number;
do
{
if (min == Integer.MIN_VALUE && max == Integer.MAX_VALUE)
{
System.out.print(prompt + ": ");
}
else if (min == Integer.MIN_VALUE)
{
System.out.print(prompt + " (less than " + max + "): ");
}
else if (max == Integer.MAX_VALUE)
{
System.out.print(prompt + " (greater than " + min + "): ");
}
else
{
System.out.print(prompt + " (between " + min + " and " + max + "): ");
}
try {
number = Integer.parseInt(user_input.next());
if (number < min)
{
System.out.print(minError + " ");
}
else if (number > max)
{
System.out.print(maxError + " ");
}
} catch (NumberFormatException e) {
number = min - 1;
System.out.print("Input wasn't an integer. ");
}
} while (number < min || number > max);
return number;
}
public static int promptIntInRange( int min, int max, String minError, String maxError )
{
return promptIntInRange("Please enter an integer", min, max, minError, maxError);
}
public static int promptIntInRange( int min, int max, String error )
{
return promptIntInRange(min, max, error, error);
}
public static int promptIntInRange( int min, int max )
{
return promptIntInRange(min, max, "That's out of range.");
}
public static int promptWholeNumber( String error )
{
return promptIntInRange(0, Integer.MAX_VALUE, error);
}
public static int promptWholeNumber()
{
return promptWholeNumber("That's a negative number.");
}
}
Comments