繁体   English   中英

如何从文本文件中读取数字并将其“使用MATLAB或JAVA”保存在数组中?

[英]how to read digits from text file and save it in an array “using MATLAB or JAVA”?

我有一点点变化的类似问题,那就是:

我的文本文件包含大量不同大小的行“即,并非所有行的长度都相同”,每行仅包含整数。

例如A.txt =

4 6 4 1 2 2 5 7 7 

0 9 5 5 3 2 43 3 32 9 0 1 3 1

3 4 5 6 7 4  

34 5 8 9 0 7 6 2 4 5 6 6 7 5 4 3 2 21 4 9 8 4 2 1 5 

我想将这些整数放入数组中,以便每个整数将成为数组中的一个元素,并从“重叠”中保存行,即我需要保持每一行不变。

有人可以帮我吗?

a = dlmread('a.txt')

a =

第1至21栏

 4     6     4     1     2     2     5     7     7     0     0     0     0     0     0     0     0     0     0     0     0
 0     9     5     5     3     2    43     3    32     9     0     1     3     1     0     0     0     0     0     0     0
 3     4     5     6     7     4     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0
34     5     8     9     0     7     6     2     4     5     6     6     7     5     4     3     2    21     4     9     8

第22至25栏

 0     0     0     0
 0     0     0     0
 0     0     0     0
 4     2     1     5

我将执行以下操作:

1)为每行创建一个新的数组

2)从文件一次读取一行

3)用“空格”字符分隔每一行

4)迭代从拆分操作获得的String [],将每个值传递给Integer.parseInt(value);

5)将值存储在数组中;

6)读取下一行时,创建新数组以存储新行的值。

您可以使用Scanner一次读取一行数据,并将数字存储在List ,例如ArrayList

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

public class Numbers
{
  public static void main(String[] args) throws FileNotFoundException
  {
    Scanner data = new Scanner(new File("A.txt"));
    List<List<Integer>> ints = new ArrayList<List<Integer>>();

    while (data.hasNextLine()) {
      List<Integer> lineInts = new ArrayList<Integer>();
      Scanner lineData = new Scanner(data.nextLine());

      while (lineData.hasNextInt()) {
        lineInts.add(lineData.nextInt());
      }

      ints.add(lineInts);
    }

    System.out.println(ints);
  }
}

此代码打开文件以供读取,并创建一个二维ArrayList 外部列表包含文件中每一行的列表。 内部列表在相应的行上包含整数。 请注意,空行导致空列表。 另外,与上面显示的代码不同,您将必须正确处理任何IO异常。

如果您确实想要二维数组而不是ArrayList的整数,则必须调用toArray或更改上面的代码。 留给读者练习。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM