将 .txt 文件中的信息存储为变量

Store info from .txt file as variables

我正在尝试让我的代码从文本文件中读取并将其中的内容存储为变量..strings 和 double...以供以后使用。我可以毫无问题地获取 return 信息。

这是 .txt 文件中的内容:

circle 5
triangle 3
square 10
sphere 5
cube 4
tetrahedron 8

对于我的代码,我有:

            BufferedReader reader;
        try {
            reader = new BufferedReader(new FileReader(
                    "src/Data.txt"));

            String line = reader.readLine();
            while (line != null) {
                System.out.println(line);
                // read next line
                line = reader.readLine();
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

据我所知,构造变量名是不可能的。您不能读取 "circle" 并将其分配为变量名。您可以将它们存储为 [key,value] 对,使用 HashMap<String,Double> 将它们存储为一对。

第一部分是拆分行,使用 String.split 来分隔变量名称和值。如果事先知道文本文件中需要哪些变量,则可以声明这些变量并使用 switch 语句来确定读取名称对应于哪个变量,并相应地分配值。否则,可以使用 HashMap 或类似的东西来存储在文件中找到的名称和值。

将您的文本内容存储在哈希映射中,在下面的代码中,我将其命名为"vars"。 hashMap vars 包含您的变量作为键值对。 如果您需要获取任何变量的值,您只需编写:

    vars.get(key);

例如,要获取圆的值,您可以这样写:

     vars.get("circle");

这是您使用哈希图修改代码以存储变量后的代码。

    BufferedReader reader;
    HashMap<String,Double> vars = new HashMap<>();
    try {
        reader = new BufferedReader(new FileReader(
                "src/Data.txt"));
        String line = reader.readLine();
        while (line != null) {
            System.out.println(line);
            String[] lineVars = line.split(" ");
            vars.put(lineVars[0],Double.parseDouble(lineVars[1]));
            // read next line
            line = reader.readLine();

        }
        reader.close();
    }catch (IOException e) {
        e.printStackTrace();
    }