这是我的java代码,用于将MCQ答案与主函数中的答案键进行比较,其中学生的答案存储在外部.txt文件中。它确实向我显示了输出,但它不是正确的输出。以下是我的代码
public static void main(String[] args)
{
char [] answer = new char[152];
//char[] answer = new char[10];
char[] keys = {'D', 'B', 'D', 'C', 'C', 'D', 'A', 'E', 'A', 'D'};
int c = 0;
try{
Scanner data = new Scanner(new File("students1.txt"));
while(data.hasNextchar())
{
String s = data.nextLine();
int count = 0;
for(int i = 0; i< s.length(); i+=2) {
if(s.charAt(i) == keys[count])
count++;
}
System.out.println("Student " +c + "'s correct count is " + count);
c++;
}
}
catch(Exception e){
System.out.println(e);
}
In the Output Window it should show
Student 1's correct count is 7
Student 2's correct count is 7
Student 3's correct count is 7
Student 4's correct count is 6
Student 5's correct count is 5
Student 6's correct count is 4
Student 7's correct count is 8
Student 8's correct count is 7
答案 0 :(得分:0)
这个for循环(编辑:可能)是罪魁祸首:
int count = 0;
for(int i = 0; i< s.length(); i+=2) {
if(s.charAt(i) == keys[count])
count++;
}
}
因为您在keys[count]
计数时检查了答案键,所以当他们每个问题都正确时,您只会查看答案键的正确部分。
而是尝试类似:
if (s.charAt(i) == keys[i/2]) {
count++;
}
对for循环中的if进行更改后,您现在每次循环执行时都会检查键中的下一个答案,而不是仅在上一个问题的答案是正确的时才检查。
我无法保证这会有效,因为您对输入的评论中没有新内容,因此我无法验证其是否获得了正确的结果。
我希望这有帮助!
编辑:我做了另一个改变。我将data.hasNextchar()
更改为data.hasNextLine()
,这是一个示例文本输入文件和输出
char[] keys = {'D', 'B', 'D', 'C', 'C', 'D', 'A', 'E', 'A', 'D'};
students1.txt
D A D C C D A E A D
D A D D A D A E A D
D A D C C D A B A D
D A D D D D E C A D
if statement:
if(s.charAt(i) == keys[i/2])
count++;
输出:
Student 0's correct count is 9
Student 1's correct count is 7
Student 2's correct count is 8
Student 3's correct count is 5
我认为这是正常的。