我试图从文本文件中读取示例示例,但是,我的数组没有索引正确的字符串,我不知道如何修复它。输出返回null。我能指点一下吗?
public static void main(String[] args) throws FileNotFoundException {
File file = new File("C:\\Users\\andre\\Documents\\NetBeansProjects\\ArrayExample2\\src\\Question1");
Scanner fileScanner = new Scanner(file); // have to throw an exception
String[] questions = new String[10];
String[] answers = new String[4];
String[][] choices = new String[10][4];//3 questions 4 possible answers
for (int i = 0; i < 10; i++) {
questions[i] = fileScanner.nextLine();
System.out.println(questions[i]);
for (int k = 0; k < 4; k++) {
System.out.println(choices[i][k]);
}
String choicesInALine = fileScanner.nextLine();
String[] choiceItems = choicesInALine.split("#");
//transfer items with for loop
for (int j = 0; j < choiceItems.length; j++) {
choices[i][j] = choiceItems[j];
}
answers[i] = fileScanner.nextLine();
}
fileScanner.close();
...
// 文本文件
Psychology and Science
85
By the 1920s a new definition of psychology had gained favor. Psychology was said to be the science of...
mind # consciousness # computers # behavior # philosophy
等等..
你有三个问题,但是你在循环中在questions
数组中输入了10次。你也没有在choices
数组中输入任何内容。你是直接打印choices
数组,它给出了空值:
for(int i = 0; i < 10; i++) {
questions[i] = fileScanner.nextLine(); // questions array will contains questions and options
System.out.println(questions[i]);
for(int k = 0; k < 4; k++) {
System.out.println(choices[i][k]); // You have taken no input in choices.
//It will give null values
}
}
您必须首先在choices
数组中输入,然后打印其值。