VB.NET - Getting a NaN result, can't figure out why - vb.net

I'm trying to write a simple GPA calculator where the user enters a grade from an item on a combobox (A,B,C,D,F) and the credit hours of the course, and the calculation will output into a textbox. However, I keep getting a NaN result within the textbox and I can't for the life of me understand why. I've only got a bit of programming experience, so I'd appreciate any help!
Public Class Form1
Public points As Double, hours As Integer
Private Sub btnRecord_Click(sender As Object, e As EventArgs) Handles btnRecord.Click
Dim gpaPoints As Double
Dim creditHours As Integer
Dim grade As String
If cmbGrades.SelectedIndex < 0 Then
MsgBox("Please select a grade.")
Exit Sub
ElseIf txtHours.Text = "" Then
MsgBox("Please enter credit hours.")
Else
grade = cmbGrades.SelectedItem
creditHours = CInt(txtHours.Text)
gpaPoints = CalcGPA(grade, creditHours)
points += gpaPoints
hours += creditHours
ClearList()
End If
End Sub
Public Sub ClearList()
cmbGrades.SelectedIndex = -1
cmbGrades.Text = "Select a grade"
txtHours.Text = ""
End Sub
Public Function CalcGPA(grade As String, creditHours As Integer)
Dim gpaPoints As Double
Select Case (grade)
Case "A"
gpaPoints = 4
Case "B"
gpaPoints = 3
Case "C"
gpaPoints = 2
Case "D"
gpaPoints = 1
Case Else
gpaPoints = 0
End Select
Return gpaPoints
End Function
Private Sub btnGpa_Click(sender As Object, e As EventArgs) Handles btnGpa.Click
Dim calcGpa As Double = points / hours
txtGpa.Text = FormatNumber(calcGpa, 2)
End Sub
End Class
I basically have the record button which works fine clearing the list and allows someone to enter a second grade, but the calculate button is not working and I can't figure this out. I sincerely appreciate any help.

As a general rule of thumb, if you are getting 'NaN's you can check for the following :
A calculation with any NaN somewhere will give out a NaN
The 0 / 0 division will give a NaN if it's with floating points number. You have a floating point division, so you can check here if your values are not zero when you do your calculation.

Private Sub btnGpa_Click(sender As Object, e As EventArgs) Handles btnGpa.Click
'Dim calcGpa As Double = points / hours '(**did you assign values here?** if not remove this)
dim answer as double = 0
CalcGPA(cmbGrades.SelectedValue, txtHours.Text )
txtGpa.Text = FormatNumber(answer, 2)
End Sub

Related

How to display decimals from vs code to ms access

Ok So,
im making a grading system for students as my first project with databases in vb.net
now when i get the average in decimal value and i save it to show in ms access it says it saved but when i check ms access it never saves it unless i enter values that make the average a whole number
now i went in ms access to change property of the average textbox to allow decimal places but the problem is in vs code and all my dims are already in Double
i.e
Dim average As Double
now i dont think i need to show code but i still will
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Me.Student_GradesBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(StudentGradesDataSet)
MsgBox("Success")
Catch ex As Exception
MsgBox("Please try again")
End Try
End Sub
Private Sub btnCalc_Click(sender As Object, e As EventArgs) Handles btnCalc.Click
Try
Dim geo As Double
Dim comp As Double
Dim maths As Double
Dim sci As Double
Dim grade As String
Dim avg As Double
geo = GeographyTextBox.Text
sci = ScienceTextBox.Text
maths = MathematicsTextBox.Text
comp = ComputerTextBox.Text
If ((geo > 100) Or (sci > 100) Or (comp > 100) Or (maths > 100)) Then
MsgBox("Marks cannot be more than 100")
End
End If
avg = (geo + sci + comp + maths) / 4
If avg < 60 Then
grade = "Failed"
Else
grade = "Passed"
End If
AverageTextBox.Text = avg
GradeTextBox.Text = grade
Catch ex As Exception
MsgBox("try")
End Try
End Sub

Get the result of a sum from a string

this is my code:
Public Class Form1
Function AnswerQuestion(ByVal s As String) As String
If s.Contains("How much is") Then
Dim sum As Integer = 0
For Each ch As Char In s
Dim i As Integer
If Integer.TryParse(ch, i) Then
sum += i
End If
Next
Return "The answer is:" & sum.ToString
Else
Return Nothing
End If
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MsgBox(AnswerQuestion(TextBox1.Text))
End Sub
End Class
I want it to sum anything I put after "How much is", for example, If I put "How much is: 2 + 8" it returns 10 as a result, which is correct, but if I put "How much is: 12+5" it returns 8 instead of 17 :/ I tried to do some research but from many codes I've tried, all of them give me the same or worst result. Is there a way to do?

Need to know why code is repeating itself

Public Class Form1
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
Dim EvenNum, EvenNumCount, EvenNumAverage, Number, Result As Integer
Calculations(EvenNum, EvenNumCount)
GetInput(Number)
Output(Result)
End Sub
Sub GetInput(ByRef Number)
Number = txtInput.Text
End Sub
Sub Calculations(ByRef EvenNum, ByRef EvenNumCount)
Dim ListedNumbers, lstOutputSize As Integer
GetInput(lstOutputSize)
For i As Integer = 0 To lstOutputSize - 1
ListedNumbers = InputBox("Enter Numbers", "Input")
lstOutput.Items.Add(ListedNumbers)
Next
For i As Integer = 0 To lstOutput.Items.Count - 1
If (CInt(lstOutput.Items(i)) Mod 2 = 0) Then
EvenNum += lstOutput.Items(i)
EvenNumCount += 1
End If
Next
End Sub
Function Average(ByRef EvenNumAverage As Integer) As Integer
Dim EvenNum, EvenNumCount As Integer
Calculations(EvenNum, EvenNumCount)
EvenNumAverage = EvenNum / EvenNumCount
Return EvenNumAverage
End Function
Sub Output(ByRef EvenNumAverage)
lstOutput.Items.Add(Average(EvenNumAverage))
End Sub
The program is supposed to get input from a textbox for a desired number of numbers to be entered into a listbox from inputboxes.
It is then supposed to get the average of only the even numbers and then display that average into the listbox.
In it's current state the program will do what it is intended to do, it just repeats the calculation code. This only happens when I add the Output call statement under the button procedure.
You're calling Calculations twice
From btnCalculate_Click
From Average which is called by Output

Syntax error when multiplying variables in VB.NET

I'm trying to multiply two variables within VB Studio, however I am getting a syntax error when trying to do this.
(Quantity * ItemCost) gives me a syntax error on the first bracket, and removing the brackets gives me the error that method arguments must be enclosed in parenthesis.
Sorry if this was rather vague or really obvious, I am new to programming in general and am doing my best to make simple programs. I know my code is far from the most efficient but it's the best I can do at the moment.
The whole of my code is below :
Public Class Form1
Dim CustomerName As String
Dim Pensioner As Boolean
Dim Takeout As Boolean
Dim Items(4) As Array
Dim CostOfItems(4) As Array
Dim Alpha As Integer = 0
Dim Quantity As Integer
Dim ItemCost As Integer
Private Sub txtName_TextChanged(sender As Object, e As EventArgs) Handles txtName.TextChanged
CustomerName = txtName.Text
End Sub
Private Sub cboItemName_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboItemName.SelectedIndexChanged
If cboItemName.Text = "Tea" Then
txtItemPrice.Text = "£0.50"
ElseIf cboItemName.Text = "Coffee" Then
txtItemPrice.Text = "£0.70"
ElseIf cboItemName.Text = "Orange Juice" Then
txtItemPrice.Text = "£0.80"
ElseIf cboItemName.Text = "Apple Juice" Then
txtItemPrice.Text = "£0.80"
ElseIf cboItemName.Text = "Potato" Then
txtItemPrice.Text = "£1.00"
End If
ItemCost = txtItemPrice.Text
End Sub
Private Sub txtQuantity_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtQuantity.KeyPress
If Asc(e.KeyChar) <> 8 Then
If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
e.Handled = True
End If
End If
Quantity = txtQuantity.Text
End Sub
Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
If chxPension.Checked = True Then
Pensioner = True
chxPension.Hide()
End If
If cbxTakeOut.Checked = True Then
TakeOut = True
cbxTakeOut.Hide()
End If
Quantity * ItemCost
txtQuantity.Text = ""
cboItemName.Text = ""
Alpha += 1
txtName.ReadOnly = True
End Sub
End Class
(I have now changed the ItemCost value to not include a £ or . , however I am still getting a syntax error on the bracket)
The problem with your code is that you are not assigning the result of the multiplication to any variable. Some languages permit that (calculating a value and throwing it away), but apparently VB.NET doesn't. It is trying to save you from a common programmer mistake.
Do it like this instead:
Dim TotalCost As Integer = Quantity * ItemCost
The result of the multiplication will now be stored in the variable TotalCost, which you can use for whatever you need.
Of course, you could also store the result of the calculation in one of the operand variables (assuming, of course, it is not a constant). In this case, judging from the names of the variables, it doesn't make much sense, but sometimes it is appropriate:
ItemCost = Quantity * ItemCost ' probably wrong, but syntactically legal
You also need to declare your variables correctly.
item cost can not be integer.
Item cost should be something like double or decimal
Dim TotalCost as Decimal = Quantity * ItemCost
Could you please remove the £ in your txtItemPrice.Text?
Replace this in your existing codes:
ItemCost = cInt(txtItemPrice.Text)
Quantity = cInt(txtQuantity.Text)
This is to convert the Strings (.text) into Integer
For the computation of Total Cost:
Dim Total As Integer = Quantity * ItemCost
Please Take Note:
Integer data types cannot hold values with decimal. Use Double instead.

multiple inputs in text box not totaling

I got another super basic question, im trying to total the subtotals of every entry in the txtPrice.Text the user enters, and then refresh the other lables with the updated tax, shipping, and grand total. Its not totaling the subTotal, everything else works fine. Whats up with that?
Private Sub btnCalc_Click(sender As Object, e As EventArgs) Handles btnCalc.Click
Dim sglSub As Single
Dim sglTotal As Single
Dim sglSalesTax As Single
Const TAX_RATE As Single = 0.02
Dim bytShippingCharge As SByte = 10
Dim sglCompTotal As Single
Single.TryParse(txtPrice.Text, sglSub)
sglTotal += sglSub
lblSubTotal.Text = sglTotal.ToString("C2")
sglSalesTax = (sglTotal * TAX_RATE)
lblTax.Text = sglSalesTax.ToString("C2")
If sglTotal >= 100 Then
bytShippingCharge = 0
End If
lblShipping.Text = bytShippingCharge.ToString("C2")
sglCompTotal = (sglTotal + sglSalesTax + bytShippingCharge)
lblTotal.Text = sglCompTotal.ToString("C2")
End Sub
Tips
In this line:
sglTotal += sglSub
-Every time you work with a total initialize it to zero before adding a value to it. If not it can leads to undesired result.
-When working with currency is better to use a decimal type instead.
If you want a variable keeps its value declare it shared.
This a little example of how you can use a shared field
Public Class Form1
Shared total As Decimal = 0D
Shared Sub calc()
total += 2
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
calc()
Label1.Text = total.ToString
End Sub
End Class