简体   繁体   English

Visual Basic分配的并行数组

[英]parallel array for Visual Basic assignment

For this assignment I am being ask to "Read the file into parallel string arrays corresponding to the columns in the file". 对于此分配,我被要求“将文件读入与文件中的列相对应的并行字符串数组中”。 The columns in the file are: "P_CODE" "P_DESCRIPT" "P_INDATE" "P_QOH" "P_MIN" "P_PRICE". 文件中的列为:“ P_CODE”“ P_DESCRIPT”“ P_INDATE”“ P_QOH”“ P_MIN”“ P_PRICE”。 My question is "What is a parallel array?" 我的问题是“什么是并行数组?” and what does it look like. 看起来像什么 I took a guess at how I would imagine it might done but I'm not sure I'm on the right track. 我猜想我会怎么做,但是我不确定自己是否走对了。

  ========== project Inventory ========== 

Selecting the Read button shall cause the contents of the InventoryData.txt file to be read from your project's default folder. 选择读取按钮将导致从项目的默认文件夹中读取InventoryData.txt文件的内容。 The file does contain a column header line. 该文件确实包含列标题行。

Read the file into parallel string arrays corresponding to the columns in the file. 将文件读入对应于文件中各列的并行字符串数组。 After reading the file, close it. 读取文件后,将其关闭。 Display the contents of the file in the parallel arrays, including column titles, in the List box formatted using the Format() method. 在使用Format()方法设置格式的“列表”框中,显示并行数组中文件的内容,包括列标题。 Left and right align columns according to convention for their type of data. 根据惯例,将数据列左右对齐。 Hint: Set the Font property of you List Box to a nonproportional space font such as Courier. 提示:将列表框的Font属性设置为非比例空格字体,例如Courier。

Write the contents of the file in the parallel arrays, including column titles, to a file named InventoryDataOut.txt created in your project's default folder. 将并行数组中的文件内容(包括列标题)写入在项目的默认文件夹中创建的名为InventoryDataOut.txt的文件。 Delimit the columns with the pipe (|) symbol. 用竖线(|)分隔列。 Each inventory item to one line of output to the file. 每个库存项目以一行输出到文件。

This is what I have done so far. 到目前为止,这是我所做的。 I just started so this is not functioning code. 我刚开始,所以这不是功能代码。

 Private Sub btnRead_Click(sender As Object, e As EventArgs) Handles btnRead.Click

        Dim dirPath As String = "C:\Users\...\Inventory\"
        Dim filePath As String = dirPath & "InventoryData.txt"

        'Arrays
        Dim P_CODE As String()
        Dim P_DESCRIPT As String()
        Dim P_INDATE As String()
        Dim P_QOH As String()
        Dim P_MIN As String()
        Dim P_PRICE As String()


    ' Open file for reading

    Dim textIn As New StreamReader(
        New FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None))

    'Read in the lines of text into the String variables in the array;

    Dim i As Integer = 0
    Do While textIn.Peek <> -1
        Dim row As String = textIn.ReadLine
        Dim columns As String() = row.Split(CChar(" "))
        P_CODE(i) = columns(i)
        P_DESCRIPT(i) = columns(i)
        P_INDATE(i) = columns(i)
        P_QOH(i) = columns(i)
        P_MIN(i) = columns(i)
        P_PRICE(i) = columns(i)
        i = i + 1
    Loop


    '=====================================
    '- After reading the file, close it. 
    textIn.Close()

I get the following warning and error (for each array) : 我得到以下警告和错误(对于每个数组):

Warning 1 Variable 'P_CODE' is used before it has been assigned a value. 警告1在给变量'P_CODE'赋值之前,先使用它。 A null reference exception could result at runtime. 空引用异常可能在运行时导致。

Columns as independant arrays ? 列作为独立数组? :/ :/


One line answer : You're doing it right ! 一线回答: 您做对了


However : 但是:

  • there are simplier ways to do this (in terms of usage and readability - not performance) 有更简单的方法可以做到这一点(就用法和可读性而言,而非性能)
  • there are typos in your code. 您的代码中有错别字。

StackOverflow's main purpose is not to teach basic language reference, but help you overcome a specific problem with the appropriate coding (while keeping in mind an answer can't be an answer if it doesn't provide the elements to answer OP's question) StackOverflow的主要目的不是教授基本的语言参考,而是通过适当的编码帮助您克服特定的问题(同时请记住,如果答案没有提供回答OP问题的要素,那么答案就不是答案)

The error you stated is not really related to the question "what is a parallel array". 您说的错误与“什么是并行数组”这个问题并没有真正的关系。 "Variable used before it has been assigned a value" . “在为变量分配值之前使用的变量” Of course ! 当然 ! Your array is Null . 您的数组为Null The variable is declared but no instance of it has been created. 声明了变量,但尚未创建任何实例。 And Arrays are that strict in dotNet (unlike JavaScript) 数组在dotNet中是如此严格(与JavaScript不同)

What's your real question ? 您真正的问题是什么?
It's more related to "how should I assign values to (parallel) array(s)" and could be reformulated like "How to read string values stored in a text file in parallel arrays and write them back ?" 它与“我应该如何为并行数组分配值”更相关,可以像“如何读取并行数组中的文本文件中存储的字符串值并将其写回?”这样重新编写?

Homework questions usually disallows the use of alternative approaches (and sometimes such homework questions are downvoted) 作业问题通常不允许使用替代方法(有时这类作业问题被否决了)

Different approaches like (using a database with linq or) : 不同的方法,例如(使用带有linq的数据库或):


Use File.ReadAllLines() to know the number of lines right from the beginning... 使用File.ReadAllLines()从一开始就知道行数...

Declare your arrays top level : you won't be able to access them outside your btnRead Click otherwise. 在顶层声明数组 :您将无法在btnRead之外访问它们。否则,请单击。

Private P_CODE As String()
Private P_DESCRIPT As String()
' ...
Private P_PRICE As String()

Load the file content inside your btnRead Click... 将文件内容加载到btnRead Click中...

Dim AllLines As String() = File.ReadAllLines(filePath)
' ^^ the above will open and close the file XD

Dim Columns As String()

' Initialize your arrays...
ReDim(P_CODE, AllLines.Length - 1)
ReDim(P_DESCRIPT, AllLines.Length - 1)
' ...
ReDim(P_PRICE, AllLines.Length - 1)

' set each cell value.
For LineIndex As Int32 = 0 To P_CODE.Length - 1
    Columns = AllLines(LineIndex).Split(" "c)
    P_CODE(LineIndex) = Columns(0)
    P_DESCRIPT(LineIndex) = Columns(1)
    ' ...
    P_PRICE(LineIndex) = Columns(5)

    ' Hey ! Your File Datas are ordered horizontaly,
    ' so Columns must be indexed from 0 to 5 
    ' instead of you "i" in your code in order 
    ' to correctly feed your parallel arrays
Next

Your teacher wanna force you to open the file using StreamReader and teach you to not forget to close the file... and use StreamReader.ReadLine() ... Okay..! 您的老师想强迫您使用StreamReader打开文件,并教您不要忘记关闭文件...并使用StreamReader.ReadLine() ...好吧..!

' ...

Dim LineIndex As Int32 = 0
Dim textIn As New StreamReader(filePath)
' ^^ why do you bother using a FileStream ?
Dim Row As String = textIn.ReadLine()
Dim Columns As String()

Do While row IsNot Nothing
    Redim Preserve P_CODE(LineIndex)
    Redim Preserve P_DESCRIPT(LineIndex)
    ' ...
    Redim Preserve P_PRICE(LineIndex)

    Columns = Row.Split(" "c)

    P_CODE(LineIndex) = Columns(0)
    P_DESCRIPT(LineIndex) = Columns(1)
    ' ...
    P_PRICE(LineIndex) = Columns(5)

    Row = textIn.ReadLine()
    LineIndex = LineIndex + 1
Loop

textIn.Close() ' Voila !

' /!\ Add at least a Try Catch enclosing your Do/Loop if you're lazy.

Tell your teacher you're gonna use Using because he forces you to use StreamReader.Peek() (is .Peek() necessary ?) 告诉您的老师您将使用Using因为他强迫您使用StreamReader.Peek() (.Peek()是否必要?)

Using textIn As New StreamReader(filePath)
    Dim LineIndex As Int32 = 0
    Dim Columns As String()

    Do While textIn.Peek() <> -1
        Redim Preserve P_CODE(LineIndex)
        Redim Preserve P_DESCRIPT(LineIndex)
        ' ...
        Redim Preserve P_PRICE(LineIndex)

        Columns = textIn.ReadLine().Split(" "c)

        P_CODE(LineIndex) = Columns(0)
        P_DESCRIPT(LineIndex) = Columns(1)
        ' ...
        P_PRICE(LineIndex) = Columns(5)

        LineIndex = LineIndex + 1
    Loop
End Using ' StreamReader closed ! XD

No ! 不行 Don't ask me to use a FileStream ! 不要问我使用FileStream I would if I know the size of each data chunck in the file and I'm using structures of fixed size. 如果我知道文件中每个数据块的大小,并且我正在使用固定大小的结构,那我就可以了。 FileStream is best used when manipulating large buffer of datas as it directly works in memory with appropriate asynchronous checks. FileStream是处理大型数据缓冲区时的最佳选择,因为它可以通过适当的异步检查直接在内存中工作。

Just to read lines ? 只是看台词? No ! 不行 For this part, read the documentation . 对于这一部分,请阅读文档


String.Format() 的String.Format()

Dim Row As String

MyListBox.Items.Clear()
For LineIndex As Int32 = 0 To P_CODE.Length - 1
    Row = String.Format("{0, -12}{1,-16}{2,10}{3,10}{4,8}{5,10}", _
              P_CODE(LineIndex), _
              P_DESCRIPT(LineIndex), _
              P_INDATE(LineIndex), _
              P_QOH(LineIndex), _
              P_MIN(LineIndex), _
              P_PRICE(LineIndex))
    MyListBox.Items.Add(Row)
Next

Write file to InventoryDataOut.txt.. 将文件写入InventoryDataOut.txt。

Dim Separator As String = "|"
Dim FileContent As New StringBuilder() ' System.Text

' Prepare File content...
If P_CODE.Length > 0 Then
    For LineIndex As Int32 = 0 To P_CODE.Length - 2 ' Note the -2
        FileContent.AppendLine(String.Format("{0}{6}{1}{6}{2}{6}{3}{6}{4}{6}{5}", _
              P_CODE(LineIndex), _
              P_DESCRIPT(LineIndex), _
              P_INDATE(LineIndex), _
              P_QOH(LineIndex), _
              P_MIN(LineIndex), _
              P_PRICE(LineIndex), _
              Separator)))
    Next
    FileContent.Append(String.Format("{0}{6}{1}{6}{2}{6}{3}{6}{4}{6}{5}", _
              P_CODE(P_CODE.Length - 1), _
              P_DESCRIPT(P_CODE.Length - 1), _
              P_INDATE(P_CODE.Length - 1), _
              P_QOH(P_CODE.Length - 1), _
              P_MIN(P_CODE.Length - 1), _
              P_PRICE(P_CODE.Length - 1), _
              Separator)))

    ' This ensures we don't add unnecessary line at the end of the file
    ' which would make your application explode !

    ' best move is to check for null entries upon file parsing.
    ' (Again : File.ReadAllLines() + RemoveEmptyString parameter to keep it simple)

End If

' Create your file using the stream object 
' you're forced to use by your teacher,
' then dump the the content of your StringBuilder inside like
MyDummyStream.Write(FileContent.ToString())

' And close you dummy stream or use Using XD

Does your teacher has a bunch of CSV-like files which needs separator conversion from space to pipe ? 您的老师是否有一堆类似CSV的文件,需要从空间到管道的分隔符转换?

It seems he's just lazy to write the code to dispatch each column in several parallel arrays for display or other purpose. 似乎他只是懒惰地编写代码以将几列分派到几个并行数组中以用于显示或其他目的。 Or why would you use the space as separator upon loading the content of your file while using pipe instead to write them ? 还是为什么在使用管道代替写入内容时,在加载文件内容时使用空格作为分隔符?
If its a typo , just don't bother reading this. 如果是错别字那就别再读了。 Otherwise, your teacher is just asking you to create a small program that converts the space separator to pipe... (while giving you the mission to learn manipulate (parallel) arrays, streams I/O, and String.Format) 否则,您的老师只是要您创建一个将空格分隔符转换为管道的小程序...(同时给您学习操作(并行)数组,流I / O和String.Format的任务)

.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM