比较两个整数数组而不在java中进行排序

时间:2017-07-07 15:32:24

标签: java arrays

我正在编写一段代码,用于创建多项选择题问题考试。我正在处理的代码的目的是使问题具有多个正确的答案。

用户输入答案的方式是选择与他们想要提交的选项相对应的整数。

实际的正确整数存储在名为" correctionIndex"的数组中。并且用户存储的响应存储在名为" response"。

的数组中

我遇到的错误是检查用户的答案是否正确,无论他或她提交的顺序如何。我当前的想法是创建一个嵌套的for循环来遍历两个数组和检查匹配,如果匹配等于正确答案的数量,那么学生将是正确的。当我运行它时,这不起作用。

在该点之前的所有内容都能正常运行,我已确保用户无法输入无效的回复,重复回复,并且如果他们提交的回复数量超过了正确的答案,则会自动将其标记为错误。

以下是代码中不起作用的部分:

for(int i = 0; i < correctIndex.length; i++){
            for(int j = 0; j < response.length; j++){
                if(correctIndex[i] == response[j]){
                    matches++;
                }
            }
        }
        if(matches == correctIndex.length){
            System.out.println("Correct, answer was: ");
            for(int i = 0; i < correctIndex.length; i++){
                System.out.println((correctIndex[i] + 1) + ": " + choices[correctIndex[i]]);
            }
        }
        else{
            System.out.println("Your answer: ");
            for(int i = 0; i < response.length; i++){
                System.out.println(response[i] + ": " + choices[response[i]-1]);
            }
            System.out.println();
            System.out.println();
            System.out.println("Is incorrect, the correct answer is: ");
            for(int i = 0; i < correctIndex.length; i++){
                System.out.println((correctIndex[i] + 1) +": " + choices[correctIndex[i]]);
            }
        }

以下是我得到的输出示例:

Please input the correct choice using its corresponding number

Which of these are visibilities?

1: Public
2: Private
3: Void
4: Protected
5: Int
6: String
7: Package-Protected

Please enter how many answers you would like to select: 
4
Enter your number for answer 1
1
Enter your number for answer 2
2
Enter your number for answer 3
4
Enter your number for answer 4
7

以下是使用结果方法(相关问题)后的结果:

Question: 
Which of these are visibilities?

Choices: 
1: Public
2: Private
3: Void
4: Protected
5: Int
6: String
7: Package-Protected

Your answer: 
1: Public
2: Private
4: Protected
7: Package-Protected


Is incorrect, the correct answer is: 
1: Public
2: Private
4: Protected
7: Package-Protected

2 个答案:

答案 0 :(得分:1)

为什么不使用套装?如果两个集合具有相同的元素,则无论顺序如何,它们都是相同的!

一个例子:

Set<Integer> correctIndex = new HashSet<>();
Set<Integer> response = new HashSet<>();

correctIndex.add(1);
correctIndex.add(2);
correctIndex.add(3);

response.add(3);
response.add(2);
response.add(1);

// This will print true!
System.out.println(correctIndex.equals(response));

答案 1 :(得分:0)

这样的事情应该这样做:

for(int i = 0;i<correctIndex.length;i++){
  int answer = correctIndex[i];
  boolean contained = false;
  for(int i = 0;i<response.length;i++){
    if(response[i]==answer){
      contained =true;
    }
  }
  if(contained = false){
    return false; // response is incorrect, add code to handle
  }
}
return true; // if it makes it through, response is correct