> VB.NET Check if a string contains symbols.?

VB.NET Check if a string contains symbols.?

Posted at: 2014-12-18 
Imports System

Public Class Program

Public Shared Sub Main

Dim num2 As Integer

num2 = ReadInput( "Please Enter A Year Below")

Dim _message As String = String.Format("{0} is not a leap year.", num2)

If (IsLeapYear(num2)) Then

_message = String.Format("{0} is a leap year.", num2)

End If

Console.WriteLine(_message)

End Sub



Private Shared Function ReadInput(ByVal _message As String) As Integer

Dim _result As Integer = 0

Do

Console.WriteLine(_message)

Try

_result = CInt(Console.ReadLine)

Exit Do

Catch

Console.WriteLine("Invalid year entered.")

End Try

Loop

Return _result

End Function

Private Shared Function IsLeapYear(ByVal value As Integer) As Boolean

If value Mod 400 = 0 Then

Return True

ElseIf value Mod 100 = 0 Then

Return False

ElseIf value Mod 4 = 0 Then

Return True

End If

Return False

End Function

End Class

The first thing you should do is learn what the rules are for determining if a year is a leap year.

Year mod 4, check for 0 doesn't work. See link.

My homework is to create a program that tells the user if the year they enter is a leap year. But I also need to make it so that the program won't crash if the user enters letters or symbols. I have letters covered but I can't seem to get symbols to not crash it. If you could tell me what I need to put in and where it needs to go that would be great, thanks. Here is my code:

Dim num1 As String

Dim num2 As Integer

'Asks the user to enter a year.

Console.WriteLine("Please Enter A Year Below")

num1 = Console.ReadLine

'Checks if the string contains any letters.

For i = 0 To num1.Length - 1

If Char.IsLetter(num1.Chars(i)) Then

Console.WriteLine("Please only enter numbers!")

num1 = Console.ReadLine

End If

Next

'Checks if the year enter is a leap year or not and displays result.

num2 = num1 Mod 4

Console.Clear()

If num2 = 0 Then

Console.WriteLine("" & num1 & " Is a leap year!")

Else : Console.Clear()

Console.WriteLine("" & num1 & " Is not a leap year!")

End If

Console.ReadLine()