从txt文件读取并写入文本框

时间:2021-06-03 15:28:44

标签: vb.net

有人能帮我解决这个问题吗,我不知道下一步该做什么

在计算机的任何位置给出一个文本文件,它包含 15 个可以重复的不同整数 使程序不单独打印一个数字的多次重复,而是每个数字只打印一次 旁边写着他出现在哪些地方

    Imports System.IO
Public Class form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim povratnaVrijednost As DialogResult
        Dim nazivDatoteke As String
        Try
            OpenFileDialog1.AddExtension = True
            OpenFileDialog1.Multiselect = False
            OpenFileDialog1.Filter = "Tekst datoteke (*.txt)|*.txt;"
            povratnaVrijednost = OpenFileDialog1.ShowDialog()
            If povratnaVrijednost = Windows.Forms.DialogResult.OK Then
                If OpenFileDialog1.CheckFileExists = True And
                OpenFileDialog1.CheckPathExists = True Then
                    nazivDatoteke = OpenFileDialog1.FileName
                    TextBox1.Text = nazivDatoteke
                    Dim citac As New StreamReader(nazivDatoteke)
                    Dim redTeksta As String = ""
                    Do
                        redTeksta = citac.ReadLine()
                        If Not redTeksta Is Nothing Then
                            RichTextBox1.Text = RichTextBox1.Text + redTeksta
                        End If
                    Loop Until redTeksta Is Nothing
                    citac.Close()
                End If
            End If
        Catch ex As Exception
            MsgBox("Greska prilikom otvaranja" + ex.StackTrace.ToString)


        End Try
    End Sub
End Class

123

2 个答案:

答案 0 :(得分:1)

要求 1:

<块引用>

在计算机的任何位置给出一个文本文件,它包含 15 个可以重复的不同整数

此要求意味着其他一些要求。首先,您应该阅读文本文件。其次,您需要将值解析为数字(大概是整数)。

您可以使用 OpenFileDialog (documentation) 并指定它只能接受文本文件:

Using browseFileDialog = New OpenFileDialog()
    With browseFileDialog
        .Filter = "*.txt|*.txt"

        If (.ShowDialog() = DialogResult.Ok) Then
            '.FileName will be the text file that the user picked
        End If
    End With
End Using

要读取文本文件,假设您需要每一行,请使用 File.ReadAllLines 方法 (documentation):

Using browseFileDialog = New OpenFileDialog()
    With browseFileDialog
        .Filter = "*.txt|*.txt"

        If (.ShowDialog() = DialogResult.Ok) Then
            Dim lines = IO.File.ReadAllLines(.FileName)
        End If
    End With
End Using

要解析值,请使用 Array.ConvertAll 方法 (documentation) 并在谓词内部使用 Integer.Parse 方法 (documentation):

Using browseFileDialog = New OpenFileDialog()
    With browseFileDialog
        .Filter = "*.txt|*.txt"

        If (.ShowDialog() = DialogResult.Ok) Then
            Dim lines = IO.File.ReadAllLines(.FileName)
            Dim values = Array.ConvertAll(lines, Function(line) Integer.Parse(line))
        End If
    End With
End Using

请记住,如果您想验证这些行是否都是有效数字,而不是假设它们都是有效数字,则此步骤将有所不同。但是,您没有在原始帖子中指定该要求,因此我不包括如何做到这一点。

要求 2:

<块引用>

使程序不单独打印一个数字的多次重复,而是每个数字只打印一次

您可以使用 Random.Next 方法 (documentation) 生成随机值。请务必声明一次随机对象的新实例,以便只设置一次种子。要对值进行随机排序,请使用 OrderBy 方法 (documentation) 在谓词中传递随机值:

Private ReadOnly _random As New Random()
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Using browseFileDialog = New OpenFileDialog()
        With browseFileDialog
            .Filter = "*.txt|*.txt"

            If (.ShowDialog() = DialogResult.Ok) Then
                Dim lines = IO.File.ReadAllLines(.FileName)
                Dim values = Array.ConvertAll(lines, Function(line) Integer.Parse(line))
                Dim randomlyOrderedValues = values.OrderBy(Function(value) _random.Next())

                RichTextBox1.Text = String.Join(", ", randomlyOrderedValues.ToArray())
            End If
        End With
    End Using
End Sub

答案 1 :(得分:0)

.AddExtension 的默认值为 True.Multiselect 的默认值为 False。通过将 If 的返回值直接与所需的 .Showdialog 进行比较,我简化了 DialogResult 语句。如果文件路径不存在,对话框将显示警告。

始终尽可能缩小变量的范围。我将 Dim nazivDatoteke 移到 If 内部,因为它没有在其他任何地方使用。 StreamReader 需要一个 Using 块,因为它们需要被释放。

为什么文本文件使用 RichTextBox

如您所见,获取数组中的 distinct 项很容易,只需一行代码。更困难的是在原始数组 lines 中找到索引。

我遍历了 distinct 数组中的所有项目(实际上它是一个 IEnumerable(Of String) 但这对这段代码并不重要,只是在我的解释中键入数组更容易)。我创建了一个 List(Of Integer) 来保存原始数组 lines 中每个项目的索引。 startIndex 其中 FindIndexArray 方法是字符串第一次出现的位置。

Do 循环的每次迭代中,我都会从 lines 数组中查找与项目的匹配项。 FindIndex 接受参数(原始数组、起始索引、我们要查找的内容)。它在找到匹配项后立即停止,如果未找到匹配项,则返回 -1。可以看到这个方法的操作是设置断点和检查变量值。

如果找到匹配项,我会将该值添加到列表中,并将 startIndex 更改为找到的索引之后的位置。

接下来我使用 StringBuilder 创建要显示的字符串。我选择立即窗口进行测试,但您可以在文本框中显示 sb.ToString 或将其添加到 ListBox

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    OpenFileDialog1.Filter = "Tekst datoteke (*.txt)|*.txt;"
    If DialogResult.OK = OpenFileDialog1.ShowDialog Then
        Dim nazivDatoteke = OpenFileDialog1.FileName
        TextBox1.Text = nazivDatoteke
        Dim lines = File.ReadAllLines(nazivDatoteke)
        Dim distinct = lines.Distinct
        For Each item In distinct
            Dim lst As New List(Of Integer)
            Dim startIndex = Array.IndexOf(lines, item)
            Do
                Dim FoundIndex = Array.FindIndex(lines, startIndex, Function(line) line = item)
                If FoundIndex = -1 Then
                    Exit Do
                Else
                    lst.Add(FoundIndex)
                    startIndex = FoundIndex + 1
                End If
            Loop
            Dim sb As New StringBuilder
            sb.Append(item)
            For Each i In lst
                sb.Append($" ({i})")
            Next
            Debug.Print(sb.ToString)
        Next
    End If
End Sub

此代码显示列表中的不同项目,并在原始列表中显示位置(索引)。

相关问题