2015-11-04 107 views
0

我已經創建了一個間隔在兩者之間的文本文件。所以我不知道如何讀入文件並添加數字。它應該基本上增加數字並給出總數。我很困難。我認爲你需要創建一個循環和另一個變量,但我不知道在哪裏添加這個。 在此先感謝: 進口System.IO 模塊模塊1閱讀加整數VB

Sub Main() 
    Dim objStreamReader As StreamReader 
    Dim strLine As String 
    Dim filename As String 
    Console.WriteLine("This program will add up all the numbers in this program.") 
    Console.WriteLine("Please type in the name of the file to view.") 
    filename = Console.ReadLine() 
    'Pass the file path and the file name to the StreamReader constructor. 
    objStreamReader = New StreamReader("C:\Users\Oliver\Documents\Computing\" + filename + ".txt") 
    'Read the first line of text. 
    strLine = objStreamReader.ReadLine 
    'Continue to read until you reach the end of the file. 
    Do While Not strLine Is Nothing 
     'Write the line to the Console window. 
     Console.WriteLine(strLine) 
     'Read the next line. 
     strLine = objStreamReader.ReadLine 
    Loop 
    objStreamReader.Close() 
    Console.Read() 
End Sub 

前端模塊

回答

0

不知道你有什麼樣的數字在你的文件,但你可以試試這個。此外,不是先讀一行然後循環,只是循環讀取行,並隨時保持行程總數:

Dim objStreamReader As StreamReader 
Dim strLine As String 
Dim filename As String 
Dim total as Integer 

Console.WriteLine("This program will add up all the numbers in this program.") 
Console.WriteLine("Please type in the name of the file to view.") 
filename = Console.ReadLine() 

'Pass the file path and the file name to the StreamReader constructor. 
objStreamReader = New StreamReader("C:\Users\Oliver\Documents\Computing\" + filename + ".txt") 

Do While Not objStreamReader.EndOfStream 
    'Read line. 
    strLine = objStreamReader.ReadLine 

    'Write the line to the Console window. 
    Console.WriteLine(strLine) 

    'If the line has data, add its value to total 
    if strLine.Trim.length > 0 then 
     total += CInt(strLine.Trim) 
    end if 
Loop 
objStreamReader.Close() 
Console.WriteLine("Total: " & total) 
Console.Read()