【发布时间】:2018-07-02 11:54:46
【问题描述】:
我一直在尝试创建一个程序,该程序将在多行文本框中找到用户单击的单词。此过程基于单击位置的索引。我实现的代码:
Public Class Form1
Private Sub TextBox1_MouseDown(sender As Object, e As MouseEventArgs) Handles TextBox1.MouseDown
If e.Clicks = 1 And e.Button = MouseButtons.Left Then
'Try
Dim indexClicked As Integer = TextBox1.GetCharIndexFromPosition(New Point(e.X, e.Y))
Dim ch As Char = TextBox1.Text.Chars(indexClicked)
Dim indexOfWord As Int32
If Not ch = " " Then
Dim wordFound As Boolean
Dim previousCh As Char
Dim previousIndex As Integer = indexClicked
While Not wordFound
previousIndex = previousIndex - 1
previousCh = TextBox1.Text.Chars(previousIndex)
If previousCh = " " Then
indexOfWord = previousIndex + 1
wordFound = True
End If
End While
Else
indexOfWord = indexClicked + 1
End If
Label1.Text = indexClicked & ", " & indexOfWord
Label2.Text = GetWordByIndex(TextBox1.Text, indexOfWord)
' Catch ex As Exception
' Label2.Text = ex.Message
' End Try
End If
End Sub
Public Shared Function GetWordByIndex(input As String, index As Integer) As String
Try
Dim words = input.Split(" ")
If (index < 0) OrElse (index > words.Length - 1) Then
Throw New IndexOutOfRangeException("Index out of range!")
End If
Return words(index)
Catch ex As Exception
'handle the exception your way
Return String.Empty
End Try
End Function
End Class
问题是每当程序到达该行时:
previousCh = TextBox1.Text.Chars(previousIndex)
它以 :
退出An unhandled exception of type 'System.IndexOutOfRangeException' occurred in WindowsApplication1.exe
Additional information: Index was outside the bounds of the array.
当抛出异常时,通过将鼠标悬停在 previousIndex 变量上,visual studio 会显示它的值:-1。
我认为previousCh = " " 条件永远不会为真,因此程序永远不会退出while 循环,它会一直寻找前一个字符。在某些时候 int previousIndex 变为负数,程序崩溃。为什么条件不能正常工作?
有什么问题? 谢谢。
【问题讨论】:
-
追踪 -1 的来源。我想它应该是0或1。是因为减法导致了这个吗?是不是在某处找不到的默认返回值?
-
这是有用的信息,即使是假设,也可以edit 进入问题。
-
让用户双击单词并使用
.SelectionChanged、.SelectionStart、.SelectionLength和.SelectedText属性不是更容易吗?