Привет, я только начал учиться программировать. Я использую 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));
Спасибо, ребята.
Т.е. измените свой код на: String[] Questions; while(input.hasNextLine()){
, а затем вы можете просто сделать: Questions = data.split("_");
Это может быть полезно прочитать: geeksforgeeks.org/variable-scope-in-java
Вы также можете использовать приведенный ниже код, если хотите просто распечатать данные:
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]
Правильная версия вашего кода должна быть такой, как показано ниже (вы должны получить доступ к переменной Question в объявленной области, переместив println в конец цикла while):
// 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));
}
}
}
Вы объявили
Questions
только в рамках циклаwhile
. Объявите это вне цикла. Также соглашения об именах Java предназначены для переменных, которые должны начинаться с нижнего регистра.