VB 2017中的单词和元音数量

问题描述 投票:0回答:2

我需要编写一个简单的控制台应用程序,它接受一个输入字符串,然后调用一个子例程来计算字符串中的单词数量和元音量。我写了这个,由于某种原因,它没有输出我在Console.Writeline代码中输入的文本。有关如何做到这一点的任何帮助?

Module Module1

    Sub Main()
        Dim Sentence As String
        Console.WriteLine("Sentence Analysis")
        Console.WriteLine()
        Console.WriteLine("Enter a sentence then press 'Enter'")
        Console.WriteLine()
        Sentence = Console.ReadLine()
        Sentence = Sentence.ToUpper
        Call Words(Sentence)
        Call Vowels(Sentence)
        Console.ReadLine()
    End Sub

    Sub Words(ByVal Input As String)
        Dim Count As Integer
        Dim Index As Short
        Dim Character As Char
        Do Until Index = Len(Input)
            Character = Input.Substring(Index)
            If Character = " " Then
                Count = Count + 1
            End If
        Loop
        Console.WriteLine("Your sentence contains {0} words.", (Count))
    End Sub

    Sub Vowels(ByVal Input As String)
        Dim Count As Integer
        Dim Vowels() As String = {"A", "E", "I", "O", "U"}
        Dim Index As Short
        Dim Character As Char
        Do Until Index = Len(Input)
            Character = Input.Substring(Index)
            If Character = Vowels(Index) Then
                Count = +1
            End If
        Loop
        Console.WriteLine("Your sentence contains {0} words.", (Count))
    End Sub
End Module
vb.net visual-studio visual-studio-2017 word-count
2个回答
3
投票

Words中,您有以下代码:

Do Until Index = Len(Input)

索引永远不会增加,因此无限循环。

Vowels也是同样的问题


0
投票

以下对您有什么帮助吗?

它不是查看句子是否包含元音,而是查看元音列表是否包含句子中的每个字符。

对于单词计数,它同样询问包含单个空格的字符串是否包含句子中的每个字符(在这种情况下,“单词计数”只是空格的计数,因此前导或尾随空格,或单词之间的额外空格,将被视为额外的单词,正如您的代码目前所做的那样)。

它还允许我们废除单独的方法调用,以及手动循环代码,正如您所看到的,它容易出现小错误(我个人建议在这种情况下使用For循环而不是Do Until循环,因为For循环被设计为自动递增索引)。

Sub Main()
    Console.WriteLine("Sentence Analysis")
    Console.WriteLine()
    Console.WriteLine("Enter a sentence then press 'Enter'")
    Console.WriteLine()

    Dim sentence As String
    sentence = Console.ReadLine()

    Dim vowel_count As Integer = sentence.Count(Function(c) "aeiou".Contains(Char.ToLower(c)))
    Dim word_count As Integer = sentence.Count(Function(c) " ".Contains(Char.ToLower(c)))

    Console.WriteLine("Your sentence contains {0} words.", word_count)
    Console.WriteLine("Your sentence contains {0} vowels.", vowel_count)        

    Console.ReadLine()
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.