I need help writing an arithmetic code for visual basic. I cannot get the number
ID: 3677895 • Letter: I
Question
I need help writing an arithmetic code for visual basic. I cannot get the numbers to multiply, the answers is always zero.
Here is what I have:
Public Class Form1
Private Property operands As Integer
Private Sub enterButton_Click(sender As Object, e As EventArgs) Handles enterButton.Click
If resultLabel.Text <>
String.Empty Then
resultLabel.Text =
String.Empty
operandsListBox.Items.Clear()
addButton.Enabled = False
multiplyButton.Enabled =
False
End If
operandsListBox.Items.Add(Val(enterOperandTextBox.Text))
enterOperandTextBox.Clear()
enterOperandTextBox.Focus()
If operandsListBox.Items.Count >= 2 Then
addButton.Enabled = True
End If
End Sub
Private Sub addButton_Click(sender As Object, e As EventArgs) Handles addButton.Click
Dim sum As Double
For x As Integer = 0 To operandsListBox.Items.Count - 1
sum += (operandsListBox.Items(x))
Next
resultLabel.Text = sum.ToString
End Sub
Private Sub multiplyButton_Click(sender As Object, e As EventArgs) Handles multiplyButton.Click
Dim product As Double
For x As Integer = 0 To operandsListBox.Items.Count - 1
product *= operandsListBox.Items(x)
Next
resultLabel.Text = product.ToString
End Sub
End Class
Explanation / Answer
In the given program
the variable (product) is 0 to begin with
so, you are trying to multiply the number in the listbox by 0 which is always going to equal 0.
(product) should be assigned the first number in the listbox before entering the loop
and then the loop should start at the second number in the listbox.
Also the numbers in the listbox are actually strings
and should be converted to a double before any math functions are done with them
or they are assigned to a Double variable. You can do that like this
product *= CDbl(operandsListBox.Items(x))
modified program
Public Class Form1
Private Property operands As Integer
Private Sub enterButton_Click(sender As Object, e As EventArgs) Handles enterButton.Click
If resultLabel.Text <>
String.Empty Then
resultLabel.Text =
String.Empty
operandsListBox.Items.Clear()
addButton.Enabled = False
multiplyButton.Enabled = False
End If
operandsListBox.Items.Add(Val(enterOperandTextBox.Text))
enterOperandTextBox.Clear()
enterOperandTextBox.Focus()
If operandsListBox.Items.Count >= 2 Then
addButton.Enabled = True
End If
End Sub
Private Sub addButton_Click(sender As Object, e As EventArgs) Handles addButton.Click
Dim sum As Double
For x As Integer = 0 To operandsListBox.Items.Count - 1
sum += (operandsListBox.Items(x))
Next
resultLabel.Text = sum.ToString
End Sub
Private Sub multiplyButton_Click(sender As Object, e As EventArgs) Handles multiplyButton.Click
Dim product As Double
For x As Integer = 0 To operandsListBox.Items.Count - 1
product *= CDbl(operandsListBox.Items(x))
Next
resultLabel.Text = product.ToString
End Sub
End Class