Block of Code

Practical Examples for Programmers

  • Home
  • C++
  • Java
  • Visual Basic
  • Discrete Math
  • Ask a Question

Unit Conversions

The table below contains some lengths in terms of feet.

1 inch = .0833 foot 1 rod = 16.5 feet
 1 yard = 3 feet 1 furlong = 660 feet
1 meter = 3.28155 feet  1 kilometer = 3281.5 feet
 1 fathom = 6 feet  1 mile = 5280 feet

Write a program that displays the nine different units of measure; requests the unit to convert from, the unit to convert to, and the quantity to be converted; and then displays the converted quantity.  A typical outcome is shown in the figure below.

Unit Conversion

Suggested Control Names and Attributes:

Name Property Text Property Control Type Notes
 frmConvert Conversion Form Holds Controls
 lstUnits ListBox Displays line number and associated unit of measurement from units.txt
 txtLength TextBox Captures desired length to convert
 mtbFrom MaskedTextBox Captures original units (1-9)
 mtbTo MaskedTextBox Captures desired units (1-9)
 btnConvert Convert Button Triggers event to compute and display desired length
txtOutput Text Box Display desired length.  ReadOnly property should be set to true.

Hints:

  • Create a text file named units.txt using Notepad which contains the following text

Unit Conversion Screenshot 3

  • Place the text file in the bin/Debug folder of your visual basic solution.
  • Use the ReadAllLines method to populate an array with each line of the text file.  Then use the Split method to separate the name from the value.
  • The lengths must be converted to their equivalent in feet first, and then converted to their final unit of length.

Write the Code:


' Project: Unit Conversion
' Description:  This is a program to convert measurement units.  The user enters the 
' unit to convert from, the unit to convert to, and the quantity of units to be converted.  
' The program then performs calculations and displays the converted quantity.

Public Class frmUnitConversion
    ' declare global variables
    Dim units() As String = IO.File.ReadAllLines("Units.txt")
    Dim conversionRates(10) As Double
    Dim query() As String
    Dim counter As Integer = -1
    Dim length As Double = 0
    Dim fromUnit As Integer = 0
    Dim toUnit As Integer = 0
    Dim desiredUnits As Double
    Dim valid As Boolean = True ' variable for input validation

    Private Sub frmUnitConversion_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ' loads info from text file into array
        Dim query = From line In units
                                Let data = line.Split(","c)
                                Let unitName = data(0)
                                Let conversionRate = data(1)
                                Select unitName, conversionRate
        For Each unit In query
            ' displays each item in the list box
            counter += 1
            lstUnits.Items.Add(CStr(counter + 1) & ". " & unit.unitName)
        Next
        counter = 0
        For Each unit In query
            ' assigns conversion rates to an array
            conversionRates(counter) = CDbl(unit.conversionRate)
            counter += 1
        Next
    End Sub

    Private Sub btnConvert_Click(sender As Object, e As EventArgs) Handles btnConvert.Click
        ' get input
        txtOutput.Clear()
        InputData()
        ' validate input values are within the correct range
        If length < 0 Or fromUnit < 1 Or fromUnit > 9 Or toUnit < 1 Or toUnit > 9 Then
            valid = False
            MessageBox.Show("Length must be positive and units must be between 1 and 9", "Error")
        End If
        ' complete calculations
        If valid = True Then
            ConvertUnits()
            txtOutput.Text = ((desiredUnits).ToString("N2"))
        End If
    End Sub

    Sub InputData()
        ' Gets input from user and assigns to variables
        valid = True ' Initialize to true in case of prior invalid input
        Try
            length = CDbl(txtLength.Text)
            fromUnit = CInt(mtbFrom.Text)
            toUnit = CInt(mtbTo.Text)
        Catch ex As Exception
            MessageBox.Show("Either an entry is blank or the input is not valid", "Error")
            valid = False
        End Try
    End Sub

    Sub ConvertUnits()
        desiredUnits = conversionRates(fromUnit - 1) / conversionRates(toUnit - 1) * length
    End Sub
End Class

Secondary Sidebar

This is the secondary sidebar

Copyright © 2023 · Metro Pro Theme on Genesis Framework · WordPress · Log in