【问题标题】:Making a quiz with Java using arrays. Need pointers with grading answers使用数组进行 Java 测验。需要带有评分答案的指针
【发布时间】:2015-06-08 02:50:26
【问题描述】:

这是为了上课。我无法弄清楚如何最好地将用户输入与数组答案键进行比较,从而对给出的答案进行评分。我试着搜索了一段时间,但找不到我需要的东西,所以任何指针都将不胜感激!

练习的提示是:

编写一个 DMV 程序,对驾照考试的笔试部分进行评分。它应该有20个多项选择题。它应该要求用户为 20 个问题中的每一个问题输入学生的答案,这些问题应该存储在另一个数组中。输入学生的答案后,程序应显示一条消息,指示学生通过或未通过考试。(学生必须正确回答 20 个问题中的 15 个才能通过考试)。然后它应该显示正确回答的问题总数和错误回答问题的总数。输入验证:只接受字母 A、B、C 或 D。

到目前为止我的代码:

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    String[] answerkey = {"b","d","a","a","c","a","a","d","b","b","b","d","c","a","c","c","a","d","a","a"};
    int n = 0;

        int correct = 0;
        int incorrect = 0;
        String answer = "";

        for (int i = 0; i < 20; i++){
            System.out.println("Please enter your answers. Acceptable input is limited to A,B,C and D.\n");
            answer = input.next();

            if (answer.compareTo(answerkey[0])==0){
                correct++;} 
            else {incorrect++;}
        }

        if (correct > 14){
            System.out.println("You passed.");
        } else {
           System.out.println("You failed.");
        }
        System.out.println("You have " + correct + " correct answers.");
        System.out.println("You have " + incorrect + " incorrect answers.");

}

【问题讨论】:

  • @HovercraftFullOfEels 不,实际上......我的具体问题(如帖子开头所述)是我不知道如何将给定的用户输入与正确答案数组进行比较。例如,如果答案是 [1,2,3,4,5] 并且用户输入是 [1,2,3,8,5] 它应该报告一个元素不同。我需要知道的是有什么方法可以做到这一点?
  • 在你的 for 循环中,如果布尔检查,你将在答案数组中检查的数组项硬编码为仅第 0 项而不是对应于第 i 个问题的答案项:@987654322 @。不应该是if (answer.compareTo(answerkey[i]) == 0) {还是if (answer.equals(answerkey[i])) {
  • 啊。不知道我是怎么错过的,非常感谢。
  • 我完全错过了你的问题——很抱歉。

标签: java arrays if-statement


【解决方案1】:

尝试使用此代码将用户输入与数组 myArray 进行比较。

希望这会有所帮助。

String[] myArray= { //initialize values here 
};


if ((myArray[0]).equals(answer)){
    correct++;
} else{
    incorrect++;
} 

【讨论】:

    【解决方案2】:

    使用动态索引访问变量。现在,您的每个答案都会与第一个答案(“b”)进行比较

    一个例子是

    String[] myArray = { //initialize values here
                           };
    
    for (int index = 0; index <= myArray.length-1; index++){
        if (answer.equals(myArray[index]){
            correct++;}
        else{
            incorrect++;}
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-26
      • 1970-01-01
      • 1970-01-01
      • 2020-09-21
      • 1970-01-01
      • 2017-09-05
      • 1970-01-01
      相关资源
      最近更新 更多