我正在尝试从文本文件中读取示例示例,但是,我的数组未为正确的字符串建立索引,并且我不知道如何解决它。输出返回空值。我可以得到一些指示吗?
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
等等。
答案 0 :(得分:0)
您有三个问题,但是您在循环中以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
数组中输入内容,然后打印其值。