将文本读入二维数组

Reading text into a 2D array

我需要能够读取文本文件,然后将其放入二维数组中。我在这里看到的所有问题都使用 ArrayLists,这是我们不允许的。 我的文本文件如图所示。

Bananas, 5, 5
Apples, 5, 5
Steak, 5, 10

第一个值为名称,第二个值为数量,第三个值为价格。我想将它们放在一个包含 30 个项目的数组 inventory[30][3] 中,具有我提到的三个特征。如果这太基础了,我深表歉意,我尝试了很多 Google 和 YouTube,但找不到简单的答案。

这是我用来获取您想要的数组的代码:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadFileIntoArray {
    public static void main(String[] args) {
        String[][] inventory = new String[30][3];
        try {
            File myObj = new File("filename.txt");
            Scanner myReader = new Scanner(myObj);
            int i = 0;
            while (myReader.hasNextLine()) {
                String[] traits = myReader.nextLine().split(",");
                for(int j = 0; j < traits.length; j++){
                    inventory[i][j] = traits[j];
                }
                i++;
            }
            // do stuff here with inventory
            myReader.close();
        } catch (FileNotFoundException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}

这里有几点需要注意。

首先是拆分,它以逗号分隔文本文件的每一行。根据文件的格式,您可能需要添加一个 space 以免特征上有尾随的白色 space:split(", ")

接下来我遍历了 traits 字符串数组,这可能有点矫枉过正,因为永远只有 3 个条目,但这意味着如果需要,该数组可以扩展到更多特征未来。

最后是i变量。这是跟踪循环迭代所必需的。