java - 将 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));
}
}
}
推荐阅读
- visual-studio-code - 如何对预定义变量进行子字符串化?
- powershell - 删除文件名中的某些单词
- c++17 - C ++ 17减少与累积速度
- maven - Maven阶段:生成源、进程源、进程类
- python - Python 正则表达式在某个字符串之后找到大括号内的所有内容
- node.js - 带有 Express 和 Handlebars 的多个视图文件夹
- c++ - 删除 memcpy 从字符串类复制的字符串时崩溃
- javascript - 从 JavaScript 中的字符串中删除正斜杠和前面的字符
- typescript - TypeScript 覆盖现有值并强制执行字段值
- java - 如何用句子中的不同字母匹配和替换单词的指定最后一个字母