将项目从 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));

谢谢这么多家伙。

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

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

最新更新