2015-11-06 22 views
0

我很努力使這個元音計數器正常工作。我應該可以輸入文件(我是否正在輸入權限)應該讀取文本文件(它沒有),然後計算元音。另外,如果我能夠讓它計算單詞的數量,但這不是必需的。 錯誤代碼表示變量myline已在當前塊中聲明。 ??提前致謝。在VB中破壞的元音計數器

下面是代碼:

Imports System.IO 

Module Module1 

    Sub Main() 
     Dim vowel As Integer = 0 
     Dim Text, myline As String 
     Dim objStreamReader As StreamReader 
     objStreamReader = New StreamReader("H:\vowelcounter.txt") 
     Dim myline = objStreamReader 
     Text = objStreamReader.ReadLine() 

     Do While Not Text Is Nothing 
      Console.WriteLine(text) 
      For x = 0 To Text.Length 
       If x = "a" Then 
        vowel = vowel + 1 
       End If 
       If x = "e" Then 
        vowel = vowel + 1 
       End If 
       If x = "i" Then 
        vowel = vowel + 1 
       End If 
       If x = "o" Then 
        vowel = vowel + 1 
       End If 
       If x = "u" Then 
        vowel = vowel + 1 
       End If 
       If x = "A" Then 
        vowel = vowel + 1 
       End If 
       If x = "E" Then 
        vowel = vowel + 1 
       End If 
       If x = "I" Then 
        vowel = vowel + 1 
       End If 
       If x = "O" Then 
        vowel = vowel + 1 
       End If 
       If x = "U" Then 
        vowel = vowel + 1 
       End If 
      Next 

     Loop 
     Console.ReadLine() 
    End Sub 

End Module 
+0

'x'不會等於一個字符,因爲它是一個介於0和'text.length'之間的整數。 –

+0

您也正在使用實現「iDisposable」的對象,並且在代碼結束時尚未關閉它。你需要使用'Using'語句。 –

+0

只要在執行循環迭代時Text不爲Nothing,While循環就會無限次地運行,因爲它在整個循環中都沒有改變。 –

回答

2

錯誤代碼說,變量MYLINE在 當前塊已經聲明。

是的,這就是:

Dim Text, myline As String ' <----- HERE 
Dim objStreamReader As StreamReader 
objStreamReader = New StreamReader("H:\vowelcounter.txt") 
Dim myline = objStreamReader ' <----- and HERE 

所以重命名第一個字符串變量或StreamReader(你爲什麼需要兩個一個呢?)。

你可以更達到元音計數器簡單:

Dim text As String = System.IO.File.ReadAllText("H:\vowelcounter.txt") 
Dim vowels = From c In text Where "aeiouAEIOU".Contains(c) 
Dim vowelCount As Int32 = vowels.Count() 

你可以得到字計數這樣:

Dim words = text.Split() 
Dim wordCount As Int32 = words.Length 

這是假設只有空格,製表符或新行字符是分隔符。如果您還需要其他字符:

Dim wordDelimiter As Char() = {" "C, ControlChars.Tab, ","C, "."C, "!"C, "?"C, _ 
";"C, ":"C, "/"C, "\"C, "["C, "]"C, _ 
"("C, ")"C, "<"C, ">"C, "@"C, """"C, _ 
"'"C} 
Dim words = text.Split(wordDelimiter, StringSplitOptions.None) 
+0

謝謝,但我需要了解此之前,進展到更難的東西。我需要刪除哪一個?正如你所看到的,我正在輸入一個文件,所以我輸入myline作爲字符串。 – user5423489

+0

我該刪除哪一個。我以字符串的形式刪除第一層myline,它現在出現了這個問題:在Microsoft.VisualBasic.dll中發生未處理的類型爲「System.InvalidCastException」的異常。 附加信息:從字符串「a」轉換爲類型「Double」不是有效。它還表示split不是文本的成員。 – user5423489

+0

@ user5423489:這取決於你。 Dim myline = objStreamReader'顯然是錯誤的。爲什麼要將StreamReader稱爲'myLine'?這一切都是關於可讀性的。你見過我更簡單的方法嗎? –