I am attempting to create a grade calculator program and I am having some two problems:
Getting the right outputs (because I am getting ridiculous numbers) and
Getting my counters to work.
The basic form is basically one enters 7 input grades:
3 exams (weighed 15%, 20%, and 20% respectively)
A project (weighed 10%),
Assignments (weighed 20%),
Peer reviews (weighed 5%) ,
A programming language presentation (weighed 10%)
and the individual is supposed to get an output of their numeric grade, their letter grade, and two counters that count how many people got A's and F's.
For an example when I enter 3 exam grades: 82,87,91; Assignments: 94; Peer reviews: 100; programming language presentation: 90; and final project: 92,
I get a final numeric grade of 253.90 and a letter grade of F when it clearly should be a letter grade of A and numeric 89.90.
My counters also are not working properly because they aren't displaying the count, but I feel like I put it in the right place (displaying outputs). What exactly am I doing wrong here? Here's my code
Option Strict On
Public Class frmGradeCalculator
'declare Constants
Const EXAM1GRADE_WEIGHT As Decimal = 0.15D
Const EXAM2GRADE_WEIGHT As Decimal = 0.2D
Const EXAM3GRADE_WEIGHT As Decimal = 0.2D
Const HOMEWORKGRADE_WEIGHT As Decimal = 0.2D
Const HOMEWORKPEERREVIEW_WEIGHT As Decimal = 0.05D
Const LANGUAGEQUICKREFERENCE_WEIGHT As Decimal = 0.1D
Const FINALPROJECT_WEIGHT As Decimal = 0.1D
'Declare module variables
Dim mdecFinalNumericGrade As Decimal
Dim mstrFinalLetterGrade As String
Dim mintStudentsWithAs As Integer
Dim mintStudentsWithFs As Integer
Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click
'declare variables
Dim decExam1Grade As Decimal
Dim decExam2Grade As Decimal
Dim decExam3Grade As Decimal
Dim decHomeworkGrade As Decimal
Dim decPeerReviewGrade As Decimal
Dim decLanguageReferenceGrade As Decimal
Dim decFinalProjectGrade As Decimal
Dim decPercent As Decimal
'check for blanks
If (txtExam1Grade.Text) = "" Then
MessageBox.Show("You Can't Leave Exam 1 Blank")
Exit Sub
End If
'check for numeric
If IsNumeric(txtExam1Grade.Text) = False Then 'value is not numeric
MessageBox.Show("Please enter a numeric value for Exam 1!")
Exit Sub
End If
'check for blanks
If (txtExam2Grade.Text) = "" Then
MessageBox.Show("Please enter Exam 2!")
Exit Sub
End If
'check for everything else
If IsNumeric(txtExam2Grade.Text) = False Then 'Value is not numeric
MessageBox.Show("Please enter a numeric value for Exam 2!")
Exit Sub
End If
'check for blanks
If (txtExam3Grade.Text) = "" Then
MessageBox.Show("Please enter Exam 3!")
Exit Sub
End If
'check for numerics
If IsNumeric(txtExam3Grade.Text) = False Then
MessageBox.Show("Please enter a positive numeric value for Exam3!")
Exit Sub
End If
'check for blanks
If (txtHomeworkGrade.Text) = "" Then
MessageBox.Show("Please enter Homework Grade!")
Exit Sub
End If
'check for numerics
If IsNumeric(txtHomeworkGrade.Text) = False Then
MessageBox.Show("Please enter a numeric positive value for Homework Grade!")
Exit Sub
End If
'check for blanks
If (txtPeerReviewGrade.Text) = "" Then
MessageBox.Show("Please enter a Peer Review Grade!")
Exit Sub
End If
'check for numerics
If IsNumeric(txtPeerReviewGrade.Text) = False Then
MessageBox.Show("Please enter a numeric positive value for Peer Review Grade!")
Exit Sub
End If
'check for blanks
If (txtLanguageReferenceGrade.Text) = "" Then
MessageBox.Show("Please enter a Language Reference Grade!")
Exit Sub
End If
'check for numerics
If IsNumeric(txtLanguageReferenceGrade.Text) = False Then
MessageBox.Show("Please enter a numeric positive value for Language Reference Grade!")
Exit Sub
End If
'check for blanks
If (txtFinalProjectGrade.Text) = "" Then
MessageBox.Show("Please enter a Final Project Grade!")
Exit Sub
End If
'check for numerics
If IsNumeric(txtFinalProjectGrade.Text) = False Then
MessageBox.Show("Please enter a numeric positive value for Final Project Grade!")
Exit Sub
End If
'convert data types
decExam1Grade = Convert.ToDecimal(txtExam1Grade.Text)
decExam2Grade = Convert.ToDecimal(txtExam2Grade.Text)
decExam3Grade = Convert.ToDecimal(txtExam3Grade.Text)
decHomeworkGrade = Convert.ToDecimal(txtHomeworkGrade.Text)
decPeerReviewGrade = Convert.ToDecimal(txtPeerReviewGrade.Text)
decLanguageReferenceGrade = Convert.ToDecimal(txtLanguageReferenceGrade.Text)
decFinalProjectGrade = Convert.ToDecimal(txtFinalProjectGrade.Text)
mdecFinalNumericGrade = (decExam1Grade * EXAM1GRADE_WEIGHT) + _
(decExam2Grade * EXAM2GRADE_WEIGHT) + _
(decExam3Grade * EXAM3GRADE_WEIGHT) + _
(decHomeworkGrade * HOMEWORKGRADE_WEIGHT) + _
(decPeerReviewGrade * HOMEWORKPEERREVIEW_WEIGHT) + _
(decLanguageReferenceGrade + LANGUAGEQUICKREFERENCE_WEIGHT) + _
(decFinalProjectGrade + FINALPROJECT_WEIGHT)
'check for 0 or positive
If decExam1Grade < 0 Then
MessageBox.Show("Please enter a positive value or zero for Exam 1!")
Exit Sub
End If
'check for 0 or positive
If decExam2Grade < 0 Then
MessageBox.Show("Please enter a positive value or zero for Exam 2!")
Exit Sub
End If
'check for 0 or positive
If decExam3Grade < 0 Then
MessageBox.Show("Please enter a positive value or zero for Exam 3!")
Exit Sub
End If
'check for 0 or positive
If decHomeworkGrade < 0 Then
MessageBox.Show("Please enter a positive value or zero for Homework Grade!")
Exit Sub
End If
'check for 0 or positive
If decPeerReviewGrade < 0 Then
MessageBox.Show("Please enter a positive value or zero for Peer Review Grade!")
Exit Sub
End If
'check for 0 or positive
If decLanguageReferenceGrade < 0 Then
MessageBox.Show("Please enter a positive value or zero for Language Reference!")
Exit Sub
End If
'check for 0 or positive
If decFinalProjectGrade < 0 Then
MessageBox.Show("Please enter a positive value or zero for Final Project Grade!")
Exit Sub
End If
'make sure values are less than 100
If decExam1Grade > 100 Then
MessageBox.Show("Please enter a value thats 100 or less!")
End If
If decExam2Grade > 100 Then
MessageBox.Show("Please enter a value thats 100 or less!")
End If
If decExam3Grade > 100 Then
MessageBox.Show("Please enter a value thats 100 or less!")
End If
If decHomeworkGrade > 100 Then
MessageBox.Show("Please enter a value thats 100 or less!")
End If
If decPeerReviewGrade > 100 Then
MessageBox.Show("Please enter a value thats 100 or less!")
End If
If decLanguageReferenceGrade > 100 Then
MessageBox.Show("Please enter a value thats 100 or less!")
End If
If decFinalProjectGrade > 100 Then
MessageBox.Show("Please enter a value thats 100 or less!")
End If
'Determine grade per letter
Select Case decpercent
Case Is >= 89.5D
mstrFinalLetterGrade = "A"
mintStudentsWithAs += 1
Case Is >= 79.5D
mstrFinalLetterGrade = "B"
Case Is >= 69.5D
mstrFinalLetterGrade = "C"
Case Is >= 59.5D
mstrFinalLetterGrade = "D"
Case Else
mstrFinalLetterGrade = "F"
mintStudentsWithFs += 1
End Select
lblFinalLetterGrade.Text = mstrFinalLetterGrade
'display outputs
lblFinalNumericGrade.Text = mdecFinalNumericGrade.ToString("f2")
End Sub
Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click
'clear the texboxes and labels
txtExam1Grade.Clear()
txtExam2Grade.Clear()
txtExam3Grade.Clear()
txtHomeworkGrade.Clear()
txtPeerReviewGrade.Clear()
txtLanguageReferenceGrade.Clear()
txtFinalProjectGrade.Clear()
lblFinalLetterGrade.Text = ""
lblFinalNumericGrade.Text = ""
'setcursor back to top textbox
txtExam1Grade.Focus()
End Sub
Private Sub btnReset_Click(ByVal sende As System.Object, ByVal e As System.EventArgs) Handles btnReset.Click
'reset module level variables
mdecFinalNumericGrade = 0
mstrFinalLetterGrade = ""
mintStudentsWithAs = 0
mintStudentsWithFs = 0
End Sub
Private Sub btnExit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExit.Click
'close the form
End
End Sub
Private Sub frmGradeCalculator_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
End Sub
End Class
Your final grade total is wrong because you're not multiplying the language presentation and final project by their weights, but adding the weight to the score:
Exam1 = 82 * .15 = 12.3
Exam2 = 87 * .20 = 17.4
Exam3 = 91 * .20 = 18.2
Assignments = 94 * .20 = 18.8
Peer Review = 100 * .05 = 5
Language Presentation = 90 + .10 = 90.1
Final Project = 92 + .10 = 92.1
Notice the addition (rather than multiplication) on the last two values. The total is 253.9.
Change the last two calculations for medcFinalNumericGrade to:
(decLanguageReferenceGrade * LANGUAGEQUICKREFERENCE_WEIGHT) + _
(decFinalProjectGrade * FINALPROJECT_WEIGHT)
You will always get an "F" because decpercent is never assigned a value, and therefore the Else Case is executed. Either assign decpercent a value, or use mdecFinalNumericGrade.
For example:
Select Case mdecFinalNumericGrade
instead of
Select Case decpercent
Once you fix the Select Case, your counts should work (unless you reset the form).
Related
I'm new to Visual Basics and I need some help.
I need to calculate the overtime pay into the gross pay.
Here is my whole code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Assigns integer and decimals'
Dim intHoursWorked As Integer
Dim decPayPerHour As Decimal
Dim decGrossPay As Decimal
Dim decTax As Decimal
Dim decNetPay As Decimal
'Conversions'
If IsNumeric(Me.HoursWorked.Text) Then
intHoursWorked = Convert.ToInt32(Me.HoursWorked.Text)
If IsNumeric(Me.txtPPH.Text) Then
decPayPerHour = Convert.ToDecimal(Me.txtPPH.Text)
End If
End If
'Hours worked + overtime'
If intHoursWorked > 48 Then
MsgBox("You have exceeded your maximum hours")
Me.HoursWorked.Text = ""
Me.lblNetPay.Text = ""
Me.lblGrossPay.Text = ""
Me.lblTax.Text = ""
ElseIf intHoursWorked < 23 Then
MsgBox("You must enter at least 23 hours")
' Add time and a half for overtime
ElseIf decGrossPay = decGrossPay + (decGrossPay - 40) * 0.5 Then
End If
'Pay per hour'
If decPayPerHour < 14.25 Then
MsgBox("You must enter a value above $14.25")
ElseIf decPayPerHour > 100 Then
MsgBox("You must enter a value lower than $100")
Else
If Me.radSingleRate.Checked = True Then
decTax = 0.205D
ElseIf Me.radFamilyRate.Checked = True Then
decTax = 0.15D
End If
End If
'Calculations for Gross, Tax, and Netpay'
decGrossPay = intHoursWorked * decPayPerHour
decTax = intHoursWorked * decPayPerHour * decTax
decNetPay = decGrossPay - decTax
Me.lblGrossPay.Text = decGrossPay.ToString("C")
Me.lblNetPay.Text = decNetPay.ToString("C")
Me.lblTax.Text = decTax.ToString("C")
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.txtName.Focus()
Me.radSingleRate.Checked = True
Me.lblTax.Text = ""
Me.lblGrossPay.Text = ""
Me.lblNetPay.Text = ""
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
' Clears all inputs '
Me.txtName.Text = ""
Me.HoursWorked.Text = ""
Me.txtPPH.Text = ""
Me.lblGrossPay.Text = ""
Me.lblTax.Text = ""
Me.lblNetPay.Text = ""
Me.radSingleRate.Checked = True
Me.radFamilyRate.Checked = False
Me.txtName.Focus()
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
' Closes Application '
Me.Close()
End Sub
End Class
I can't figure out what code I should be typing into my code to have it calculate the gross pay. The overtime should be automatically calculated by the program if a number over 40 hours worked is inputted by the user. Overtime is time and a half.
I think you are after something like this?
Select Case intHoursWorked
Case Is > 48
MsgBox ("You have exceeded your maximum hours")
Case Is < 23
MsgBox ("You must enter at least 23 hours")
Case 40 To 48
decGrossPay = decGrossPay * 5
Case Else
'Add code for any other scenarios if required.
End With
Edit, not really sure how you are calculating the pay. Don't you need a figure for the regular hourly rate? If so, maybe something like this. Can't test because it's only partial code and just a guess.
Select Case intHoursWorked
Case Is > 48
MsgBox ("You have exceeded your maximum hours")
Case Is < 23
MsgBox ("You must enter at least 23 hours")
Case 40 To 48
decGrossPay = hourlyrate * 40 + ((intHoursWorked - 40) * (hourlyrate * 1.5))
Case Else
decGrossPay = hourlyrate * intHoursWorked
End With
This part got problem as you did not consider the hours between 24 ~ 48:
ElseIf intHoursWorked < 23 Then
MsgBox("You must enter at least 23 hours")
' Add time and a half for overtime
ElseIf decGrossPay = decGrossPay + (decGrossPay - 40) * 0.5 Then
End If
Should it work if you amend the code as following, so that if the worker work more than 24 but less than 40 hours, they only get basic hours, when they work more than 40 hours, they will get basic + OT, although I did not go through the remaining part and i am consider the decGrossPay is total hours to be paid:
ElseIf intHoursWorked < 23 Then
MsgBox("You must enter at least 23 hours")
' Add time and a half for overtime
ElseIf intHoursWorked > 40 and intHoursWorked <= 48 Then
decGrossPay = 40+ ((intHoursWorked - 40) *0.5 )
else decGrossPay = 40
End If
I am a new programmer learning Visual Basic.
Right now, I'm working on a project about a softball scoreboard. I have been working on this project for a bit, and I am confused on 1 thing.
The thing I am confused on is that I put in a messagebox that said invalid input for negative numbers, but it does not delete it from lstScores and even though the message box appears it still counts as a inning input.
If runs < 0 Then
MessageBox.Show(VALID_MESSAGE)
This is the code:
Public Class frmSoftballScoreboard
Const VALID_MESSAGE As String = "Enter valid runs value"
Const ONLY_MESSAGE As String = "Only seven innings are allowed"
'Declaring array
Dim scores(6) As Double
'declaring variables
Dim runs As String
Dim runningScore As Integer = 0
Dim i As Integer = 0
Dim out As Double
'page load event
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
lstScores.Items.Add("Runs : Running Score")
End Sub
'Enter score button
Private Sub btnScore_Click(sender As Object, e As EventArgs) Handles btnScore.Click
If i < scores.Length Then
'display inputbox to the user
runs = InputBox("Enter score for " & (i + 1) & " innings", "Score")
'if runs is entered
If runs <> "" Then
'parse the value of runs
If (Double.TryParse(runs, out)) Then
'parse the runs and add it to the array scores()
scores(i) = Double.Parse(runs)
runningScore += scores(i)
'add the rainfall value to the listbox along with month name
lstScores.Items.Add(scores(i) & " :" & runningScore)
'increment the value of i
i = i + 1
Else
'display error message
MessageBox.Show(VALID_MESSAGE)
lblTotal.Text = ""
End If
Else
'if runs is empty then display error message
MessageBox.Show("Enter runs for " & i & "innings")
End If
Else
MessageBox.Show(ONLY_MESSAGE)
End If
If runs < 0 Then
MessageBox.Show(VALID_MESSAGE)
End If
'calculate total runs And display on the lable
If scores(6) = 7 Then
lblTotal.Text = String.Format("final score is {0}", scores.Sum())
End If
End Sub
'Clear Menu click
Private Sub ClearToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles mnuClear.Click
lstScores.Items.Clear()
lblTotal.Text = ""
'reset i to 0
i = 0
End Sub
'Exit Menu click
Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles mnuExit.Click
'close application
Application.Exit()
End Sub
End Class
I would really appreciate it if you could help. Thank you.
Private Sub btnScore_Click(sender As Object, e As EventArgs) Handles btnScore.Click
If i < scores.Length Then
'display inputbox to the user
runs = InputBox("Enter score for " & (i + 1) & " innings", "Score")
'if runs is entered
If runs < 0 Then
MessageBox.Show(VALID_MESSAGE)
Exit Sub
ElseIf runs <> "" Then
'parse the value of runs
If (Double.TryParse(runs, out)) Then
'parse the runs and add it to the array scores()
scores(i) = Double.Parse(runs)
runningScore += scores(i)
'add the rainfall value to the listbox along with month name
lstScores.Items.Add(scores(i) & " :" & runningScore)
'increment the value of i
i = i + 1
Else
'display error message
MessageBox.Show(VALID_MESSAGE)
lblTotal.Text = ""
End If
Else
'if runs is empty then display error message
MessageBox.Show("Enter runs for " & i & "innings")
End If
Else
MessageBox.Show(ONLY_MESSAGE)
End If
If runs < 0 Then
MessageBox.Show(VALID_MESSAGE)
End If
'calculate total runs And display on the lable
If scores(6) = 7 Then
lblTotal.Text = String.Format("final score is {0}", scores.Sum())
End If
End Sub
This is the reason why if you input invalid data it will add into lstScores, because your If statement.. is in bottom of your code, although is not recommend where you put the If else statement... Remember reading of the code is start in top to bottom.
Your first If statement is like this. If runs <> "" then ...., of course if you type the -1 value in the Input Text the Boolean will result to true, If -1 <> "" = true, then it will proceed to the statement which is
If (Double.TryParse(runs, out)) Then
'parse the runs and add it to the array scores()
scores(i) = Double.Parse(runs)
runningScore += scores(i)
'add the rainfall value to the listbox along with month name
lstScores.Items.Add(scores(i) & " :" & runningScore)
'increment the value of i
i = i + 1
This is the line of code even the value is invalid or not it still adding value in the lstScores, lstScores.Items.Add(scores(i) & " :" & runningScore)
Now after that statement you will receive a message which is :
Enter valid runs value
If runs < 0 Then
MessageBox.Show(VALID_MESSAGE)
End If
That code is the reason why you receiving the message. If you input -1 of course the result of boolean is true, why? -1 is lessthan to 0 which is true.
The thing i do is, I've insert If statement.. above, which is If runs < 0 then .... and also Exit Sub to instantly end the statement. If you input -1 to Input Text the result is something like this, if runs(-1) lessthan to 0 the Boolean result is true then it will proceed to statement which is the Message and Exit Sub.
Try my code above, and also use Breakpoints.. Hope this helps..
The code is supposed to display all the numbers that meet the criteria. It is not complete, but I cannot figure out why it is displaying the numbers that are larger than 10 in the list box. For example, I will type a 2 into the text box and the MessageBox will show saying the number has to be bigger than 3 and it will not display the number in the list box. If I type a number bigger than 10 it will display the MessageBox saying that the number must be bigger than 10 but it will display it in the list box. I do not know why.
Private Sub btnProcess_Click(sender As Object, e As EventArgs) Handles btnProcess.Click
Dim input As String = txtNumber.Text
If DataOk() Then
lstOutput.Items.Clear()
lstOutput.Items.Add(input)
End If
End Sub
Function DataOk() As Boolean
Dim number As String = txtNumber.Text
If number = "" Then
MessageBox.Show("Must not be blank")
txtNumber.Focus()
ElseIf CInt(number) > 10 Then
MessageBox.Show("Number must be less than 10")
txtNumber.Focus()
ElseIf CInt(number) < 3 Then
MessageBox.Show("Number must be greater than 3")
txtNumber.Focus()
Return False
End If
Return True
End Function
You are getting numbers added because there is no Return False if number is greater than 10. Hence True is returned. To solve your problem, update your code as below.
ElseIf CInt(number) > 10 Then
MessageBox.Show("Number must be less than 10")
txtNumber.Focus()
Return False ''please add this statement
ElseIf CInt(number) < 3 Then
You may rewrite the function as below.
Function DataOk() As Boolean
Dim number As Integer
Dim errMssg As String = ""
If txtNumber.Text.Trim = "" Then
errMssg = "Must not be blank"
ElseIf Not Integer.TryParse(txtNumber.Text.Trim, number) Then
errMssg = "Provide a valid number"
ElseIf number > 10 Then
errMssg = "Number must be less than 10"
ElseIf number < 3 Then
errMssg = "Number must be greater than 3"
End If
If errMssg = "" Then
Return True
Else
MessageBox.Show(errMssg)
Me.txtNumber.Focus()
Return False
End If
End Function
Hey guys I have been having this crashing problem with my program.
I am trying to create a program where it calculates a persons account balance by inputting their beginning balance, credit limit, total charges, and total credits. In this case I am having specific problems with the Total Charges and Total Credits Code.
I have a message box set up to where if the Total Charges and total credits box are blank it will say "please enter a numeric value for ....". The problem is that when I do run it and enter a blank, the message shows up and then the program crashes.
After crashing, the The program then highlights in yellow the specific conversion code (in this case: decTotalCharges = Convert.ToDecimal(txtTotalCharges.Text)) and the error says Input string was not in correct format.
What's going on, I converted it into a correct format right? (decimal to decimal?). Here's an in depth look at my code:
Public Class frmEndingBalance
'Declare module level variables
Dim mdecEndingBalance As Decimal
Dim mdecAllCharges As Decimal
Dim mdecAllCredits As Decimal
Dim mintCustomersOverLimit As Integer
Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click
'clears the form
'clears the labels
txtAccountNumber.Text = ""
txtBeginningBalance.Text = ""
txtTotalCharges.Text = ""
txtTotalCredits.Text = ""
txtCreditLimit.Text = ""
lblEndingBalance.Text = ""
lblCreditMessage.Text = ""
lblAllCharges.Text = ""
lblAllCredits.Text = ""
lblCustomersOverLimit.Text = ""
lblCreditMessage.Text = ""
'clear the textboxes
txtAccountNumber.Clear()
txtBeginningBalance.Clear()
txtTotalCredits.Clear()
txtTotalCharges.Clear()
txtCreditLimit.Clear()
'clear module level variables
mdecEndingBalance = 0
mdecAllCharges = 0
mdecAllCredits = 0
mintCustomersOverLimit = 0
End Sub
Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click
'Declare Variables
Dim intAccountNumber As Integer
Dim intBeginningBalance As Integer
Dim decTotalCharges As Decimal
Dim decTotalCredits As Decimal
Dim decCreditLimit As Decimal
Dim mdecEndingBalance As Decimal 'Beginning Balance + Charges - Credits()
Dim decCreditMessage As Decimal
'check for numeric
If IsNumeric(txtAccountNumber.Text) = False Then 'value is not numeric
MessageBox.Show("You can't enter anything blank!")
Exit Sub
End If
'convert to a numeric data type
intAccountNumber = Convert.ToInt32(txtAccountNumber.Text)
'check for numeric
If String.IsNullOrEmpty(txtBeginningBalance.Text) Then MessageBox.Show("Beginning Balance Cannot Be Blank!")
'check for everything else
If IsNumeric(txtBeginningBalance.Text) = False Then 'Value is not numeric
MessageBox.Show("Please enter a numeric value for Beginning Balance!")
Exit Sub
End If
'convert to a numeric data type
intBeginningBalance = Convert.ToInt32(txtBeginningBalance.Text)
'check for numeric
If IsNumeric(txtTotalCharges.Text) = False Then 'value is not numeric
MessageBox.Show("Please enter a numeric value for Total Charges!")
End If
'convert
decTotalCharges = Convert.ToDecimal(txtTotalCharges.Text)
'check for 0 or positive
If decTotalCharges < 0 Then
MessageBox.Show("Please enter a positive value or zero for number of Total Charges!")
Exit Sub
End If
'check for numeric
If IsNumeric(txtTotalCredits.Text) = False Then 'value is not numeric
MessageBox.Show("Please enter a numeric value for Total Credits")
End If
'convert to a numeric data type
decTotalCredits = Convert.ToDecimal(txtTotalCredits.Text)
'check for 0 or positive
If decTotalCredits < 0 Then
MessageBox.Show("Please enter a positive value or zero for total credits!")
End If
'check numeric
If IsNumeric(txtCreditLimit.Text) = False Then 'value is not numeric
MessageBox.Show("Please enter a numeric value for the Credit Limit!")
End If
'convert to a numeric data type
decCreditLimit = Convert.ToDecimal(txtCreditLimit.Text)
'check for a 0 or positive
If decCreditLimit < 0 Then
MessageBox.Show("Please enter a positive value or zero for Credit Limit!")
End If
'check for customers over limit
decCreditMessage = decCreditLimit - (mdecEndingBalance)
'running totals
mdecAllCharges += decTotalCharges
mdecAllCredits += decTotalCredits
'calculate Ending Balance
mdecEndingBalance = Convert.ToDecimal(intBeginningBalance + decTotalCharges - (decTotalCredits))
'display outputs
lblEndingBalance.Text = mdecEndingBalance.ToString("c")
lblAllCharges.Text = mdecAllCharges.ToString("c")
lblAllCredits.Text = mdecAllCredits.ToString("c")
lblCustomersOverLimit.Text = mintCustomersOverLimit.ToString("n0")
End Class
Any Help would be greatly appreciated!
Thanks
You've missed Exit Sub out of the test
If IsNumeric(txtTotalCharges.Text) = False Then 'value is not numeric
MessageBox.Show("Please enter a numeric value for Total Charges!")
End If
You've done it in a few other places as well (as have we all , in fact as do we all :( ). Be worth refactoring with a little helper method or something similar.
If IsValidDecimal(txtTotalCharges.Text, "Total Charges")
' etc
End If
Good afternoon all, I am beginning my first forays into programming and have decided to begin with VB.net as I can get VS2010 professional free through MS Dreamspark program.
I have been following some basic tutorials online and am now writing a small program that runs a loop to add all the numbers together between two numbers input by the user.
Below is the code I have written:
Public Class Form1
Private Sub cmdAddNumbers_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAddNumbers.Click
Dim NumberOne As Integer
Dim NumberTwo As Integer
Dim Result As Integer
Dim i As Integer
If Not IsNumeric(txtNumberOne.Text) Then
MsgBox("Please Enter A Valid Number For Number One")
txtNumberOne.Clear()
Exit Sub
ElseIf txtNumberOne.Text = 0 Then
MsgBox("Please Enter A Valid Number For Number One")
txtNumberOne.Clear()
Exit Sub
ElseIf txtNumberOne.Text > 0 And IsNumeric(txtNumberOne.Text) Then
NumberOne = txtNumberOne.Text
End If
If Not IsNumeric(txtNumberTwo.Text) Then
MsgBox("Please Enter A Valid Number For Number Two")
txtNumberTwo.Clear()
Exit Sub
ElseIf txtNumberTwo.Text < NumberOne Then
MsgBox("Please Enter A Valid Number For Number Two")
txtNumberTwo.Clear()
Exit Sub
ElseIf txtNumberTwo.Text > NumberOne And IsNumeric(txtNumberTwo.Text) Then
NumberTwo = txtNumberTwo.Text
End If
For i = NumberOne To NumberTwo
Result = Result + i
Next i
txtResult.Text = Result
txtNumberOne.Clear()
txtNumberTwo.Clear()
End Sub
End Class
Now, I am wondering if I have written the most efficent If statements to execute this code or if they can be written any simpler with AND/OR statements to possibly remove some of the ElseIf's.
Any insight is greatly appreciated.
Thank you,
Alex
You should start with putting Option Strict On at the top of your code to force yourself to write code without implicit conversions between strings and numbers. An example of a pitfall in your code is where you compare the string value txtNumberTwo.Text to the numeric value NumberOne; it isn't obvious if the string is converted to a number so that the comparison works properly, or if the number is converted to a string so that it does a string comparison instead.
You can use the Int32.TryParse method to parse each number only once instead of three times:
Dim numberOne As Integer
Dim numberTwo As Integer
Dim result As Integer
If Not Int32.TryParse(txtNumberOne.Text, numberOne) Then
MsgBox("Please Enter A Valid Number For Number One")
txtNumberOne.Clear()
Exit Sub
ElseIf numberOne <= 0 Then
MsgBox("Please Enter A Valid Number For Number One")
txtNumberOne.Clear()
Exit Sub
End If
If Not Int32.TryParse(txtNumberTwo.Text, numberTwo) Then
MsgBox("Please Enter A Valid Number For Number Two")
txtNumberTwo.Clear()
Exit Sub
ElseIf numberTwo < numberOne Then
MsgBox("Please Enter A Valid Number For Number Two")
txtNumberTwo.Clear()
Exit Sub
End If
Your loop is not needed at all. You can calculate the sum directly:
Result = (numberOne + numberTwo) * (numberTwo + 1 - numberOne) / 2
What about:
If Not IsNumeric(txtNumberOne.Text) Or txtNumberOne.Text <= 0 Then
MsgBox("Please Enter A Valid Number For Number One")
txtNumberOne.Clear()
Exit Sub
Else
NumberOne = txtNumberOne.Text
End If
If Not IsNumeric(txtNumberTwo.Text) Or txtNumberTwo.Text < NumberOne Then
MsgBox("Please Enter A Valid Number For Number Two")
txtNumberTwo.Clear()
Exit Sub
Else
NumberTwo = txtNumberTwo.Text
End If
Be aware that if NumberOne is equal to Textbox2.Text, NumberTwo is never assigned
i think the best solution for you is just set the textboxes to be able to accept only numbers, that way you can avoid all the checks if the texts is numeric or not and only check if its bigger than zero.
to set the textboxes to accept only numbers copy this function:
Private Function TrapKey(ByVal KCode As String) As Boolean
If (KCode >= 48 And KCode <= 57) Or KCode = 8 Then
TrapKey = False
Else
TrapKey = True
End If
End Function
and in the keypress event of the textboxes add
e.Handled = TrapKey(Asc(e.KeyChar))
If Not IsNumeric(txtNumberOne.Text) Then
MsgBox("Please Enter A Valid Number For Number One")
txtNumberOne.Clear()
Exit Sub
ElseIf txtNumberOne.Text = 0 Then
MsgBox("Please Enter A Valid Number For Number One")
txtNumberOne.Clear()
Exit Sub
ElseIf txtNumberOne.Text > 0 And IsNumeric(txtNumberOne.Text) Then
NumberOne = txtNumberOne.Text
End If
The third If is superflious. We know it must be IsNumeric, as it passed the first If, and we know it cannot be 0, as it passed the second If. (You also make no allowances at all, if it happens to be negative)
Now, it been a while since I last did VB.Net, but I'm pretty sure it still have a distinct between strings & integers, which means txtNumberOne.Text = 0 shouldn't even compile.
And also, why are you making your users guess what a "valid number" is?
Dim numberOne as Integer
If IsNumeric(txtNumberOne.Text) Then
numberOne = CInt(txtNumberOne.Text)
else
numberOne = -1;
End If
If numberOne < 1
MsgBox("Please Enter A Positive Number For Number One")
txtNumberOne.Clear()
Exit Sub
End If
Dim doub As Double
If Not (Double.TryParse(txtNumberOne.Text, doub) AndAlso doub > 0) Then
MsgBox("Please Enter A Valid Number For Number One")
txtNumberOne.Clear()
Else
NumberOne = doub
End If
If Not (Double.TryParse(txtNumberTwo.Text, doub) AndAlso doub > 0) Then
MsgBox("Please Enter A Valid Number For Number Two")
txtNumberTwo.Clear()
Else
NumberTwo = doub
End If
I think this is waht you are looking for
Result = (NumberTwo * (NumberTwo + 1) / 2) - ((NumberOne - 1) * (NumberOne) / 2)