Function GetInt Learn programming Java

Lesson:

Functions


Exercise:

Function GetInt 14


Objetive:

Create a function named "GetInt", which displays on screen the text received as a parameter, asks the user for an integer number, repeats if the number is not between the minimum value and the maximum value which are indicated as parameters, and finally returns the entered number:

age = GetInt("Enter your age", 0, 150);

would become:

Enter your age: 180
Not a valid answer. Must be no more than 150.
Enter your age: -2
Not a valid answer. Must be no less than 0.
Enter your age: 20

(the value for the variable "age" would be 20)


Code:

import java.util.*;
public class Main
{
	public static int getInt(String text, int low, int high)
	{
		int answer;
		do
		{
			System.out.print(text);
			answer = Integer.parseInt(new Scanner(System.in).nextLine());
			if ((answer > high))
			{
				System.out.println("Not a valid answer. Must be no more than 150");
			}
			if ((answer < low))
			{
				System.out.println("Not a valid answer. Must be no less than 0");
			}
		} while ((answer < low) || (answer > high));
		return answer;
	}


	public static void main(String[] args)
	{
		int age = getInt("Enter your age:  ", 0, 150);
		System.out.printf("The age is %1$s" + "\r\n", age);
	}
}