【问题标题】:displaying which questions missed in array显示数组中遗漏了哪些问题
【发布时间】:2017-06-29 23:14:02
【问题描述】:

我希望我的程序显示两个数组之间遗漏了哪些问题。我会输入前 12 个的所有正确答案,然后输入错误的后 3 个。每当我尝试显示它时,它都会出现一些奇怪的返回答案,我认为它可能是内存地址。我已经尽我所能让它打印出错过的问题编号。请任何帮助都将不胜感激!

import java.util.Scanner; //import scanner

public class DriverTestBlah {
 public static void main(String [] args){

 Scanner input = new Scanner(System.in);
  char[] correctAnswers = {'A','D','C','A','A','D','B',
    'A','C','A','D','C','B','A','B'};
  char[] userAnswer = new char[correctAnswers.length];
      for(int i = 0; i < 15; i++) //print question numbers/takes user input
      {
      System.out.print("Question " + (i + 1) + ":");
          userAnswer [i] = input.nextLine().charAt(0);
      }//end of for loop
  for(int i = 0; i < questions.length; i++) //for loop prints you missed
    {
     System.out.print("You missed question: ");
        for(int y = 0; y < 1; y++) //for loop only takes one question # at a time
          {
           System.out.println(" " + which_questions_missed(userAnswer, correctAnswers));

          }//end of question number for loop
    }//end of 
  }//end of main
//create new class that determines which questions missed and returns their numbers
  public static int []which_questions_missed(char[] userAnswer, char[] correctAnswers){
     int missed[] = new int[correctAnswers.length];
        for (int i = 0; i < correctAnswers.length; i++){
           if (userAnswer[i] != correctAnswers[i]){
             missed[i]=(i+1);//chooses the index of the missed answers and adds 1 to display
            }
        }
     return missed;
  }
 }//end of class

【问题讨论】:

  • 您正在尝试打印一个数组。你需要Arrays.toString(which_questions_missed(userAnswer, correctAnswers))。但是,您的算法看起来有点奇怪。您可能无法获得预期的结果。

标签: java arrays loops methods pass-by-value


【解决方案1】:

我会像这样修改方法(不是which_questions_missed。请注意我是如何将名称从 which_questions_missed 更改为 whichQuestionsMissed 这并非偶然在 Java 程序中使用 camelCase 而不是 snake_case

import java.util.Scanner;

public class Main {
  public static void main(String [] args){
    Scanner input = new Scanner(System.in);
    char[] correctAnswers = {'A','D','C','A','A','D','B', 'A','C','A','D','C','B','A','B'};
    char[] userAnswer = new char[correctAnswers.length];
    for(int i = 0; i < 15; i++) {
      System.out.print("Question " + (i + 1) + ":");
      userAnswer[i] = input.nextLine().charAt(0);
    }
    whichQuestionsMissed(userAnswer, correctAnswers);
  }

  public static void whichQuestionsMissed(char[] userAnswer, char[] correctAnswers) {
    for(int i = 0; i < userAnswer.length; i++) {
      if(Character.toUpperCase(userAnswer[i]) != correctAnswers[i]) {
        System.out.println("You missed question: " + i);
      }
    }
  }
}

它利用Character.toUpperCase() 允许用户输入等效的小写字母。

试试here!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-11
    相关资源
    最近更新 更多