GPA Calculation - vb.net

I'm having trouble finding out what the proper code would be to calculate the GPA. Everything I try ends up in the wrong GPA. Any help would be greatly appreciated I'm still a beginner at visual basic but this is the best I could do.
Option Explicit On
Option Strict On
Option Infer Off
Public Class mainForm
Private Sub exitButton_Click(sender As Object, e As EventArgs) Handles exitButton.Click
Me.Close()
End Sub
Private Sub dataButton_Click(sender As Object, e As EventArgs) Handles dataButton.Click
Const Prompt As String = "Enter number of Credit Hours:"
Const Title As String = "Credit Hours"
Const Prompt2 As String = "Enter grade:"
Const Title2 As String = "Grades"
Dim inputCredit As String
Dim inputGrades As String
Dim creditHours As Integer
Dim grades As Char
Dim gradesCounter As Integer
Dim point As Integer
Dim gpaTotal As Double
Dim creditHoursAccumulator As Integer
Dim pointAccumulator As Integer
inputCredit = InputBox(Prompt, Title)
inputGrades = InputBox(Prompt2, Title2)
Do While inputCredit <> String.Empty
Integer.TryParse(inputCredit, creditHours)
Char.TryParse(inputGrades, grades)
Select Case grades
Case CChar("A")
point = 4
Case CChar("B")
point = 3
Case CChar("C")
point = 2
Case CChar("D")
point = 1
Case CChar("F")
point = 0
End Select
pointAccumulator += 1
gradesCounter += 1
creditHoursAccumulator += creditHours
inputCredit = InputBox(Prompt, Title)
inputGrades = InputBox(Prompt2, Title2)
Loop
gpaTotal = pointAccumulator / creditHoursAccumulator
totalCreditsLabel.Text = "Total credit hours:" & creditHoursAccumulator
gpaLabel.Text = "GPA:" & gpaTotal
totalGradesLabel.Text = "Number of grades entered:" & gradesCounter
End Sub
End Class

Shouldn't line:
pointAccumulator += 1
be:
pointAccumulator += point

Related

If I click the calculate button the program crashes?

Just for context;
I need to calculate the average of 5 numbers located in 5 textboxes.
Nummer means number
Gemiddelde means average
and
Bereken means calculate
What is causing it to crash?
Private Sub butBereken_Click(sender As Object, e As EventArgs) Handles butBereken.Click
'Variabelen'
Dim nummer1 As Decimal = txtNummer1.Text
Dim nummer2 As Decimal = txtNummer2.Text
Dim nummer3 As Decimal = txtNummer3.Text
Dim nummer4 As Decimal = txtNummer4.Text
Dim nummer5 As Decimal = txtNummer5.Text
Dim somNummers As Decimal = nummer1 + nummer2 + nummer3 + nummer4 + nummer5
Dim Gemiddelde As String = (somNummers) / 5
lblGemiddelde.Text = Gemiddelde
If Gemiddelde < 5.5 Then
lblGemiddelde.Text = Gemiddelde + " Dit is onvoldoende"
End If
If nummer1 = "" Or nummer2 = "" Or nummer3 = "" Or
nummer4 = "" Or nummer5 = "" Then
butBereken.Enabled = False
MessageBox.Show("your mom")
Else
butBereken.Enabled = True
End If
End Sub
I don't see what would crash the program but check to that the TextBoxes have values before assigning them to numeric variables. A Decimal value will never = "".
Private Sub butBereken_Click(sender As Object, e As EventArgs) Handles butBereken.Click 'Variabelen'
If Not IsNumeric(txtNummer1.Text) Or _
Not IsNumeric(txtNummer2.Text) Or _
Not IsNumeric(txtNummer3.Text) Or _
Not IsNumeric(txtNummer4.Text) Or _
Not IsNumeric(txtNummer5.Text) Then
MessageBox.Show ("your mom wants you to fill in all the number boxes")
Exit Sub
End If
Dim nummer1 As Decimal = CDec(txtNummer1.Text)
Dim nummer2 As Decimal = CDec(txtNummer2.Text)
Dim nummer3 As Decimal = CDec(txtNummer3.Text)
Dim nummer4 As Decimal = CDec(txtNummer4.Text)
Dim nummer5 As Decimal = CDec(txtNummer5.Text)
Dim somNummers As Decimal = nummer1 + nummer2 + nummer3 + nummer4 + nummer5
Dim Gemiddelde As String = (somNummers) / 5
lblGemiddelde.Text = Gemiddelde
If Gemiddelde < 5.5 Then
lblGemiddelde.Text = Gemiddelde + "Dit is onvoldoende"
End If
If nummer1 = 0 Or nummer2 = 0 Or nummer3 = 0 Or nummer4 = 0 Or nummer5 = 0 Then
butBereken.Enabled = False
MessageBox.Show ("your mom")
Else
butBereken.Enabled = True
End If
End Sub
If this doesn't work I would consider setting breakpoints in the could to determine what line is causing the crash.
If that doesn't work consider adding this line to the form's initialization:
butBereken.Caption = "Warning: Do not Click!"
Assuming the user populated all the textboxes with numeric only data, (and you have checked this) try replacing these lines in your code with this code
Dim nummer1 As Decimal = txtNummer1.Text
Dim nummer2 As Decimal = txtNummer2.Text
Dim nummer3 As Decimal = txtNummer3.Text
Dim nummer4 As Decimal = txtNummer4.Text
Dim nummer5 As Decimal = txtNummer5.Text
Dim somNummers As Decimal = nummer1 + nummer2 + nummer3 + nummer4 + nummer5
Dim Gemiddelde As Decimal = somNummers / 5
lblGemiddelde.Text = Gemiddelde.ToString("##0.0")
I'd do something more like:
Private Sub butBereken_Click(sender As Object, e As EventArgs) Handles butBereken.Click
Dim TBs() As TextBox = {txtNummer1, txtNummer2, txtNummer3, txtNummer4, txtNummer5}
Dim inputs() As String = TBs.Select(Function(x) x.Text).ToArray()
Dim values() As Decimal
Try
values = Array.ConvertAll(inputs, Function(s) Decimal.Parse(s))
Dim Gemiddelde As String = values.Average()
lblGemiddelde.Text = Gemiddelde & If(Gemiddelde < 5.5, " Dit is onvoldoende", "")
Catch ex As Exception
MessageBox.Show("your mom")
End Try
End Sub
I prefer this approach as it doesn't require repetitive lines of code, manually converting each TextBox to a Decimal. Since the TextBoxes are in an Array, we could also add another TextBox to the form and then add that name to the end of the Array. The rest of the code would not need to change at all; it would still just work as is.
From the Array of TextBox, we use a LINQ statement to extract the Text from each TextBox and add it to an Array of String called "inputs". From there, we convert every single String to a Decimal using Array.ConvertAll(), again avoiding repetitive code. If any of the input values is not a valid Decimal then an Exception will be thrown and we'll jump the the Catch block where the not so well written error message is displayed.
If there are no exceptions, then all String inputs were successfully converted to Decimals and stored in the "values" Array. Next we simply use the LINQ function Average() to get the average of all the values.
Lastly we display the computed average in the Label, adding the "Dit is onvoldoende" message if approapriate. The If() function used in this line is simply a shorthand version of a longer If...Else...End If statement.
In your original attempt, it looks like you wanted to disable the button if any of the values are blank (or maybe if they are invalid decimals?):
If nummer1 = "" Or nummer2 = "" Or nummer3 = "" Or nummer4 = "" Or nummer5 = "" Then
butBereken.Enabled = False
MessageBox.Show("your mom")
Else
butBereken.Enabled = True
End If
This makes no sense as if you disable the button, how would it get turned back on so that user could click it again?
A different approach would be to handle the TextChanged() event of all the TextBoxes and simply update your Label with the average in real-time whenever one of the TextBoxes is changed:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
UpdateAverage()
End Sub
Private Sub txtAll_TextChanged(sender As Object, e As EventArgs) Handles txtNummer5.TextChanged, txtNummer4.TextChanged, txtNummer3.TextChanged, txtNummer2.TextChanged, txtNummer1.TextChanged
UpdateAverage()
End Sub
Private Sub UpdateAverage()
Dim TBs() As TextBox = {txtNummer1, txtNummer2, txtNummer3, txtNummer4, txtNummer5}
Dim inputs() As String = TBs.Select(Function(x) x.Text).ToArray()
Try
Dim values() As Decimal = Array.ConvertAll(inputs, Function(s) Decimal.Parse(s))
Dim average As Decimal = values.Average
lblGemiddelde.Text = average & If(average < 5.5, " Dit is onvoldoende", "")
Catch ex As Exception
lblGemiddelde.Text = "{ Invalid Input }"
End Try
End Sub
End Class
Sample run:

Finding the average of an array after dropping lowest value? (VB)

I'm developing a program that asks the user to input 5 numbers. The lowest of the 5 numbers will be dropped, and then the other 4 numbers are to be averaged.
I'm quite new to VB, but I believe I'm currently on the right path here...
I've sorted the array to help identify the lowest number, but I do not know how to exclude the lowest number and to then average the other remaining 4.
Here is my code so far:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim IntArr(4) As Integer
Dim i As Integer
For i = 1 To 5
IntArr(4) = InputBox("Enter Number" & i)
Next
Array.Sort(IntArr)
'textbox1.text = ???
End Sub
End Class
Can anyone please assist or at least point me in the right direction?
In keeping with the spirit of your code, something like the following would work.
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim IntArr(4) As Integer
Dim OutArr(3) As Integer
For i = 0 To 4
IntArr(i) = InputBox("Enter Number " & i)
Next
Array.Sort(IntArr)
Array.Copy(IntArr, 1, OutArr, 0, 4) 'exclude the lowest number
TextBox1.Text = OutArr.Average()
End Sub
End Class
Using built in LINQ functions
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim numberOfItems = 5
Dim numberOfItemsToRemove = 1
Dim inArray(numberOfItems - 1) As Integer
Dim outArray(numberOfItems - 1 - numberOfItemsToRemove) As Integer
Dim i As Integer
For i = 0 To numberOfItems - 1
While Not Integer.TryParse(InputBox("Enter Number " & i + 1), inArray(i))
MessageBox.Show("Invalid input!")
End While
Next
outArray = inArray.OrderBy(Function(j) j).Skip(numberOfItemsToRemove).ToArray()
MessageBox.Show(
String.Format(
"Input: [{0}], Output: [{1}], average: {2:0.0}",
String.Join(", ", inArray),
String.Join(", ", outArray),
outArray.Average))
End Sub
Your code as it is above will continue to simply change the value of index 4 with each box if I'm not mistaken. I would do something like this (I will use your variable names for your convenience).
Button1_Click(procedure junk that is auto-inserted)
Dim intArr(4) As Integer
Dim OutArr(3) As Integer
Dim intCounter, intAverage, intLowest, intLowIndex As Integer
'populate all indexes of intArr()
For intCounter = 0 to 4
intArr(intCounter) = InputBox("Please enter a number.")
Next intCounter
intCounter = 1 'reset counter for check
intLowest = intArr(intLowIndex) 'start with index 0
'find lowest number and its index
For intCounter = 1 to 4
If intLowest > intArr(intCounter) Then 'defaults to previous
intLowest = intArr(intCounter)
intLowIndex = intCounter
End If
Next intCounter
intCounter = 0 'reset counter again for possible For...Next loops
Select Case intLowIndex
Case = 0
For intCounter = 0 to 3
OutArr(intCounter) = intArr(intCounter + 1)
Next intCounter
Case = 1
OutArr(0) = intArr(0)
OutArr(1) = intArr(2)
OutArr(2) = intArr(3)
OutArr(3) = intArr(4)
Case = 2
OutArr(0) = intArr(0)
OutArr(1) = intArr(1)
OutArr(2) = intArr(3)
OutArr(3) = intArr(4)
Case = 3
OutArr(0) = intArr(0)
OutArr(1) = intArr(1)
OutArr(2) = intArr(2)
OutArr(3) = intArr(4)
Case = 4
For intCounter = 0 to 3
OutArr(intCounter) = intArr(intCounter)
Next intCounter
End Select
intAverage = (OutArr(0) + OutArr(1) + OutArr(2) + OutArr(3)) / 4
'insert your preferred method to display OutArr() and intAverage

Visual Basic Confusion

I have been required to create a program that asks me to find the maximum value of one particular array. I am using multiple forms in this project and have used a user-defined data type and created multiple array under it. There is a first form that is related to this, which defines my defined data type is gStudentRecord and the arrays that define it are last name, Id, and GPA. This second form is where I write all of the code to display what I want. My question is how to get the Max GPA out of that array. I'm sorry if this isn't in very good format, this is the first time I've used Stackoverflow
Public Class frmSecond
Private Sub frmSecond_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim Ctr As Integer
Dim Line As String
lstDisplay.Items.Clear()
lstDisplay.Items.Add("Name".PadRight(25) & "ID".PadRight(16) & "GPA".PadRight(20) & "Out of state".PadRight(10))
For Ctr = 0 To gIndex Step 1
Line = gCourseRoster(Ctr).LastName.PadRight(20) & gCourseRoster(Ctr).ID.PadRight(15) & gCourseRoster(Ctr).GPA.ToString.PadRight(15) & gCourseRoster(Ctr).OutOfState.ToString().PadLeft(5)
lstDisplay.Items.Add(Line)
Next
End Sub
Private Sub btnStats_Click(sender As Object, e As EventArgs) Handles btnStats.Click
Dim Ctr As Integer = 0
Dim Average As Double
Dim Sum As Double
Dim Found As Boolean = False
Dim Pass As Integer
Dim Index As Integer
lstDisplay.Items.Clear()
**For Ctr = 0 To gIndex Step 1
If gCourseRoster(Ctr).GPA > gCourseRoster(Ctr).GPA Then
lstDisplay.Items.Add(gCourseRoster(Ctr).GPA)
End If
Next**
Average = gComputeAverage(Sum)
lstDisplay.Items.Add("Number of Students: " & gNumberOfStudents)
lstDisplay.Items.Add("Average: " & Average)
End Sub
Private Function gComputeAverage(Sum As Double) As Double
Dim Ctr As Integer
Dim Average As Double
For Ctr = 0 To gIndex Step 1
Sum = Sum + gCourseRoster(Ctr).GPA
Next
Average = Sum / gNumberOfStudents
Return Average
End Function
End Class
You can use a Lambda expression to tease it out. The Cast part is converting from the gCourseRoster to a collection of Double by supplying the GPA to the Select statement.
Dim gList As New List(Of gCourseRoster)
gList.Add(New gCourseRoster With {.id = 1, .name = "Bob", .GPA = 3.9})
gList.Add(New gCourseRoster With {.id = 2, .name = "Sarah", .GPA = 3.2})
gList.Add(New gCourseRoster With {.id = 3, .name = "Frank", .GPA = 3.1})
Dim maxGPA = gList.Cast(Of gCourseRoster).Select(Function(c) c.GPA).ToList.Max
MessageBox.Show(maxGPA.ToString)
Output: 3.9

VB program to calculate grades

So I am working on a program that will ask for the number of assignments, say 20, then run through a loop that many times asking for the total points earned on each assignment as well as the total points possible to get the final grade. For example if the user put in 2 assignments with assignment 1 earning 48 points out of 50 and assignment 2 earning 35 points out of 40 the program would display the grade as 92.
So far here is what I have:
Public Class Form1
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click
Dim amountAssignments As Integer
Dim pointsEarned As Integer = 0
Dim pointsEarnedTotal As Integer = 0
Dim pointsPossible As Integer = 0
Dim pointsPossibleTotal As Integer = 0
Dim Assignment As Integer = 1
Integer.TryParse(txtAmount.Text, amountAssignments)
Do Until Assignment > amountAssignments
txtAmount.Text = String.Empty
lblAmount.Text = "Enter Points Given on Assignment " & Assignment & ":"
Integer.TryParse(txtAmount.Text, pointsEarned)
pointsEarnedTotal = pointsEarnedTotal + pointsEarned
lblAmount.Text = "Enter Points Possible on Assignment " & Assignment & ":"
Integer.TryParse(txtAmount.Text, pointsPossible)
pointsPossibleTotal = pointsPossibleTotal + pointsPossible
Assignment = Assignment + 1
Loop
lblAmount.Text = "Enter the amount of Assignments: "
lblGrade.Text = (pointsEarnedTotal / pointsPossibleTotal)
End Sub
End Class
syntax is correct but when the program is run and the number of assignments put in and calculate entered the program displays the grade as NaN with no other input requested.
Could use another set of eye(s) to look over this and tell me where i screwed up logically.
Thank you in advance!
This program seems to not have some sort of user intervention when the loop starts. What I would do is surely have the user enter the amount of assignments on the textbox and then from there would ask the user to enter marks from an input box separated by a slash e.g I enter 45/50 so after input the program finds the index of "/",all characters before the '/' are the pointsEarned and can be added to the pointsEarnedTotal while all the characters after the '/' are placed in the pointsPossible and added to the pointsPossibleTotal
Try this and tell me how it goes...give me points if it works
` Private Sub butGetMarks_Click(sender As System.Object, e As System.EventArgs) Handles butGetMarks.Click
Dim assignments As Integer = 0
Dim totalAssignments As Integer
Integer.TryParse(txtAssignments.Text, totalAssignments)
Dim pointsEarned As Double = 0
Dim pointsEarnedTotal As Double = 0
Dim possibleEarned As Double = 0
Dim possibleEarnedTotal As Double = 0
Dim temp As String
For i As Integer = 1 To totalAssignments
temp = InputBox("Enter marks per assignment separated by /")
Dim i1 As Integer
i1 = temp.IndexOf("/") 'read index of /
pointsEarned = temp.Substring(0, i1) 'read from start until / character
possibleEarned = temp.Substring(i1 + 1) 'read from after / character onwards
'add to totals
possibleEarnedTotal += possibleEarned
pointsEarnedTotal += pointsEarned
Next i
MessageBox.Show(pointsEarnedTotal & "/" & possibleEarnedTotal)
End Sub`

Equals Operator with Listbox & Math not working properly

I'm finished with my homework my teacher asked for. The math isn't calculating out to what it should be. The math is working corectly for Handling Stress, Time management, and supervision skills. When I get to Negotiation, and How to interview. I am getting random numbers.
How to interview(395) + Dallas(110) = 505
But I am getting 725. I think it's doing 395 + (110x3).
Public Class frmMain
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim Workshops As New ArrayList()
Workshops.Add(New Workshop("Handling Stress", "595"))
Workshops.Add(New Workshop("Time Management", "695"))
Workshops.Add(New Workshop("Supervision Skills", "995"))
Workshops.Add(New Workshop("Negotiation", "1295"))
Workshops.Add(New Workshop("How to Interview", "395"))
lbWorkshop.DataSource = Workshops
lbWorkshop.DisplayMember = "Workshop"
lbWorkshop.ValueMember = "Price"
lbWorkshop.ClearSelected()
Dim Location As New ArrayList()
Location.Add(New Workshop("Austin", "95"))
Location.Add(New Workshop("Chicago", "125"))
Location.Add(New Workshop("Dallas", "110"))
Location.Add(New Workshop("Orlando", "100"))
Location.Add(New Workshop("Phoenix", "92"))
Location.Add(New Workshop("Raleigh", "90"))
lbLocation.DataSource = Location
lbLocation.DisplayMember = "Workshop"
lbLocation.ValueMember = "Price"
lbLocation.ClearSelected()
End Sub
Private Sub lblAdd_Click(sender As Object, e As EventArgs) Handles lblAdd.Click
Dim description As String
Dim value As Integer
If (lbWorkshop.SelectedIndex > -1) Then
If (lbLocation.SelectedIndex > -1) Then
lblStatus1.Text = String.Empty
If (lbWorkshop.SelectedItem.Equals("How to Interview")) Then
value = lbWorkshop.SelectedValue + lbLocation.SelectedValue
ElseIf (lbWorkshop.SelectedItem.Equals("Negotiation")) Then
value = lbWorkshop.SelectedValue + (lbLocation.SelectedValue * 5)
Else
value = lbWorkshop.SelectedValue + (lbLocation.SelectedValue * 3)
End If
description = value.ToString
lbTotal.Items.Add(description)
lbTotal.ValueMember = value
Dim total As Integer
For Each Str As String In lbTotal.Items
total = total + CInt(Str)
Next
lblTotal.Text = FormatCurrency(total.ToString)
Else
lblStatus1.Text = "Please Select a Location"
End If
Else
lblStatus1.Text = "Please Select a Workshop"
End If
End Sub
it's doing what you asked, as far as I can tell. Is this your intention?
Else 'Supervision Skills, Negotiation, How to Interview
value = lbWorkshop.SelectedValue + (lbLocation.SelectedValue * 3)