SlideShare a Scribd company logo
1C:UsersMichelleDocumentsVisual Studio 2013... Cost CalculatorUtility Cost CalculatorAppCalc.vb
' Michelle John
' May 11, 2015
' POS 408
' Dr. Bill Spees
Imports System.IO
Public Class AppCalc
Dim strApplianceArray(1) As String
Dim dblDefaultValueArray(1) As Double
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
ResetTheForm()
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
' Close the form
Me.Close()
End Sub
Private Sub txtCostKWh_Leave(sender As Object, e As EventArgs) Handles txtCostKWh.Leave
' Values determined by current prices of electricity at
' http://www.eia.gov/electricity/monthly/epm_table_grapher.cfm?t=epmt_5_6_a
' Cost in Hawaii is the highest at $0.3334 as of this date.
' Cost in Washington is the lowest at $0.0813 as of this date.
Const dblMIN_COST_PER_KWH = 0.05
Const dblMAX_COST_PER_KWH = 0.35
ResetErrorMessage()
' Checks if the value is in range and if not puts cursor back in the text box
If Not InRange(txtCostKWh.Text, dblMIN_COST_PER_KWH, dblMAX_COST_PER_KWH) Then
txtCostKWh.Focus()
End If
End Sub
Private Sub txtPower_Leave(sender As Object, e As EventArgs) Handles txtPower.Leave
ResetErrorMessage()
' Ranges determined by the values found on this site:
' http://www.daftlogic.com/information-appliance-power-consumption.htm
' Ranges for appliances not on that site extrapolated from values given in classroom
' texts.
Select Case cbxApplianceList.Text
' REFRIGERATOR-----------------------------------------------------------------
Case "Refrigerator"
Const dblMIN_POWER = 0.1
Const dblMAX_POWER = 0.5
' Checks if the value is in range and if not puts cursor back in the text box
If Not InRange(txtPower.Text, dblMIN_POWER, dblMAX_POWER) Then
txtPower.Focus()
2C:UsersMichelleDocumentsVisual Studio 2013... Cost CalculatorUtility Cost CalculatorAppCalc.vb
End If
' HAIR DRYER---------------------------------------------------------------
Case "Hair Dryer"
Const dblMIN_POWER = 1.0
Const dblMAX_POWER = 1.5
' Checks if the value is in range and if not puts cursor back in the text box
If Not InRange(txtPower.Text, dblMIN_POWER, dblMAX_POWER) Then
txtPower.Focus()
End If
' DEEP FREEZE-------------------------------------------------------------
Case "Deep Freeze"
Const dblMIN_POWER = 0.1
Const dblMAX_POWER = 0.25
' Checks if the value is in range and if not puts cursor back in the text box
If Not InRange(txtPower.Text, dblMIN_POWER, dblMAX_POWER) Then
txtPower.Focus()
End If
' MICROWAVE----------------------------------------------------------------
Case "Microwave"
Const dblMIN_POWER = 0.5
Const dblMAX_POWER = 1.5
' Checks if the value is in range and if not puts cursor back in the text box
If Not InRange(txtPower.Text, dblMIN_POWER, dblMAX_POWER) Then
txtPower.Focus()
End If
' COMPUTER------------------------------------------------------------------
Case "Computer"
Const dblMIN_POWER = 0.04
Const dblMAX_POWER = 0.2
' Checks if the value is in range and if not puts cursor back in the text box
If Not InRange(txtPower.Text, dblMIN_POWER, dblMAX_POWER) Then
txtPower.Focus()
End If
' FAN---------------------------------------------------------------------
Case "Fan"
Const dblMIN_POWER = 0.005
Const dblMAX_POWER = 0.03
' Checks if the value is in range and if not puts cursor back in the text box
If Not InRange(txtPower.Text, dblMIN_POWER, dblMAX_POWER) Then
txtPower.Focus()
End If
3C:UsersMichelleDocumentsVisual Studio 2013... Cost CalculatorUtility Cost CalculatorAppCalc.vb
' WASHER-------------------------------------------------------------------
Case "Washer"
Const dblMIN_POWER = 0.4
Const dblMAX_POWER = 0.6
' Checks if the value is in range and if not puts cursor back in the text box
If Not InRange(txtPower.Text, dblMIN_POWER, dblMAX_POWER) Then
txtPower.Focus()
End If
' ELSE---------------------------------------------------------------------
Case Else
' Unique error message
lblResults.ForeColor = Color.Red
lblResults.BackColor = Color.White
lblResults.Text = "Please select an appliance from the pull down list."
End Select
End Sub
Private Sub txtHoursPerDay_Leave(sender As Object, e As EventArgs) _
Handles txtHoursPerDay.Leave
ResetErrorMessage()
Const dblMIN_HOURS = 0.0
Const dblMAX_HOURS = 24.0
' Checks if the value is in range and if not puts cursor back in the text box
If Not InRange(txtHoursPerDay.Text, dblMIN_HOURS, dblMAX_HOURS) Then
txtHoursPerDay.Focus()
End If
End Sub
Private Function InRange(ByVal strInputString As String,
ByVal dblMinValue As Double,
ByVal dblMaxValue As Double) As Boolean
' Tests entered values to determine if they fall within the proper range.
' Returns True if the value is within range, False if the value is not within range.
Dim dblEnteredValue As Double
If Double.TryParse(strInputString, dblEnteredValue) Then
If (dblEnteredValue < dblMinValue) Or (dblEnteredValue > dblMaxValue) Then
ShowErrorMessage(dblMinValue, dblMaxValue)
Return False
Else
Return True
End If
Else
4C:UsersMichelleDocumentsVisual Studio 2013... Cost CalculatorUtility Cost CalculatorAppCalc.vb
ShowErrorMessage(dblMinValue, dblMaxValue)
Return False
End If
End Function
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
Dim dblCost As Double ' Used to make it easier to read the code
Dim ApplianceOutputList As ListViewItem
Dim blnFound As Boolean = False
Dim intCounter As Integer = 0
' Checks to make sure all values are numeric to prevent calculation errors
If IsNumeric(txtCostKWh.Text) And _
IsNumeric(txtPower.Text) And _
IsNumeric(txtHoursPerDay.Text) And _
IsNumeric(txtCostPerGallon.Text) And _
IsNumeric(txtGallonsPerHour.Text) Then
dblCost = CalculateTotalCostPerDay(CDbl(txtCostKWh.Text), _
CDbl(txtPower.Text), _
CDbl(txtHoursPerDay.Text), _
CDbl(txtCostPerGallon.Text), _
CDbl(txtGallonsPerHour.Text))
' Updates the list with the values entered by the user
lstApplianceOutputList.BeginUpdate()
ApplianceOutputList = lstApplianceOutputList.Items.Add(cbxApplianceList.Text)
ApplianceOutputList.SubItems.Add(txtHoursPerDay.Text)
ApplianceOutputList.SubItems.Add(dblCost.ToString("c"))
lstApplianceOutputList.Update()
lstApplianceOutputList.EndUpdate()
RunningTotal()
Else
lblResults.ForeColor = Color.Red
lblResults.BackColor = Color.White
lblResults.Text = "Please make sure all values you have entered are numeric."
End If
' Resets the form to get ready for the next set of inputs
cbxApplianceList.Text = "Refrigerator"
txtHoursPerDay.Text = String.Empty
ResetWasherInfo()
gbxAppList.Focus()
' Finds the default value for "Refrigerator" and populates the txtPower field with the
' appropriate value
While Not blnFound
If strApplianceArray(intCounter) = "Refrigerator" Then
txtPower.Text = dblDefaultValueArray(intCounter).ToString
blnFound = True
End If
intCounter += 1
End While
5C:UsersMichelleDocumentsVisual Studio 2013... Cost CalculatorUtility Cost CalculatorAppCalc.vb
End Sub
Private Sub RunningTotal()
' Adds the values in the Cost Per Day column
Dim dblRunningTotal As Double = 0.0
For i As Integer = 0 To (lstApplianceOutputList.Items.Count() - 1)
' Gets the values held within the Cost Per Day column and adds them
dblRunningTotal += CDbl(lstApplianceOutputList.Items(i).SubItems.Item(2).Text)
Next
' Updates lblTotalCost
lblTotalCost.Text = dblRunningTotal.ToString("c")
End Sub
Private Sub ShowErrorMessage(ByVal dblMinValue As Double, _
ByVal dblMaxValue As Double)
' Error message
lblResults.ForeColor = Color.Red
lblResults.BackColor = Color.White
lblResults.Text = "Please enter a numeric value greater than " & dblMinValue.ToString &
" and less than " & dblMaxValue.ToString & "."
End Sub
Private Sub ResetErrorMessage()
' Resets the colors back to default
lblResults.ForeColor = SystemColors.ControlText
lblResults.BackColor = SystemColors.Control
lblResults.Text = String.Empty
End Sub
Private Function CalculateTotalCostPerDay(ByVal dblCost As Double, _
ByVal dblPower As Double, _
ByVal dblHours As Double, _
ByVal dblGalCost As Double, _
ByVal dblGalHour As Double) As Double
' Total cost per day calculated as Cost per kWH * Power used per hour * hours used.
' When no water is used the value in the right side of the expression will always be zero.
Return (dblCost * dblPower * dblHours) + (dblGalCost * dblGalHour * dblHours)
End Function
Private Sub ResetTheForm()
Dim blnFound As Boolean = False
Dim intCounter As Integer = 0
' Reset the form
cbxApplianceList.Text = "Refrigerator"
txtCostKWh.Text = String.Empty
txtHoursPerDay.Text = String.Empty
ResetWasherInfo()
lblResults.Text = String.Empty
lblTotalCost.Text = "0.00"
lstApplianceOutputList.Items.Clear()
gbxAppList.Focus()
6C:UsersMichelleDocumentsVisual Studio 2013... Cost CalculatorUtility Cost CalculatorAppCalc.vb
' Finds the default value for "Refrigerator" and populates the txtPower field
' with the appropriate value
While Not blnFound
If strApplianceArray(intCounter) = "Refrigerator" Then
txtPower.Text = dblDefaultValueArray(intCounter).ToString
blnFound = True
End If
intCounter += 1
End While
End Sub
Private Sub ResetWasherInfo()
' Resets the labels and text boxes related to the choice of "Washer"
lblGallonCostLabel.Visible = False
lblGallonsUsedLabel.Visible = False
lblDollarSign2.Visible = False
lblGalPerHour.Visible = False
txtCostPerGallon.Visible = False
txtCostPerGallon.Text = "0.00"
txtGallonsPerHour.Visible = False
txtGallonsPerHour.Text = "0.0"
End Sub
Private Sub cbxApplianceList_SelectedValueChanged(sender As Object, e As EventArgs) _
Handles cbxApplianceList.SelectedValueChanged
Dim blnFound As Boolean = False
Dim intCounter As Integer = 0
' Looks through the array strApplianceArray, finds the appliance,
' and sets a default value to txtPower.text
While Not blnFound
If strApplianceArray(intCounter) = cbxApplianceList.Text Then
txtPower.Text = dblDefaultValueArray(intCounter).ToString
blnFound = True
End If
intCounter += 1
End While
' Shows fields related to the choice of "Washer"
If cbxApplianceList.Text = "Washer" Then
lblGallonCostLabel.Visible = True
lblGallonsUsedLabel.Visible = True
lblDollarSign2.Visible = True
lblGalPerHour.Visible = True
txtCostPerGallon.Visible = True
txtGallonsPerHour.Visible = True
Else
ResetWasherInfo()
7C:UsersMichelleDocumentsVisual Studio 2013... Cost CalculatorUtility Cost CalculatorAppCalc.vb
End If
End Sub
Private Sub txtCostPerGallon_Leave(sender As Object, e As EventArgs) _
Handles txtCostPerGallon.Leave
' Costs constant values based on cost of author's water.
Const dblMIN_COST = 0.01
Const dblMAX_COST = 0.15
ResetErrorMessage()
InRange(txtCostPerGallon.Text, dblMIN_COST, dblMAX_COST)
End Sub
Private Sub txtGallonsPerHour_Leave(sender As Object, e As EventArgs) _
Handles txtGallonsPerHour.Leave
' Gallons of water used based on values found at
' http://www.home-water-works.org/indoor-use/clothes-washer
Const dblMIN_GALLONS_USED = 12
Const dblMAX_GALLONS_USED = 45
ResetErrorMessage()
InRange(txtGallonsPerHour.Text, dblMIN_GALLONS_USED, dblMAX_GALLONS_USED)
End Sub
Private Sub AppCalc_Load(sender As Object, e As EventArgs) _
Handles MyBase.Load
' Fills an array of appliance names and a parallel array of default
' values from an external file
Dim fileReader As StreamReader
Dim intArrayElement As Integer
intArrayElement = 0
fileReader = File.OpenText("DefaultValues.txt")
' Counts the number of elements needed in the parallel arrays
While Not fileReader.EndOfStream
fileReader.ReadLine()
fileReader.ReadLine()
intArrayElement += 1
End While
fileReader.Close()
' Resizes arrays based on the number of records in the data file
ReDim strApplianceArray(intArrayElement - 1)
ReDim dblDefaultValueArray(intArrayElement - 1)
fileReader = File.OpenText("DefaultValues.txt")
For i As Integer = 0 To (intArrayElement - 1)
strApplianceArray(i) = fileReader.ReadLine()
dblDefaultValueArray(i) = CDbl(fileReader.ReadLine())
8C:UsersMichelleDocumentsVisual Studio 2013... Cost CalculatorUtility Cost CalculatorAppCalc.vb
Next
fileReader.Close()
End Sub
Private Sub btnExport_Click(sender As Object, e As EventArgs) _
Handles btnExport.Click
' Exports the data in the lstApplianceOutputList and the total
' cost into a txt file
Dim fileWriter As StreamWriter
Dim strTemp As String 'Used to format the output
Dim strTempApp As String 'Used to format the output
Dim strTempHours As String 'Used to format the output
Dim strTempCost As String 'Used to format the output
fileWriter = File.AppendText("ExportFile.txt")
' Writes a header to the text file
fileWriter.WriteLine(String.Format("{0, 15} {1, 15} {2, 15}", _
"Appliance", "Hours Used", "Cost per Day"))
' Runs through lstApplianceOutputList, reads the values into the temp variables,
' formats the results, and then writes the formated results into the text file
For i As Integer = 0 To (lstApplianceOutputList.Items.Count - 1)
strTempApp = lstApplianceOutputList.Items(i).Text
strTempHours = lstApplianceOutputList.Items(i).SubItems(1).Text
strTempCost = lstApplianceOutputList.Items(i).SubItems(2).Text
strTemp = String.Format("{0, -15} {1, 15} {2, 15}", _
strTempApp, strTempHours, strTempCost)
fileWriter.WriteLine(strTemp)
Next
' Adds the total cost to the text file
fileWriter.WriteLine("-----------------")
fileWriter.WriteLine("Total Cost")
fileWriter.WriteLine(lblTotalCost.Text)
fileWriter.WriteLine()
fileWriter.Close()
' Let's the user know something happened when the button was clicked
lblResults.Text = "File has been exported to ExportFile.txt."
End Sub
End Class

More Related Content

What's hot

Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Jonas Bonér
 
Chaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscoreChaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscoreNicolas Carlo
 
Michael Colon Portfolio
Michael Colon PortfolioMichael Colon Portfolio
Michael Colon Portfoliomichael_colon
 
Let's make a contract: The art of designing a Java API | DevNation Tech Talk
Let's make a contract: The art of designing a Java API | DevNation Tech TalkLet's make a contract: The art of designing a Java API | DevNation Tech Talk
Let's make a contract: The art of designing a Java API | DevNation Tech TalkRed Hat Developers
 
AngularJS CheatSheet
AngularJS CheatSheetAngularJS CheatSheet
AngularJS CheatSheetAbdul Basit
 
Event sourcing in the functional world (22 07-2021)
Event sourcing in the functional world (22 07-2021)Event sourcing in the functional world (22 07-2021)
Event sourcing in the functional world (22 07-2021)Vitaly Brusentsev
 
Kotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRreadyKotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRreadyMobileAcademy
 
Presenting things in Swift
Presenting things in SwiftPresenting things in Swift
Presenting things in SwiftDenis Fileev
 
C# Starter L06-Delegates, Event Handling and Extension Methods
C# Starter L06-Delegates, Event Handling and Extension MethodsC# Starter L06-Delegates, Event Handling and Extension Methods
C# Starter L06-Delegates, Event Handling and Extension MethodsMohammad Shaker
 
Dependency Injection in Drupal 8
Dependency Injection in Drupal 8Dependency Injection in Drupal 8
Dependency Injection in Drupal 8katbailey
 
Does your code spark joy? Refactoring techniques to make your life easier.
Does your code spark joy? Refactoring techniques to make your life easier.Does your code spark joy? Refactoring techniques to make your life easier.
Does your code spark joy? Refactoring techniques to make your life easier.Juciellen Cabrera
 
JavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashJavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashBret Little
 

What's hot (19)

Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
Chaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscoreChaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscore
 
Docimp
DocimpDocimp
Docimp
 
Hadoop + Clojure
Hadoop + ClojureHadoop + Clojure
Hadoop + Clojure
 
Michael Colon Portfolio
Michael Colon PortfolioMichael Colon Portfolio
Michael Colon Portfolio
 
Let's make a contract: The art of designing a Java API | DevNation Tech Talk
Let's make a contract: The art of designing a Java API | DevNation Tech TalkLet's make a contract: The art of designing a Java API | DevNation Tech Talk
Let's make a contract: The art of designing a Java API | DevNation Tech Talk
 
Vb.net iii
Vb.net iiiVb.net iii
Vb.net iii
 
Lodash js
Lodash jsLodash js
Lodash js
 
AngularJS CheatSheet
AngularJS CheatSheetAngularJS CheatSheet
AngularJS CheatSheet
 
Event sourcing in the functional world (22 07-2021)
Event sourcing in the functional world (22 07-2021)Event sourcing in the functional world (22 07-2021)
Event sourcing in the functional world (22 07-2021)
 
Kotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRreadyKotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRready
 
Presenting things in Swift
Presenting things in SwiftPresenting things in Swift
Presenting things in Swift
 
Vb.net iv
Vb.net ivVb.net iv
Vb.net iv
 
C# Starter L06-Delegates, Event Handling and Extension Methods
C# Starter L06-Delegates, Event Handling and Extension MethodsC# Starter L06-Delegates, Event Handling and Extension Methods
C# Starter L06-Delegates, Event Handling and Extension Methods
 
Dependency Injection in Drupal 8
Dependency Injection in Drupal 8Dependency Injection in Drupal 8
Dependency Injection in Drupal 8
 
Macaraeg
MacaraegMacaraeg
Macaraeg
 
C++11 Multithreading - Futures
C++11 Multithreading - FuturesC++11 Multithreading - Futures
C++11 Multithreading - Futures
 
Does your code spark joy? Refactoring techniques to make your life easier.
Does your code spark joy? Refactoring techniques to make your life easier.Does your code spark joy? Refactoring techniques to make your life easier.
Does your code spark joy? Refactoring techniques to make your life easier.
 
JavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashJavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and Lodash
 

Similar to UtilityCostCalcCode

Funcitonal Swift Conference: The Functional Way
Funcitonal Swift Conference: The Functional WayFuncitonal Swift Conference: The Functional Way
Funcitonal Swift Conference: The Functional WayNatasha Murashev
 
0853352_Report_Valuing Warrants With VBA
0853352_Report_Valuing Warrants With VBA0853352_Report_Valuing Warrants With VBA
0853352_Report_Valuing Warrants With VBAKartik Malla
 
Unit iii vb_study_materials
Unit iii vb_study_materialsUnit iii vb_study_materials
Unit iii vb_study_materialsgayaramesh
 
Ensure code quality with vs2012
Ensure code quality with vs2012Ensure code quality with vs2012
Ensure code quality with vs2012Sandeep Joshi
 
.Net Enterprise Services and their Implementations
.Net Enterprise Services and their Implementations.Net Enterprise Services and their Implementations
.Net Enterprise Services and their ImplementationsKashif Aleem
 
Help with Starting out with visual basic 7th edition chapter 6 Progr.pdf
Help with Starting out with visual basic 7th edition chapter 6 Progr.pdfHelp with Starting out with visual basic 7th edition chapter 6 Progr.pdf
Help with Starting out with visual basic 7th edition chapter 6 Progr.pdfezycolours78
 
Puerto serialarduino
Puerto serialarduinoPuerto serialarduino
Puerto serialarduinozadkiel_123
 
Theater revenue
Theater revenueTheater revenue
Theater revenueSara Hicks
 
Codes
CodesCodes
CodesOSit3
 
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 1
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 1Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 1
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 1PVS-Studio
 
write the To Dos to get the exact outputNOte A valid Fraction .pdf
write the To Dos to get the exact outputNOte A valid Fraction .pdfwrite the To Dos to get the exact outputNOte A valid Fraction .pdf
write the To Dos to get the exact outputNOte A valid Fraction .pdfjyothimuppasani1
 
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docxPROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docxamrit47
 
Running Head Discussion Board .docx
Running Head Discussion Board                                  .docxRunning Head Discussion Board                                  .docx
Running Head Discussion Board .docxjeanettehully
 
vbscript-reference book
vbscript-reference bookvbscript-reference book
vbscript-reference bookAnand Dhana
 
Kajal Gaharwal , BCA Third Year
Kajal Gaharwal , BCA Third YearKajal Gaharwal , BCA Third Year
Kajal Gaharwal , BCA Third YearDezyneecole
 
Student information system
Student information systemStudent information system
Student information systempatrick7772
 
2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2Warui Maina
 
Updated Visual Basic 6 for beginners.pptx
Updated Visual Basic 6 for beginners.pptxUpdated Visual Basic 6 for beginners.pptx
Updated Visual Basic 6 for beginners.pptxSarveshDeodhar
 

Similar to UtilityCostCalcCode (20)

Funcitonal Swift Conference: The Functional Way
Funcitonal Swift Conference: The Functional WayFuncitonal Swift Conference: The Functional Way
Funcitonal Swift Conference: The Functional Way
 
VB net lab.pdf
VB net lab.pdfVB net lab.pdf
VB net lab.pdf
 
0853352_Report_Valuing Warrants With VBA
0853352_Report_Valuing Warrants With VBA0853352_Report_Valuing Warrants With VBA
0853352_Report_Valuing Warrants With VBA
 
Unit iii vb_study_materials
Unit iii vb_study_materialsUnit iii vb_study_materials
Unit iii vb_study_materials
 
Ensure code quality with vs2012
Ensure code quality with vs2012Ensure code quality with vs2012
Ensure code quality with vs2012
 
.Net Enterprise Services and their Implementations
.Net Enterprise Services and their Implementations.Net Enterprise Services and their Implementations
.Net Enterprise Services and their Implementations
 
Help with Starting out with visual basic 7th edition chapter 6 Progr.pdf
Help with Starting out with visual basic 7th edition chapter 6 Progr.pdfHelp with Starting out with visual basic 7th edition chapter 6 Progr.pdf
Help with Starting out with visual basic 7th edition chapter 6 Progr.pdf
 
Puerto serialarduino
Puerto serialarduinoPuerto serialarduino
Puerto serialarduino
 
Theater revenue
Theater revenueTheater revenue
Theater revenue
 
Codes
CodesCodes
Codes
 
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 1
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 1Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 1
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 1
 
write the To Dos to get the exact outputNOte A valid Fraction .pdf
write the To Dos to get the exact outputNOte A valid Fraction .pdfwrite the To Dos to get the exact outputNOte A valid Fraction .pdf
write the To Dos to get the exact outputNOte A valid Fraction .pdf
 
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docxPROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
 
Running Head Discussion Board .docx
Running Head Discussion Board                                  .docxRunning Head Discussion Board                                  .docx
Running Head Discussion Board .docx
 
vbscript-reference book
vbscript-reference bookvbscript-reference book
vbscript-reference book
 
Kajal Gaharwal , BCA Third Year
Kajal Gaharwal , BCA Third YearKajal Gaharwal , BCA Third Year
Kajal Gaharwal , BCA Third Year
 
IT104 Week 4 - Module/Function
IT104 Week 4 - Module/FunctionIT104 Week 4 - Module/Function
IT104 Week 4 - Module/Function
 
Student information system
Student information systemStudent information system
Student information system
 
2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2
 
Updated Visual Basic 6 for beginners.pptx
Updated Visual Basic 6 for beginners.pptxUpdated Visual Basic 6 for beginners.pptx
Updated Visual Basic 6 for beginners.pptx
 

UtilityCostCalcCode

  • 1. 1C:UsersMichelleDocumentsVisual Studio 2013... Cost CalculatorUtility Cost CalculatorAppCalc.vb ' Michelle John ' May 11, 2015 ' POS 408 ' Dr. Bill Spees Imports System.IO Public Class AppCalc Dim strApplianceArray(1) As String Dim dblDefaultValueArray(1) As Double Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click ResetTheForm() End Sub Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click ' Close the form Me.Close() End Sub Private Sub txtCostKWh_Leave(sender As Object, e As EventArgs) Handles txtCostKWh.Leave ' Values determined by current prices of electricity at ' http://www.eia.gov/electricity/monthly/epm_table_grapher.cfm?t=epmt_5_6_a ' Cost in Hawaii is the highest at $0.3334 as of this date. ' Cost in Washington is the lowest at $0.0813 as of this date. Const dblMIN_COST_PER_KWH = 0.05 Const dblMAX_COST_PER_KWH = 0.35 ResetErrorMessage() ' Checks if the value is in range and if not puts cursor back in the text box If Not InRange(txtCostKWh.Text, dblMIN_COST_PER_KWH, dblMAX_COST_PER_KWH) Then txtCostKWh.Focus() End If End Sub Private Sub txtPower_Leave(sender As Object, e As EventArgs) Handles txtPower.Leave ResetErrorMessage() ' Ranges determined by the values found on this site: ' http://www.daftlogic.com/information-appliance-power-consumption.htm ' Ranges for appliances not on that site extrapolated from values given in classroom ' texts. Select Case cbxApplianceList.Text ' REFRIGERATOR----------------------------------------------------------------- Case "Refrigerator" Const dblMIN_POWER = 0.1 Const dblMAX_POWER = 0.5 ' Checks if the value is in range and if not puts cursor back in the text box If Not InRange(txtPower.Text, dblMIN_POWER, dblMAX_POWER) Then txtPower.Focus()
  • 2. 2C:UsersMichelleDocumentsVisual Studio 2013... Cost CalculatorUtility Cost CalculatorAppCalc.vb End If ' HAIR DRYER--------------------------------------------------------------- Case "Hair Dryer" Const dblMIN_POWER = 1.0 Const dblMAX_POWER = 1.5 ' Checks if the value is in range and if not puts cursor back in the text box If Not InRange(txtPower.Text, dblMIN_POWER, dblMAX_POWER) Then txtPower.Focus() End If ' DEEP FREEZE------------------------------------------------------------- Case "Deep Freeze" Const dblMIN_POWER = 0.1 Const dblMAX_POWER = 0.25 ' Checks if the value is in range and if not puts cursor back in the text box If Not InRange(txtPower.Text, dblMIN_POWER, dblMAX_POWER) Then txtPower.Focus() End If ' MICROWAVE---------------------------------------------------------------- Case "Microwave" Const dblMIN_POWER = 0.5 Const dblMAX_POWER = 1.5 ' Checks if the value is in range and if not puts cursor back in the text box If Not InRange(txtPower.Text, dblMIN_POWER, dblMAX_POWER) Then txtPower.Focus() End If ' COMPUTER------------------------------------------------------------------ Case "Computer" Const dblMIN_POWER = 0.04 Const dblMAX_POWER = 0.2 ' Checks if the value is in range and if not puts cursor back in the text box If Not InRange(txtPower.Text, dblMIN_POWER, dblMAX_POWER) Then txtPower.Focus() End If ' FAN--------------------------------------------------------------------- Case "Fan" Const dblMIN_POWER = 0.005 Const dblMAX_POWER = 0.03 ' Checks if the value is in range and if not puts cursor back in the text box If Not InRange(txtPower.Text, dblMIN_POWER, dblMAX_POWER) Then txtPower.Focus() End If
  • 3. 3C:UsersMichelleDocumentsVisual Studio 2013... Cost CalculatorUtility Cost CalculatorAppCalc.vb ' WASHER------------------------------------------------------------------- Case "Washer" Const dblMIN_POWER = 0.4 Const dblMAX_POWER = 0.6 ' Checks if the value is in range and if not puts cursor back in the text box If Not InRange(txtPower.Text, dblMIN_POWER, dblMAX_POWER) Then txtPower.Focus() End If ' ELSE--------------------------------------------------------------------- Case Else ' Unique error message lblResults.ForeColor = Color.Red lblResults.BackColor = Color.White lblResults.Text = "Please select an appliance from the pull down list." End Select End Sub Private Sub txtHoursPerDay_Leave(sender As Object, e As EventArgs) _ Handles txtHoursPerDay.Leave ResetErrorMessage() Const dblMIN_HOURS = 0.0 Const dblMAX_HOURS = 24.0 ' Checks if the value is in range and if not puts cursor back in the text box If Not InRange(txtHoursPerDay.Text, dblMIN_HOURS, dblMAX_HOURS) Then txtHoursPerDay.Focus() End If End Sub Private Function InRange(ByVal strInputString As String, ByVal dblMinValue As Double, ByVal dblMaxValue As Double) As Boolean ' Tests entered values to determine if they fall within the proper range. ' Returns True if the value is within range, False if the value is not within range. Dim dblEnteredValue As Double If Double.TryParse(strInputString, dblEnteredValue) Then If (dblEnteredValue < dblMinValue) Or (dblEnteredValue > dblMaxValue) Then ShowErrorMessage(dblMinValue, dblMaxValue) Return False Else Return True End If Else
  • 4. 4C:UsersMichelleDocumentsVisual Studio 2013... Cost CalculatorUtility Cost CalculatorAppCalc.vb ShowErrorMessage(dblMinValue, dblMaxValue) Return False End If End Function Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click Dim dblCost As Double ' Used to make it easier to read the code Dim ApplianceOutputList As ListViewItem Dim blnFound As Boolean = False Dim intCounter As Integer = 0 ' Checks to make sure all values are numeric to prevent calculation errors If IsNumeric(txtCostKWh.Text) And _ IsNumeric(txtPower.Text) And _ IsNumeric(txtHoursPerDay.Text) And _ IsNumeric(txtCostPerGallon.Text) And _ IsNumeric(txtGallonsPerHour.Text) Then dblCost = CalculateTotalCostPerDay(CDbl(txtCostKWh.Text), _ CDbl(txtPower.Text), _ CDbl(txtHoursPerDay.Text), _ CDbl(txtCostPerGallon.Text), _ CDbl(txtGallonsPerHour.Text)) ' Updates the list with the values entered by the user lstApplianceOutputList.BeginUpdate() ApplianceOutputList = lstApplianceOutputList.Items.Add(cbxApplianceList.Text) ApplianceOutputList.SubItems.Add(txtHoursPerDay.Text) ApplianceOutputList.SubItems.Add(dblCost.ToString("c")) lstApplianceOutputList.Update() lstApplianceOutputList.EndUpdate() RunningTotal() Else lblResults.ForeColor = Color.Red lblResults.BackColor = Color.White lblResults.Text = "Please make sure all values you have entered are numeric." End If ' Resets the form to get ready for the next set of inputs cbxApplianceList.Text = "Refrigerator" txtHoursPerDay.Text = String.Empty ResetWasherInfo() gbxAppList.Focus() ' Finds the default value for "Refrigerator" and populates the txtPower field with the ' appropriate value While Not blnFound If strApplianceArray(intCounter) = "Refrigerator" Then txtPower.Text = dblDefaultValueArray(intCounter).ToString blnFound = True End If intCounter += 1 End While
  • 5. 5C:UsersMichelleDocumentsVisual Studio 2013... Cost CalculatorUtility Cost CalculatorAppCalc.vb End Sub Private Sub RunningTotal() ' Adds the values in the Cost Per Day column Dim dblRunningTotal As Double = 0.0 For i As Integer = 0 To (lstApplianceOutputList.Items.Count() - 1) ' Gets the values held within the Cost Per Day column and adds them dblRunningTotal += CDbl(lstApplianceOutputList.Items(i).SubItems.Item(2).Text) Next ' Updates lblTotalCost lblTotalCost.Text = dblRunningTotal.ToString("c") End Sub Private Sub ShowErrorMessage(ByVal dblMinValue As Double, _ ByVal dblMaxValue As Double) ' Error message lblResults.ForeColor = Color.Red lblResults.BackColor = Color.White lblResults.Text = "Please enter a numeric value greater than " & dblMinValue.ToString & " and less than " & dblMaxValue.ToString & "." End Sub Private Sub ResetErrorMessage() ' Resets the colors back to default lblResults.ForeColor = SystemColors.ControlText lblResults.BackColor = SystemColors.Control lblResults.Text = String.Empty End Sub Private Function CalculateTotalCostPerDay(ByVal dblCost As Double, _ ByVal dblPower As Double, _ ByVal dblHours As Double, _ ByVal dblGalCost As Double, _ ByVal dblGalHour As Double) As Double ' Total cost per day calculated as Cost per kWH * Power used per hour * hours used. ' When no water is used the value in the right side of the expression will always be zero. Return (dblCost * dblPower * dblHours) + (dblGalCost * dblGalHour * dblHours) End Function Private Sub ResetTheForm() Dim blnFound As Boolean = False Dim intCounter As Integer = 0 ' Reset the form cbxApplianceList.Text = "Refrigerator" txtCostKWh.Text = String.Empty txtHoursPerDay.Text = String.Empty ResetWasherInfo() lblResults.Text = String.Empty lblTotalCost.Text = "0.00" lstApplianceOutputList.Items.Clear() gbxAppList.Focus()
  • 6. 6C:UsersMichelleDocumentsVisual Studio 2013... Cost CalculatorUtility Cost CalculatorAppCalc.vb ' Finds the default value for "Refrigerator" and populates the txtPower field ' with the appropriate value While Not blnFound If strApplianceArray(intCounter) = "Refrigerator" Then txtPower.Text = dblDefaultValueArray(intCounter).ToString blnFound = True End If intCounter += 1 End While End Sub Private Sub ResetWasherInfo() ' Resets the labels and text boxes related to the choice of "Washer" lblGallonCostLabel.Visible = False lblGallonsUsedLabel.Visible = False lblDollarSign2.Visible = False lblGalPerHour.Visible = False txtCostPerGallon.Visible = False txtCostPerGallon.Text = "0.00" txtGallonsPerHour.Visible = False txtGallonsPerHour.Text = "0.0" End Sub Private Sub cbxApplianceList_SelectedValueChanged(sender As Object, e As EventArgs) _ Handles cbxApplianceList.SelectedValueChanged Dim blnFound As Boolean = False Dim intCounter As Integer = 0 ' Looks through the array strApplianceArray, finds the appliance, ' and sets a default value to txtPower.text While Not blnFound If strApplianceArray(intCounter) = cbxApplianceList.Text Then txtPower.Text = dblDefaultValueArray(intCounter).ToString blnFound = True End If intCounter += 1 End While ' Shows fields related to the choice of "Washer" If cbxApplianceList.Text = "Washer" Then lblGallonCostLabel.Visible = True lblGallonsUsedLabel.Visible = True lblDollarSign2.Visible = True lblGalPerHour.Visible = True txtCostPerGallon.Visible = True txtGallonsPerHour.Visible = True Else ResetWasherInfo()
  • 7. 7C:UsersMichelleDocumentsVisual Studio 2013... Cost CalculatorUtility Cost CalculatorAppCalc.vb End If End Sub Private Sub txtCostPerGallon_Leave(sender As Object, e As EventArgs) _ Handles txtCostPerGallon.Leave ' Costs constant values based on cost of author's water. Const dblMIN_COST = 0.01 Const dblMAX_COST = 0.15 ResetErrorMessage() InRange(txtCostPerGallon.Text, dblMIN_COST, dblMAX_COST) End Sub Private Sub txtGallonsPerHour_Leave(sender As Object, e As EventArgs) _ Handles txtGallonsPerHour.Leave ' Gallons of water used based on values found at ' http://www.home-water-works.org/indoor-use/clothes-washer Const dblMIN_GALLONS_USED = 12 Const dblMAX_GALLONS_USED = 45 ResetErrorMessage() InRange(txtGallonsPerHour.Text, dblMIN_GALLONS_USED, dblMAX_GALLONS_USED) End Sub Private Sub AppCalc_Load(sender As Object, e As EventArgs) _ Handles MyBase.Load ' Fills an array of appliance names and a parallel array of default ' values from an external file Dim fileReader As StreamReader Dim intArrayElement As Integer intArrayElement = 0 fileReader = File.OpenText("DefaultValues.txt") ' Counts the number of elements needed in the parallel arrays While Not fileReader.EndOfStream fileReader.ReadLine() fileReader.ReadLine() intArrayElement += 1 End While fileReader.Close() ' Resizes arrays based on the number of records in the data file ReDim strApplianceArray(intArrayElement - 1) ReDim dblDefaultValueArray(intArrayElement - 1) fileReader = File.OpenText("DefaultValues.txt") For i As Integer = 0 To (intArrayElement - 1) strApplianceArray(i) = fileReader.ReadLine() dblDefaultValueArray(i) = CDbl(fileReader.ReadLine())
  • 8. 8C:UsersMichelleDocumentsVisual Studio 2013... Cost CalculatorUtility Cost CalculatorAppCalc.vb Next fileReader.Close() End Sub Private Sub btnExport_Click(sender As Object, e As EventArgs) _ Handles btnExport.Click ' Exports the data in the lstApplianceOutputList and the total ' cost into a txt file Dim fileWriter As StreamWriter Dim strTemp As String 'Used to format the output Dim strTempApp As String 'Used to format the output Dim strTempHours As String 'Used to format the output Dim strTempCost As String 'Used to format the output fileWriter = File.AppendText("ExportFile.txt") ' Writes a header to the text file fileWriter.WriteLine(String.Format("{0, 15} {1, 15} {2, 15}", _ "Appliance", "Hours Used", "Cost per Day")) ' Runs through lstApplianceOutputList, reads the values into the temp variables, ' formats the results, and then writes the formated results into the text file For i As Integer = 0 To (lstApplianceOutputList.Items.Count - 1) strTempApp = lstApplianceOutputList.Items(i).Text strTempHours = lstApplianceOutputList.Items(i).SubItems(1).Text strTempCost = lstApplianceOutputList.Items(i).SubItems(2).Text strTemp = String.Format("{0, -15} {1, 15} {2, 15}", _ strTempApp, strTempHours, strTempCost) fileWriter.WriteLine(strTemp) Next ' Adds the total cost to the text file fileWriter.WriteLine("-----------------") fileWriter.WriteLine("Total Cost") fileWriter.WriteLine(lblTotalCost.Text) fileWriter.WriteLine() fileWriter.Close() ' Let's the user know something happened when the button was clicked lblResults.Text = "File has been exported to ExportFile.txt." End Sub End Class