首页 > 解决方案 > 将 txt 文件中的项目附加到数组

问题描述

嘿,我刚开始学习如何编码。我正在使用 netbeans,我想将一些数据从 txt.file 传输到 java 中的数组中。这可能是一个非常简单的修复,但我只是看不出有什么问题

这是 txt.file 中的数据:

58_hello_sad_happy
685_dhejdho_sahdfihsf_hasfi
544654_fhokdf_dasfjisod_fhdihds

这是我正在使用的代码,但是最后一行代码是错误的:

int points = 0;
String name = "";
String a = "";
String b = "";

public void ReadFiles() throws FileNotFoundException{
    try (Scanner input = new Scanner(new File("questions.txt"))) {
        String data;
        while(input.hasNextLine()){
            data = input.nextLine();
            String[] Questions = data.split("_");
            points = Integer.parseInt(Questions[0]);
            name= Questions[1];
            a = Questions[2];
            b = Questions[3];
        }   
        System.out.println(Arrays.toString(Questions));
    }
}

这是我得到的错误:

 error: cannot find symbol 
 System.out.println(Arrays.toString(Questions));

谢谢你们。

标签: javaarraysnetbeans

解决方案


如果您只想打印数据,也可以使用以下代码:

    Files.readAllLines(Paths.get("questions.txt")).forEach(line -> {
        System.out.println(Arrays.toString(line.split("_")));
    });

输出是:

[58, hello, sad, happy]
[685, dhejdho, sahdfihsf, hasfi]
[544654, fhokdf, dasfjisod, fhdihds]

您的代码的正确版本应如下所示(您必须通过将 println 移动到 while 循环的末尾来访问声明范围内的变量 Question):

// definitions...

public void ReadFiles() throws FileNotFoundException{
    try (Scanner input = new Scanner(new File("questions.txt"))) {
        String data;
        while(input.hasNextLine()){
            data = input.nextLine();
            String[] Questions = data.split("_");
            points = Integer.parseInt(Questions[0]);
            name= Questions[1];
            a = Questions[2];
            b = Questions[3];
            System.out.println(Arrays.toString(Questions));
        }   
    }
}

推荐阅读