Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 将txt文件中的项追加到数组_Java_Arrays_Netbeans - Fatal编程技术网

Java 将txt文件中的项追加到数组

Java 将txt文件中的项追加到数组,java,arrays,netbeans,Java,Arrays,Netbeans,嘿,我刚开始学习如何编码。我正在使用netbeans,我想将一些数据从txt.file传输到java中的数组中。这可能是一个非常简单的解决办法,但我只是看不出有什么问题 这是txt.txt文件中的数据: 58_hello_sad_happy 685_dhejdho_sahdfihsf_hasfi 544654_fhokdf_dasfjisod_fhdihds 这是我正在使用的代码,但是smthg与最后一行代码有误: int points = 0; String name = ""; Strin

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

这是txt.txt文件中的数据:

58_hello_sad_happy
685_dhejdho_sahdfihsf_hasfi
544654_fhokdf_dasfjisod_fhdihds
这是我正在使用的代码,但是smthg与最后一行代码有误:

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));

Thx太多人了。

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

    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循环的末尾来访问声明范围中的变量问题):


您仅在
while
循环的范围内声明了
问题。在循环之外声明它。Java命名约定也适用于以小写字母开头的变量。将代码更改为:
String[]问题;while(input.hasNextLine()){
之后,您可以简单地执行:
Questions=data.split(“”)
这可能有助于阅读:
// 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));
        }   
    }
}