1

So the task is: Write a program that contains a text box, a list box and a command button. Put a label above the text box that tells the user to type a number from 1 to 10 inside the text box. When the user clicks the command button, check the text box for a valid number and issue an error message box if the number isn't inside the expected range or in case of empty input. If the user entered a valid number, assign it to the integer variable n and use a For...Next loop to accumulate the sum of the first n elements of an array declared with the statement Dim numList() as Integer = {2, 4, 10, 5, 6, 8, 9, 3, 2, 4} Display the sum in the list box.

Private Sub bCom_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bCom.Click
    Dim n As Integer = CInt(tNum.Text)

    If CDbl(tNum.Text) > 10 Then
        MessageBox.Show("Please Enter a Number from 1 to 10")
        tNum.Focus()
    End If

    Dim numList() As Integer = {2, 4, 10, 5, 6, 8, 9, 3, 2, 4}
    Dim sum As Integer
    For Each n As Integer In numList
        sum += n
    Next

    lOut.Items.Add(sum)
End Sub

End Class

4

3 回答 3

1

您使用的是for each循环而不是for循环,因此您迭代数组中的每个元素,而不仅仅是第一个元素n

你应该使用类似的东西:

For x = 0 To n - 1 
    sum += numList(x)
Next

还有一些问题:

  • 如果您在前一行已经将文本转换为整数,则无需将文本转换为双精度。

  • 您应该Int32.TryParse在用户输入不是数字的情况下使用。

  • 您只需检查数字是否大于 10,而不是小于 1。

  • 如果号码无效,您向用户显示一条消息,然后您继续,但您应该退出您的方法

于 2013-04-30T14:07:38.747 回答
0

正如其他人所说,您需要一个索引 For..Loop,而不是 ForEach 循环。您也可以考虑将“它是一个有效数字”逻辑移到一个单独的函数中。

Public Class Form1

    Private Sub btnCompute_Click(sender As System.Object, e As System.EventArgs) Handles btnCompute.Click
        'is the number valid?
        Dim n As Integer = -1
        If IsInputValid(txbInput.Text, n) Then
            Dim sum As Integer = 0

            'declare an array of numbers
            Dim numList() As Integer = {2, 4, 10, 5, 6, 8, 9, 3, 2, 4}

            'accumulate the sum of the first N elements of the array
            For i As Integer = 0 To n - 1
                sum += numList(i)
            Next

            'refresh the listbox with the sum
            lbxOutput.Items.Clear()
            lbxOutput.Items.Add(sum.ToString)
        Else
            MessageBox.Show("Please enter a number between 1 and 10")
        End If
    End Sub

    Private Function IsInputValid(input As String, ByRef validnumber As Integer) As Boolean
        'input must be a number between 1 and 10
        'if it is valid, assign it to the byref validNumber parameter.
        Dim i As Integer = -1
        If Integer.TryParse(input, i) Then
            If i >= 1 AndAlso i <= 10 Then
                validnumber = i
                Return True
            End If
        End If
        validnumber = i
        Return False
    End Function
End Class
于 2013-04-30T14:16:45.950 回答
0

如果我正确理解了您的问题,您想对数组 numList 的前 n 位求和。
如果是这种情况,那么您需要以这种方式更改循环代码

For x = 0 To n -1 
    sum += numList(x)
Next

使用 x 作为 numList 数组的索引器,从数组的第一个元素 (x=0) 开始,并在索引器达到 n - 1 的值时停止

有了这个,您就可以准确地满足要求。
如果您希望也可以使用 LinQ 展示一种优雅的方法,而无需显式循环

sum = numList.Take(n).Sum()

但是,在花哨之前,最好先删除代码中的一些明显错误

if Not Int32.TryParse(tNum.Text, n) Then
     MessageBox.Show("Error......")
     tNum.Focus()
     Return
End If

if n < 1 OrElse n > 10 Then
     MessageBox.Show("Error......")
     tNum.Focus()
     Return
End if

并且不要使用仅为与 VB6 兼容而保留的老式函数(如 CInt e CDbl)。使用最新的方法,如 Int32.TryParse、Convert.ToInt32 等...

于 2013-04-30T14:00:09.567 回答