Share
Explore BrainMass

Java method readInt

Provide a Java class named "Input" containing the method "readInt" (prototype given below) that displays the prompt string, reads an integer, and tests whether it is between the supplied minimum and maximum. If not, it prints an error message and repeats the entire process.

public static int readInt(Scanner in, String prompt, String error, int min, int max)

Use the following class as the main class for testing the implementation.

import java.util.Scanner;

/**
This program prints how old you'll be next year.
*/
public class AgePrinter
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int age = Input.readInt(in, "Please enter your age",
"Illegal Input--try again", 1, 150);
System.out.println("Next year, you'll be " + (age + 1));
}
}

Solution Preview

Please rename the attached 470518-AgePrinter.java to AgePrinter.java before compiling and executing it.

A sample session with given program looks like following.

$ java AgePrinter
Please enter your age
200
Illegal Input--try again
Please enter your age
-1
Illegal Input--try again
Please enter your age
99
Next year, you'll be ...

Solution Summary

Provided code has been tested with command line version of Java binaries from Java SDK v1.7.0_u3 .

$2.19