【问题标题】:Parsing text file to jagged array将文本文件解析为锯齿状数组
【发布时间】:2015-10-18 09:16:03
【问题描述】:

我有以下文件

3
2,3,4,5
6,7,8
9,10

并且我正在尝试将其转换为将其作为双精度锯齿数组传递。我的意思是,我试图将其存储为

double[][] myArray = {{2,3,4},{6,7},{9}}
double[] secondArray = {5,8,10}

我已经能够获取从文件中读取的值,但我被困在两件事上。

  1. 如何将值转换为双精度数组?
  2. 如何将最后的元素存储到新数组中?

我面临错误,因为我的数组包含逗号分隔的值,但我怎样才能将单个值转换为双精度值?我还是 Java 新手,所以我不知道所有的内置方法。

这是我目前所拥有的

public double[] fileParser(String filename) {

    File textFile = new File(filename);
    String firstLine = null;
    String secondLine = null;
    String[] secondLineTokens = null;

    FileInputStream fstream = null;
    try {
        fstream = new FileInputStream(filename);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
    try {
        firstLine = br.readLine(); // reads the first line
        List<String> myList = new ArrayList<String>();
        while((secondLine = br.readLine()) != null){
            myList.add(secondLine);
            //secondLineTokens = secondLine.split(",");

        }

        String[] linesArray = myList.toArray(new String[myList.size()]);
        for(int i = 0; i<linesArray.length; i++){
            System.out.println("tokens are: " + linesArray[i]);
        }

        double[] arrDouble = new double[linesArray.length];
        for(int i=0; i<linesArray.length; i++)
        {
           arrDouble[i] = Double.parseDouble(linesArray[i]); #error here
        }



    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

【问题讨论】:

    标签: java jagged-arrays


    【解决方案1】:

    看起来第一行给出了文件其余部分的行数。您可以利用它预先制作数组,如下所示:

    int n = Integer.parseInt(br.readLine());
    double a[][] = new double[n][];
    double b[] = new double[n];
    for (int i = 0 ; i != n ; i++) {
        String[] tok = br.readLine().split(",");
        a[i] = new double[tok.length-1];
        for (int j = 0 ; j != a[i].length ; j++) {
            a[i][j] = Double.parseDouble(tok[j]);
        }
        b[i] = Double.parseDouble(tok[tok.length-1]);
    }
    

    同样,您可以使用String.split 方法找出要添加到锯齿状数组中的条目数。这样代码就变得更短了,因为你可以预先分配所有的数组。

    Demo.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-22
      • 2013-07-01
      • 2013-06-21
      • 2011-09-13
      • 1970-01-01
      相关资源
      最近更新 更多