[这是2018年《代码出现》第1天的第一个挑战(链接:https://adventofcode.com/2018/day/1)
因此,我试图创建一个程序,读取一长串正负数(例如+ 1,-2,+ 3等),然后将它们加起来以创建总数。我研究了Visual Basic中文件处理的一些方法,并提出了以下方法:
Sub Main()
Dim objStreamReader As StreamReader
Dim strLine As String = ""
Dim total As Double = 0
objStreamReader = New StreamReader(AppDomain.CurrentDomain.BaseDirectory & "frequencies.txt")
strLine = objStreamReader.ReadLine
Do While Not strLine Is Nothing
Console.WriteLine(strLine)
strLine = objStreamReader.ReadLine
total += strLine
Loop
Console.WriteLine(total)
objStreamReader.Close()
Console.ReadLine()
End Sub
这里是数字列表的链接:https://adventofcode.com/2018/day/1/input
这不是语法错误,而是逻辑错误。答案是错误的,但我似乎无法弄清楚哪里!我试图从每个数字中删除符号,但是在编译时会抛出NullException错误。
到目前为止,我已经给出了答案549,但Advent of Code Webiste拒绝了。有什么想法吗?
通过使用File.ReadLines(fileName)
而不是StreamReader
使您的生活更轻松。使用Path.Combine
代替字符串串联来创建路径。 Path.Combine
负责添加缺少的\
或删除多余的等。
您的文件末尾可能包含多余的空行,该行不会转换为数字。使用Double.TryParse
在累计之前请确保您有一个有效的数字。无论如何,您都应该有Option Strict On
来强制进行明确的转换。
Dim fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "frequencies.txt")
Dim total As Double = 0
For Each strLine As String In File.ReadLines(fileName)
Console.WriteLine(strLine)
Dim n As Double
If Double.TryParse(strLine, n) Then
total += n
End If
Next
Console.WriteLine(total)
Console.ReadLine()