Function calculator, params and return value of Main Learn programming Visual Basic (VB.net)

Lesson:

Functions


Exercise:

Function calculator, params and return value of Main


Objetive:

Create a Visual Basic (VB.net) program to calculate a sum, subtraction, product or division, analyzing the command line parameters:

calc 5 + 379

(Parameters must be a number, a sign, and another number; allowed signs are + - * x / )

This version must return the following error codes:
1 if the number of parameters is not 3
2 if the second parameter is not an accepted sign
3 if the first or third parameter is not a valid number
0 otherwise


Code:

Imports System
Public Class exercise126
    Public Shared Function Main(ByVal args As String()) As Integer
        If args.Length <> 3 Then
            Console.WriteLine("Error!")
            Console.WriteLine("Usage: number1 operand number2")
            Console.WriteLine("Where operand can be + - / * x ·")
            Return 1
        End If

        Try
            Dim number1 As Integer = Convert.ToInt32(args(0))
            Dim number2 As Integer = Convert.ToInt32(args(2))

            Select Case args(1)
                Case "+"
                    Console.WriteLine(number1 + number2)
                    Exit Select
                Case "-"
                    Console.WriteLine(number1 - number2)
                    Exit Select
                Case "/"
                    Console.WriteLine(number1 / number2)
                    Exit Select
                Case "*", "x", "·"
                    Console.WriteLine(number1 * number2)
                    Exit Select
                Case Else
                    Console.WriteLine("Error!")
                    Console.WriteLine("Operand must be + - / * x or ·")
                    Return 2
                    Exit Select
            End Select

        Catch __unusedException1__ As Exception
            Console.WriteLine("Error!")
            Console.WriteLine("Not a valid number")
            Return 3
        End Try

        Return 0
    End Function
End Class

Juan A. Ripoll - Systems Tutorials and Programming Courses ©  All rights reserved.  Legal Conditions.