【问题标题】:Multidimension Array Reading From Text从文本中读取的多维数组
【发布时间】:2019-03-05 04:44:29
【问题描述】:

我正在尝试从文本文件中读取示例示例,但是,我的数组没有索引正确的字符串,我不知道如何修复它。输出返回空值。我能得到一些方向吗?

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

等等。

【问题讨论】:

  • 尝试整理您的身份
  • 您看到的行为是什么,您希望您的输出是什么样的?

标签: java arrays java.util.scanner


【解决方案1】:

您有三个问题,但是您在循环中将输入 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 数组,然后打印其值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-21
    • 2018-05-08
    相关资源
    最近更新 更多