-2

我对编程有点陌生,我用一个问题制作了这个小程序,在那个问题之后我还有其他一些问题,问题是我想把它放在一个数组中。现在根据我的理解,我必须把它放在一个字符串中,然后把它和我的其余问题放在一个数组中。我把其中一个问题的代码放在了,所以你们可以告诉我我问的问题是否可能:) 谢谢!

我想问用户一些问题。如果我只有一个问题,代码将如下所示:

import java.io.*;

public class Bycicle {
    public static void main(String[] args) throws IOException {

        BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
        int num1;
        // first question
        System.out.println("\n is the bycicle moving? : ");
        System.out.println("1 : yes.");
        System.out.println("2 : no.");
        System.out.flush();
        num1 = Integer.parseInt(stdin.readLine());
        if (num1 == 1) {
            System.out.println("\n good, keep going");
        } else if (num1 == 2) {
            System.out.println("\n get a move on then!\n \n \n END");
            System.exit(0);
        }
    }
}

如何将多个问题和答案放入一个数组中?

4

2 回答 2

0

Question您可以按如下方式创建一个类,

class Question{

   public Question(String questionStatement, String answer){
      this.questionStatement = questionStatement;
      this.answer = answer;
   }
   String questionStatement;
   String answer;
   // whatever fields you want here for a question e.g. options, answers.
   // getters and setters for all fields
}

在你的Bicycle课堂上,创造List<Question> questions = new ArrayList<Question>();

public static void main(String [] args){

    List<Question> questions = new ArrayList<Question>();
    questions.add(new Question("does this Bicycle move?","yes"))
    // add many questions in the list here

    for(Question question : questions){
        // do whatever you want to ask questions and get answer
    }

}
于 2013-09-06T10:21:49.170 回答
0

由于您正在编程面向对象,因此您应该创建一个 Question 类。

public class Question{
    private String question
    private String answer

    //getter & setter here
}

现在在你的main方法中:

public static void main(String[] args){
    Question[] questions = new Question[2];
    questions[0] = new Question("Is this bicycle moving?","yes");
    questions[0] = new Question("Does this eagel fly","yes");
    // and so on
}

您可以使用foreach遍历问题

编辑: 迭代示例

for(Question question : questions){
    System.out.println(question.question)
    //now read the input and use equals to verify it 
}
于 2013-09-06T10:20:45.000 回答