【问题标题】:Reading comma delimited file into a multidimensional array in Java将逗号分隔的文件读入Java中的多维数组
【发布时间】:2013-04-07 18:00:23
【问题描述】:

我想在 Java 中将多项选择题列表读入多维数组,文件格式为:Question,answer1,answer2,answer3,answer4,correctanswer

一公里有多少米?,1,10,100,1000,4, 彩虹童谣中没有哪个颜色?,蓝色,粉色,黑色,橙色,3 一个足球队有多少人在球场上?,10,11,12,13,2

所以我希望数组采用 Question[][] 格式,如果 n 为 1,那么 Question[n][1] 将是 CSV 文件中的第一个问题,然后选择一个问题,我可以将 n 更改为我想要的任何值。

我不知道会有多少问题,它们会不断地从 CSV 文件中添加或删除,因此不会有固定数量。所以问题是如何以简单的方式从 CSV 文件中加载所有问题?

【问题讨论】:

  • 你能告诉我们你尝试了什么吗?
  • 可以使用第三方库吗?否则你需要考虑转义和引用吗?
  • 我一直在 link 使用一个简单的 CSV 阅读教程,但我立即遇到了问题,因为我想要一个多维数组,你甚至不能在不知道有多少的情况下声明其中一个行。

标签: java csv multidimensional-array


【解决方案1】:

当您必须为数据层次结构创建一个二维数组时,您可能应该为它创建一个合理的模型。

这是一个快速(但又脏)的模型(因为打字速度而丢弃了设置器):

问卷类:

/**
 * Facilitates an entire questionnaire
 */
public class Questionnaire extends ArrayList<Question> {

    /**
     * This questionnaire's name
     */
    private String name;

    /**
     * Creates a new questionnaire using the specified name
     * @param name  The name of this questionnaire
     */
    public Questionnaire(String name) {
        this.name = name;
    }

    /**
     * Returns the name of this questionnaire
     */
    public String getName() {
        return name;
    }
}

问题类:

/**
 * Facilitates a question and its answers
 */
public class Question extends ArrayList<Answer> {

    /**
     * The question's text
     */
    private String text;

    /**
     * Constructs a new question using the specified text
     * @param text  The question's text
     */
    public Question(String text) {
        this.text = test;
    }

    /**
     * Returns this question's text
     */
    public String getText() {
        return text;
    }
}

答题类:

/**
 * Facilitates an answer
 */
public class Answer {

    /**
     * The answer's text
     */
    private String text;

    /**
     * Whether or not this answer is correct
     */
    private boolean correct;

    /**
     * Constructs a new answer using the specified settings
     * @param text          The text of this answer
     * @param correct       Whether or not this answer is correct
     */
    public Answer(String text, boolean correct) {
        this.text = text;
        this.correct = correct;
    }

    /**
     * Returns this answer's text
     */
    public String getText() {
        return text;
    }

    /**
     * Whether or not this answer is correct
     */
    public boolean isCorrect() {
        return correct;
    }
}

它的用法如下:

// Create a new questionnaire
Questionnaire questionnaire = new Questionnaire("The awesome questionnaire");

// Create a question and add answers to it
Question question = new Question("How awesome is this questionnaire?");
question.add(new Answer("It's pretty awesome", false));
question.add(new Answer("It's really awesome", false));
question.add(new Answer("It's so awesome my mind blows off!", true));

// Add the question to the questionnaire
questionnaire.add(question);

迭代它很容易:

// Iterate over the questions within the questionnaire
for(Question question : questionnaire) {
    // Print the question's text
    System.out.println(question.getText());

    // Go over each answer in this question
    for(Answer answer : question) {
        // Print the question's text
        System.out.println(answer.getText());
    }
}

你也可以只迭代它的一部分:

// Iterate over the third to fifth question
for (int questionIndex = 2; questionIndex < 5; questionIndex ++) {
    // Get the current question
    Question question = questionnaire.get(questionIndex);

    // Iterate over all of the answers
    for (int answerIndex = 0; answerIndex < question.size(); answerIndex++) {
        // Get the current answer
        Answer answer = question.get(answerIndex);
    }
}

使用您描述的格式将文件读入模型可以通过以下方式完成:

// Create a new questionnaire
Questionnaire questionnaire = new Questionnaire("My awesome questionnaire");

// Lets scan the file and load it up to the questionnaire
Scanner scanner = new Scanner(new File("myfile.txt"));

// Read lines from that file and split it into tokens
String line, tokens[];
int tokenIndex;
while (scanner.hasNextLine() && (line = scanner.nextLine()) != null) {
    tokens = line.split(",");

    // Create the question taking the first token as its text
    Question question = new Question(tokens[0]);

    // Go over the tokens, from the first index to the one before last
    for (tokenIndex = 1; tokenIndex < tokens.length-1; tokenIndex++) {
        // Add the incorrect answer to the question
        question.add(new Answer(tokens[tokenIndex], false));
    }

    // Add the last question (correct one)
    question.add(new Answer(tokens[tokenIndex],true));
}

// Tada! questionnaire is now a complete questionnaire.

【讨论】:

  • 感谢您的回答,问题仍然是我必须从某个地方阅读问题,最终用户将永远无法访问代码并且程序员不会维护它所以更改问题的唯一方法是通过外部文件。在问卷中欣赏你的幽默:D。编辑:哦,你好编辑:D
  • 嗯,这不仅是一种好的做法,它还可以让您的生活更轻松。您可以通过正确布置数据并节省时间来解决令人难以置信的(当然相对于人)算法问题,而不是尝试解决它。尽管看起来工作量更大,但实际上并非如此。
  • 谢谢这看起来很完美,我会改变它以适应我的程序,但这正是我想要的,非常感谢:)
  • 还有一件事,如果您还在那里,问卷中的问题和答案的迭代不起作用。它们肯定会被添加到调查问卷中,我已经打印出了传入的问题和答案,但是如果我想在调查问卷中显示完整列表或一组问题/答案,它就不起作用.
  • 您可以获得问题的第二个答案,例如:question.get(1),或者问卷的第一个问题,例如:questionnaire.get(0)。要获得第四个问题的第四个答案,您可以执行以下操作:questionnaire.get(3).get(3),很像二维数组。
【解决方案2】:

最简单的方法是创建一个ArrayList 或数组。这看起来很复杂,但使用ArrayList 意味着您不必担心问题的数量。

ArrayList<String[]> questions = new ArrayList<String[]>();
// Create the object to contain the questions.

Scanner s = new Scanner(new File("path to file"));
// Create a scanner object to go through each line in the file.

while(s.hasNextLine()) {
   // While lines still exist inside the file that haven't been loaded..
   questions.add(s.nextLine().split(","));
   // Load the array of values, splitting at the comma.
}

最后,您会得到一个ArrayList 对象,其中每个条目都是一个String[],其长度与每行上的标记数相同。

编辑

正如本答案的 cmets 中所述,您只需在 ArrayList 类中调用 toArray 方法即可获得多维数组。

【讨论】:

  • 显然你可以在最后调用toArray 并拥有一个数组。
  • 所以我刚刚尝试的是String[][] questionsarray = questions.toArray();,但这会出现错误,我错过了一些基本的东西吗? :( "类型不匹配:无法从 Object[] 转换为 String[][]"
  • 可能是因为ArrayList 类内部是一个用于存储数据的后端数组。问题是后端数组不是String[][] 类型,所以你得到了一个例外。你可能只需要坚持ArrayList
【解决方案3】:

您需要设置一个嵌套的 for 循环来处理这个问题:

for(i = 0; i < number_of_questions; i++)
{
    line_array = current_input_line.split(",")
    Questions[i] = line_array[0]
    for(j = 1; j < line_array.length; j++)
    {
        Questions[i][j] = line_array[j];
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-19
    • 2023-03-15
    • 1970-01-01
    • 2023-02-02
    • 1970-01-01
    • 1970-01-01
    • 2015-06-23
    • 2013-11-16
    相关资源
    最近更新 更多