Computer Programming/Conditions/VB.NET

From Wikiversity
Jump to navigation Jump to search

conditions.vb[edit]

' This program asks the user to select Fahrenheit or Celsius conversion
' and input a given temperature. Then the program converts the given 
' temperature and displays the result.
'
' References:
'     https://www.mathsisfun.com/temperature-conversion.html
'     https://en.wikibooks.org/wiki/Visual_Basic_.NET

Imports System

Public Module MyProgram
    Sub Main
        IfElse()
        SelectCase()
    End Sub

    Private Sub IfElse()
        Dim Choice As String
        
        Console.WriteLine("Enter F to convert to Fahrenheit or C to convert to Celsius:")
        Choice = Console.ReadLine()
        If Choice = "C" Or Choice = "c" Then
            ToCelsius()
        ElseIf Choice = "F" Or Choice = "f" Then
            ToFahrenheit()
        Else
            Console.WriteLine("You must enter C to convert to Celsius or F to convert to Fahrenheit!")
        End If
    End Sub
    
    Private Sub SelectCase()
        Dim Choice As String
        
        Console.WriteLine("Enter F to convert to Fahrenheit or C to convert to Celsius:")
        Choice = Console.ReadLine()
        Select Choice
            Case "C", "c"
                ToCelsius()
            Case "F", "f"
                ToFahrenheit()
            Case Else
                Console.WriteLine("You must enter C to convert to Celsius or F to convert to Fahrenheit!")
        End Select
    End Sub

    Private Sub ToCelsius()
        Dim F As Double
        Dim C As Double
        
        Console.WriteLine("Enter Fahrenheit temperature:")
        F = Convert.ToDouble(Console.ReadLine())
        C = (F - 32) * 5 / 9
        Console.WriteLine(F & "° Fahrenheit is " & C & "° Celsius")
    End Sub

    Private Sub ToFahrenheit()
        Dim C As Double
        Dim F As Double
        
        Console.WriteLine("Enter Celsius temperature:")
        C = Convert.ToDouble(Console.ReadLine())
        F = C * 9 / 5 + 32
        Console.WriteLine(C & "° Celsius is " & F & "° Fahrenheit")
    End Sub
End Module

Try It[edit]

Copy and paste the code above into one of the following free online development environments or use your own VB.NET compiler / interpreter / IDE.

See Also[edit]