从输入文件中获取值并逐行添加到整数数组 (java)



本质上我有一个整数行文件。每行有 9 位数字。我想读取文件。然后将每一行输入到其数组中。我希望数组每次都相同。因为我将对从第一行创建的数组进行一些处理。然后使用不同的行处理相同的数组。

我的输入文件如下:

8 5 3 8 0 0 4 4 0
8 5 3 8 0 0 4 2 2

我当前使用的代码是:

 BufferedReader br = new BufferedReader(new FileReader("c:/lol.txt"));
            Scanner sc = new Scanner(new File("c:/lol.txt"));
            String line;
            while (sc.hasNextLine()){
                line = sc.nextLine();
                int k = Integer.parseInt(line);

现在显然我应该做更多的事情,我只是不确定该怎么做。

任何帮助将不胜感激。

尝试:

import java.util.Scanner;
import java.io.File;
public class Test {
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(new File("c:/lol.txt"));
        while (sc.hasNext()) {
            String line = sc.nextLine();
            // get String array from line
            String[] strarr = line.split(" "); // attention: split expect regular expression, not just delimiter!
            // initialize array
            int[] intarr = new int[strarr.length];
            // convert each element to integer
            for (int i = 0; i < strarr.length; i++) {
                intarr[i] = Integer.valueOf(strarr[i]); // <= update array from new line
            }
        }
    }
}

当然,您应该处理异常来传递它。

最新更新