Exercise
Function GetInt
Objetive
Write a Visual Basic (VB.Net) 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
Imports System
Public Class exercise116
Public Shared Function getInt(ByVal text As String, ByVal low As Integer, ByVal high As Integer) As Integer
Dim answer As Integer
Do
Console.Write(text)
answer = Convert.ToInt32(Console.ReadLine())
If (answer > high) Then Console.WriteLine("Not a valid answer. Must be no more than 150")
If (answer < low) Then Console.WriteLine("Not a valid answer. Must be no less than 0")
Loop While (answer < low) OrElse (answer > high)
Return answer
End Function
Private Shared Sub Main()
Dim age As Integer = getInt("Enter your age: ", 0, 150)
Console.WriteLine("The age is {0}", age)
End Sub
End Class