• 3
  • 新人请关照

Java中怎样逐行读取文件信息为object并生成linked list?

### 大家好,我是刚学Java的小白,现在遇到问题需请教大神。我需要从一个.txt文件中逐行读取员工信息(id,name,salary),把每行信息存储成一个object,再把这些object(这些object 是SalariedEmployee class的 instance) 放在一个linked list(SalariedEmployeeList class)中。在 SalariedEmployeeList class中 建立一个 findByName method, 查找员工姓名,如果有该姓名,则返回该姓名所在的object。在main method中调用findByName,打印出该员工所有信息。

### 题目来源及自己的思路

### 相关代码
粘贴代码文本(请勿用截图)

txt.file如下:

1, Kelsey, 65000
2, Jake, 89000
3, Carlos, 105000
4, Clarence, 58000
5, Pacheco, 68000

SalariedEmployee class

public class SalariedEmployee {
// instance variable
    public int empId;
    public String name;
    public double salary;

    // constructor
    public SalariedEmployee(int empId, String name, double salary) {
        this.empId = empId;
        this.name = name;
        this.salary = salary;
    }
    // get methods
    public int getEmpId() {
        return empId;
    }

    public String getName(){
        return name;
    }

    public double getSalary(){
        return salary;
    }

SalariedEmployeeList

private static class Node {
        private SalariedEmployee element;
        private Node next;
        public Node(SalariedEmployee e, Node n) {
            element = e;
            next = n;
        }

        public SalariedEmployee getElement() { return element; }

        public Node getNext() { return next; }

        public void setNext(Node n) { next = n; }
      }

    // instance variables of the SinglyLinkedList
    private Node head = null;               
    private Node tail = null;               
    private int size = 0;                      
    public SalariedEmployeeList() { }              

    // access methods
    public int size() { return size; }
    public boolean isEmpty() { return size == 0; }
    public SalariedEmployee first() {             
        if (isEmpty()) return null;
        return head.getElement();
    }

    public SalariedEmployee last() {              
        if (isEmpty()) return null;
        return tail.getElement();
    }

    public void addFirst(SalariedEmployee e) {                
        head = new Node(e, head);              
        if (size == 0)
            tail = head;                           
        size++;
    }

    public void addLast(SalariedEmployee e) {                 
        Node newest = new Node(e, null);    
        if (isEmpty())
            head = newest;                         
        else
            tail.setNext(newest);                  
        tail = newest;                           
        size++;
    }

    public SalariedEmployee removeFirst() {                   
        if (isEmpty()) return null;              
        SalariedEmployee answer = head.getElement();
        head = head.getNext();                   
        size--;
        if (size == 0)
            tail = null;                          
        return answer;
    }

    public SalariedEmployee findByName(String name) {
        SalariedEmployeeList selist = new SalariedEmployeeList();
        for (int i = 0; i < selist.size; i++) {
            if (SalariedEmployeeList (selist.get(i)).getname == name);
                return selist.get(i);
            return null;
    }
}

    public void printList() {
        SalariedEmployee se = null;
        Node walk = head;
        while (walk != null) {
            se = walk.getElement();
            System.out.println("Employee id = " + se.getEmpId());
            System.out.println("Name = " + se.getName());
            System.out.println("Salary = " + se.getSalary());
            System.out.println();
            walk = walk.getNext();
        }
    }

main method

public class Hw3_Part2 {
    public static void main(String[] args) throws IOException {
        String content = new String();
        Scanner fileInput = new Scanner(new File("/Users/hw3_employees.txt"));
        LinkedList <String> selist = new LinkedList <String>();
        while(fileInput.hasNextLine()){
            content = fileInput.nextLine();
            selist.add(content);
        }
        System.out.println(selist);
        fileInput.close();
    }
}

### 你期待的结果是什么?实际看到的错误信息又是什么?

我遇到以下问题:
1、读取文件时把所有行的员工信息都变成了一整个linked list:
[1, Kelsey, 65000,2, Jake, 89000,3, Carlos, 105000,4, Clarence, 58000,5, Pacheco, 68000],这不是我想要的。我想要[[1, Kelsey, 65000],[2, Jake, 89000],[3, Carlos, 105000],[4, Clarence, 58000],[5, Pacheco, 68000]],怎样提取每名员工的信息变成SalariedEmployee class的一个object呢?

2、findByName method 中报错:“cannot resolve method "get" in SalariedEmployeeList“, .get()不是linked list中自带的吗?怎样解决?

我现在思路有点混乱,不知道该用什么方法。还请大神多多指点,手下留情,谢谢!

阅读 246
评论
    2 个回答

    梳理一下诉求:
    1、输入一个文本文件,一行一条记录,有三个属性:id,name,salary,由逗号隔开;
    2、逐行读取记录,将记录存放在SalariedEmployee对象中,所有记录存放于SalariedEmployeeList容器中,并提供根据name搜索记录的方法。


    核心代码如下:

    // 1.读取文本文件
    SalariedEmployeeList employeeList = new SalariedEmployeeList();
    try(BufferedReader br = new BufferedReader(new InputStreamReader(
    new FileInputStream("your text file path")))) {
        String line = null;
        while ((line = br.readLine()) != null) {
            // line为空或者记录不够就略过
            if(line.isEmpty()) {
                continue;
            }
            String[] fields = line.split(",");
            if(fields.length() != 3) {
                continue;
            }
            SalariedEmployee employee = new SalariedEmployee(Integer.parseInt(fields[0],
            fields[1], Double.parseDouble(fields[2]);
            employeeList.add(employee);
        }
    }
    
    // SalariedEmployeeList类
    // 从题主问题描述中没有看到这个类的声明,大体理解题主想要的意思是这个类本身就是一个容器,
    // 可以容纳SalariedEmployee对象,最后提供一个根据name来查询Employee的方法,因此我就直接
    // 将SalariedEmployeeList继承LinkedList,这样实现起来最快。
    public class SalariedEmployeeList extends LinkedList<SalariedEmployee> {
        // 其他代码省略...
        // 根据name进行SalariedEmployee查询
        public SalariedEmployee findByName(String name) {
            for(SalariedEmployee employee : this) {
                if(employee.getName().equals(name)) {
                    return employee;
                }
            }
            // 没有找到返回null
            return null;
        }
    }

    以上是代码的主要实现逻辑,应该是题主所想吧,如有问题,可以追问,望采纳,谢谢。

      一:

      LinkedList <String> selist = new LinkedList <String>();

      读取到文本信息后,遍历这个list,你会拿到单行:1, Kelsey, 65000 这样的文本,然后用逗号分割成数据,组装SalariedEmployee 就好了。伪代码:

      List<SalariedEmployee> employees = selist.stream().map(content-> {
          String result[] = content.spilt(,);
          SalariedEmployee employee = new SalariedEmployee();
          employee.setId(result[0]);
          .......
          return employee;
      }).collect(Collectors.toList());

      二:
      这里看不到你对SalariedEmployeeList 的实现,如果存在困惑的话,你可以直接让SalariedEmployeeList 继承下LinkedList

        撰写回答

        登录后参与交流、获取后续更新提醒

        相似问题
        推荐文章