将逗号分隔的文件读入Java中的多维数组

时间:2013-04-07 18:00:23

标签: java csv multidimensional-array

我想在Java中用多维数组读取多项选择题列表,文件格式为:问题,答案1,答题2,答案3,答案4,纠正

  

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

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

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

3 个答案:

答案 0 :(得分:0)

最简单的方法是创建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[],其长度与每行上的标记数相同。

修改

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

答案 1 :(得分:0)

您需要设置嵌套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];
    }
}

答案 2 :(得分:0)

当你到达必须为数据层次结构制作二维数组的点时,你应该为它创建一个合理的模型。

这是一个快速(和肮脏)的模型(设置器因打字速度而被丢弃):

问卷类:

/**
 * 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.