Java : 将 CSV 读入链表(稍加改动)

Java : Reading CSV to Linked List (with a twist)

我是编程新手,正在向 Core Java 学习 Java 自己。

这本书提到了几行关于读取 Java 中的 csv 文件并将其内容存储到 data-structure 中的内容。

所以在上网时,我遇到了以下问题:

  • There is a school which has the following actors : Faculty , Staff and Students

  • Faculty has the following attributes : Name , Phone Number , E-Mail ID Address , Department , No. of Research Papers

  • Students has the following attributes : Name , Phone Number , E-Mail ID , Address , Roll No. , GPA

  • Staff has the following attributes : Name , Phone Number , E-Mail ID , Address , Department , Salary

  • Now , the all this data is stored in a single csv file in the following manner :

Student,Harry Potter,9999999,hp@hogwarts.magic,Hogsmeade Street,1,4.0

Staff,Argus Filch,888888,arg@mrsnorris.com,Hogwarts,Cleaning,5000

Faculty,Snape,555555,snape@snivellus.com,Hogwarts,Potions,40000

.
.
.
.
  • Now , I need to read the data from the cs file , in Java , and store it into a linked list such in the following order : Faculty Records followed by Staff Records followed by Student Records

我的代码:

到目前为止我写的代码是:

import java.io.*;
import java.util.*;

public class readCSV {
  public static void main(String[] args) throws FileNotFoundException
  {
   
    Scanner scanner = new Scanner(new File("CSV.csv"));
    scanner.useDelimiter(",");
     
    
    while (scanner.hasNext())
    {
        // Read the tokens and store them into a Linked List 
    }
     
    
    scanner.close();
  }
}

我的问题:

有人可以帮助我吗?我不想使用任何库来解析 csv,也想从头开始制作我自己的链表——这将是一个很好的做法

My main problem is to read from csv and store the data into a linked list . An illustrative code snippet would go a long way

免责声明:这不是作业题。我在自学Java

对于链表,我建议阅读 Robert Sedgewick 的 Algorithm 一本书。 (如果 a) 你知道一些 Java 并且 b) 你知道链表是​​如何工作的,那么实现链表本身不会太难。)我希望网络上也有很多例子。

自己写了链表实现(学习用):扔掉,不要在实际程序中使用。严重地。现有的库实现会更好;编写真实世界的集合库是一项严肃的工作。

如果您的数据(文本)可以包含逗号和引号 而不是 CSV 定界符(在实际数据中通常如此),那么解析 CSV 比听起来更复杂。

然而,天真的实现可能是:

  • 使用 LineNumberReader.
  • 打开文件
  • 循环调用 readLine(),直到返回 null(不再有行)。
  • line.split(",").
  • 拆分读取的每一行
  • 处理每一行的字段。

您可以像这样解析文件:

Scanner scanner = new Scanner(new File("CSV.csv"));
while (scanner.hasNextLine()) {
    String line = scanner.nextLine();
    if (line.isEmpty()) {
        continue;
    }
    String[] parts = line.split(",");
    String name = parts[1];
    String number = parts[2];
    String email = parts[3];
    String address = parts[4];
    switch (parts[0]) {
    case "Faculty":
        String department = parts[5];
        String papers = parts[6];
        // add to list
        break;
    case "Student":
        String roll = parts[5];
        String gpa = parts[6];
        // add to list
        break;
    case "Staff":
        String department = parts[5];
        String salary = parts[6];
        // add to list
        break;
    }
}