创建指定数量的字符串

时间:2017-02-19 09:25:22

标签: string vb.net random

我想在VB.NET控制台应用程序中创建指定数量的字符串。我尝试过这段代码,但它抛出异常:

  

NullReferenceException:Object Reference未设置为Object的实例。

这是代码:

Module RandStrConsole

Dim r As New Random
Dim s As String
Dim result As System.Text.StringBuilder
Dim sb As System.Text.StringBuilder
Dim MaxChar As Integer


Sub Main()

    Console.Write("Enter String: ") : s = Console.ReadLine
    Console.Write("Maxchar: ") : MaxChar = Console.ReadLine

    For i As Integer = 1 To MaxChar

        Dim idx As Integer = r.Next(0, s.Count - 1)
        result = sb.Append(s.Substring(idx, 1)) 'NullReferenceException: Object Reference not set into an instance of an Object.
        result.ToString()

    Next

    Console.WriteLine(result)
    Console.ReadKey()


End Sub

End Module

评论部分指出发生异常的位置。

1 个答案:

答案 0 :(得分:-1)

您忘记初始化StringBuilders。您必须使用New keyword

Dim result As New System.Text.StringBuilder
Dim sb As New System.Text.StringBuilder