vb.net - 来自文本文件的矩阵
问题描述
从文本文件中读取矩阵,文本文件的第一行包含矩阵的维度,接下来的行将包含由空格分隔的行的元素。我正在考虑使用它,但不知道如何从文本文件中获取。
Dim path = "z:matrix.txt"
Using reader As New IO.StreamReader(path)
Dim size = reader.ReadLine() ' read first line which is the size of the matrix (assume the matrix is a square)
Dim A(size - 1, size - 1) As Integer
Dim j = 0 ' the current line in the matrix
Dim line As String = reader.ReadLine() ' read next line
Do While (line <> Nothing) ' loop as long as line is not empty
Dim numbers = line.Split(" ") ' split the numbers in that line
For i = 0 To numbers.Length - 1
A(j, i) = numbers(i) ' copy the numbers into the matrix in current line
Next
j += 1 ' increment the current line
line = reader.ReadLine() ' read next line
Console.WriteLine(line)
Loop
End Using
3
1 3 5
2 4 6
7 8 9
解决方案
Dim path = "D:\matrix.txt"
Using reader As New IO.StreamReader(path)
Dim size = reader.ReadLine() ' read first line which is the size of the matrix (assume the matrix is a square)
Dim A(size - 1, size - 1) As Integer
Dim j = 0 ' the current line in the matrix
Dim line As String = reader.ReadLine() ' read next line
Do While (line <> Nothing) ' loop as long as line is not empty
Dim numbers = line.Split(" ") ' split the numbers in that line
For i = 0 To numbers.Length - 1
A(j, i) = numbers(i) ' copy the numbers into the matrix in current line
Next
j += 1 ' increment the current line
line = reader.ReadLine() ' read next line
Loop
A.Dump() ' print the matrix in LinqPad
End Using
文本文件示例:
3
1 3 5
2 4 6
7 8 9
没有 LinqPad 的修改代码:
Dim path = "d:\matrix.txt"
Dim A(,) As Integer
Using reader As New IO.StreamReader(path)
Dim size = reader.ReadLine() ' read first line which is the size of the matrix (assume the matrix is a square)
Redim A(size - 1, size - 1)
Dim j = 0 ' the current line in the matrix
Dim line As String = reader.ReadLine() ' read next line
Do While (line <> Nothing) ' loop as long as line is not empty
Dim numbers = line.Split(" ") ' split the numbers in that line
For i = 0 To numbers.Length - 1
A(j, i) = numbers(i) ' copy the numbers into the matrix in current line
Next
j += 1 ' increment the current line
line = reader.ReadLine() ' read next line
Loop
End Using
Console.WriteLine("Matrix A :")
Dim numberWidth As Integer = 2
Dim format As String = "D" & numberWidth
For i As Integer = 0 To A.GetUpperBound(0)
Console.Write("| ")
For j As Integer = 0 To A.GetUpperBound(1)
Console.Write("{0} ", A(i, j).ToString(format))
Next
Console.WriteLine("|")
Next
推荐阅读
- python - 从具有相同结构的字符串中分离不同的名称
- azure-ad-b2c - 什么是 UserJourney/PreserveOriginalAssertion
- html - 如果表只有一行,则表的不同 css
- arrays - 使用数组时方法'对象范围'_worksheet'失败
- python - 从包含python中字典的其他嵌套列表创建Python字典
- reactjs - 使用 React Redux 提交表单
- visual-studio - Visual Studio:多种解决方案或构建配置?
- java - 为什么我在这里得到 IllegalStateException?
- java - 找不到tools.jar
- wso2 - 如何在 WSO2IS 中从批量用户端点“https://localhost:9443/t/carbon.super/scim2/Bulk”添加组织、手机号、电子邮件