【问题标题】:Function to read an array list from file and display on the screen从文件中读取数组列表并显示在屏幕上的函数
【发布时间】:2021-04-25 02:10:04
【问题描述】:

我正在尝试编写一种方法来从文件中读取数组列表,然后将其显示在屏幕上,但最终无法正常工作。这是我正在使用的方法:

说明:

  • Point 类包含构造函数、getter、setter、toString()
  • PrintPoint 类包含构造函数、打印方法和从文件读取方法
  • 要测试的TestPoint 类

点类

public class Point {
    
    private double x;
    private double y;
    private String name;
    
    public Point(String name, double x, double y){
        this.name = name;
        this.x = x;
        this.y = y;
    }
    
    //setter and getter
    
    @Override
    public String toString(){
        return this.name + "[" + this.x + ", " + this.y + "]";
    }
}

PrintPoint 类

import java.util.*;
import java.io.*;
public class PrintPoint {
    
    private ArrayList<Point> pointList;
    
    //Constructor
    public PrintPoint(String path) throws FileNotFoundException{
      pointList = getPointFromFile(path);
    }
    
    //Print method
    public void printPointList(){
      for(Point p : pointList){
        System.out.println(p);
      }
    }

    //Read from file method
    public ArrayList<Point> getPointFromFile(String path) throws FileNotFoundException{
        try {
            Scanner myReader = new Scanner(new File(path));
            ArrayList<String> list = new ArrayList<String>();
            while (myReader.hasNextLine()) {
                list.add(myReader.nextLine());
            }
            myReader.close();
        } catch (FileNotFoundException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
        return new ArrayList<Point>();
    }
}

TestPoint 类:

import java.util.*;
import java.io.*;
public class TestPoint {
    public static void main(String[] args) throws FileNotFoundException{
        PrintPoint a = new PrintPoint("arraylist.txt");
        a.printPointList();
    }
}

arraylist.txt

A,3,4
B,5,6
C,7,8

我想打印数组列表但它不起作用(没有错误只是不打印)。

已更新:我已将问题更新为另一个要求。

【问题讨论】:

  • 您从 getPointFromFile() 方法返回一个空的 ArrayList
  • 您是否使用 Eclipse 来自动完成您的功能?因为如果您忘记了return,Eclipse 会准确地建议您这样做。我建议不要一开始就过度依赖你的 IDE,因为基于对代码的有限理解,它通常会给出糟糕的建议,尤其是在类型系统传达很少信息的 Java 等语言中。

标签: java arraylist readfile


【解决方案1】:

您从 getPointFromFile() 方法返回一个空的 ArrayList,因此它不会在控制台输出上打印任何内容。

您已从文件中读取数据,但未构造 Point 对象。我不知道arraylist.txt的数据是什么,有一个样本给你:

    //Read from file method
    public ArrayList<Point> getPointFromFile(String path) throws FileNotFoundException {
        ArrayList<Point> result = new ArrayList<>();
        try {
            Scanner myReader = new Scanner(new File(path));
            // ArrayList<String> list = new ArrayList<String>();
            while (myReader.hasNextLine()) {
                // list.add(myReader.nextLine());
                String ps = myReader.nextLine();
                String[] split = ps.split(",");
                Point point = new Point(Double.parseDouble(split[0]),Double.parseDouble(split[1]));
                result.add(point);
            }
            myReader.close();
        } catch (FileNotFoundException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
        return result;
    }

arraylist.txt:

10,20
34,56
199,23

控制台输出:

[10.0, 20.0]
[34.0, 56.0]
[199.0, 23.0]

【讨论】:

    【解决方案2】:

    您需要将文件arraylist.txt 中的文本行转换为Point 对象。

    下面是 PrintPoint 类的代码,因为这是我唯一更改的类。

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.ArrayList;
    import java.util.Scanner;
    
    public class PrintPoint {
        private ArrayList<Point> pointList;
    
        // Constructor
        public PrintPoint(String path) throws FileNotFoundException {
            pointList = getPointFromFile(path);
        }
    
        // Print method
        public void printPointList() {
            for (Point p : pointList) {
                System.out.println(p);
            }
        }
    
        // Read from file method
        public ArrayList<Point> getPointFromFile(String path) throws FileNotFoundException {
            ArrayList<Point> list = new ArrayList<Point>();
            try (Scanner myReader = new Scanner(new File(path))) {
                while (myReader.hasNextLine()) {
                    String line = myReader.nextLine();
                    String[] fields = line.split(",");
                    String name = fields[0];
                    double x = Double.parseDouble(fields[1]);
                    double y = Double.parseDouble(fields[2]);
                    Point pt = new Point(name, x, y);
                    list.add(pt);
                }
            }
            return list;
        }
    }
    
    • 注意上面的代码使用try-with-resources
    • 如果你声明方法getPointFromFile抛出FileNotFoundException,那么你不应该在方法中处理它。删除方法声明中的throws FileNotFoundException 或删除try-catch。在上面的代码中,我删除了try-catch

    以下是我运行上述代码时得到的输出。

    A[3.0, 4.0]
    B[5.0, 6.0]
    C[7.0, 8.0]
    

    或者,如果您至少使用 Java 8,则可以使用 streams API

    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.util.List;
    import java.util.stream.Collectors;
    
    public class PrintPoint {
        private List<Point> pointList;
    
        // Constructor
        public PrintPoint(String path) throws IOException {
            pointList = getPointFromFile(path);
        }
    
        // Print method
        public void printPointList() {
            for (Point p : pointList) {
                System.out.println(p);
            }
        }
    
        public List<Point> getPointFromFile(String path) throws IOException {
            Path p = Paths.get(path);
            return Files.lines(p)
                        .map(line -> {
                            String[] fields = line.split(",");
                            return new Point(fields[0],
                                             Double.parseDouble(fields[1]),
                                             Double.parseDouble(fields[2]));
                        })
                        .collect(Collectors.toList());
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-01
      • 1970-01-01
      • 2021-04-06
      相关资源
      最近更新 更多