首页 > 解决方案 > 如何创建一个使用数据引用保存 ArrayList 的类?

问题描述

我有一个包含此类信息的 30 mb txt 文档(其中,首先是日期、时间、百万分之一秒数、3 个用“;”分隔的价格和一个交易)文件:https://drive. google.com/file/d/1-ky0EM75xvDXdHBcFnZYjq7D9FwKy50M/view?usp=sharing

20200429 050000 2500000;8843;8841.75;8843;1

20200429 050000 5740000;8843;8841.75;8843;1

20200429 050000 5740000;8843.25;8841.75;8843.25;1

每个数据都存储在一个名为“Dato”的类中,并且有一个数据集合“ColeccionDatos”,其中引用了每个数据,但是,在创建实例并尝试读取文件“NQ20200429 -30.txt”时“其中包含所有信息,发生 Java.util.MismatchException 错误。我已经尝试了很长时间,但无法解决,感谢您的帮助。这是代码。

   public class Dato
{
    private String fecha;
    private String hora;
    private int diezmill;
    private double last;
    private int transaccion;

    public Dato (String fecha, String hora, double last, int trans){
        this. fecha = fecha;
        this. hora = hora;
        this. last = last;
        this. transaccion = transaccion;
    }

    public String getFecha(){
        return this.fecha;
    }

    public String getHora () {
        return this.hora;
    }

    public int getDiezmill () {
        return this. diezmill;
    }

    public double getLast () {
        return this. last;
    }

    public int getTransaccion () {
        return this.transaccion;
    }

    public String toString () {
        String ret = "";
        ret += fecha + "";
        ret += hora + "";
        ret += diezmill + "";
        ret += last + "";
        ret += transaccion + "";
        return ret;
    }
}

//第二个类的代码是

import java.util.ArrayList;
import java.io.*;
import java.util.Scanner;
public class ColeccionDatos
{
    protected ArrayList <Dato> al;

    public ColeccionDatos () {
        al = new ArrayList <> ();
    }

    public void leerActivo (String NombreActivoNQ) throws FileNotFoundException {
        Scanner archivo = new Scanner (new File (NombreActivoNQ)); //In this line the file is processed
        while (archivo.hasNextLine()){
            String linea = archivo.nextLine();   
            linea = linea.replace (";", " ");
            Scanner sl = new Scanner (linea);
            String fecha = sl.next();
            String hora = sl.next();
            int diezmill = sl.nextInt();
            double bid =sl.nextDouble();
            double ask = sl.nextDouble(); //this line throws the exception
            double last = sl.nextDouble();
            int transaccion = sl.nextInt();
            Dato d = new Dato (fecha, hora, last, transaccion);
            al.add(d);
        }
    }
}

标签: javaarraylistextendstxt2tags

解决方案


你在 Dato 构造函数中犯了一个错误,它应该this. transaccion = trans;this. transaccion = transaccion;

您能否分享您的 NQ20200429 -30.tx 文件,因为我使用给定的示例运行您的代码并且我没有遇到 Java.util.MismatchException 错误,可能输入文件有问题


推荐阅读