Priyanshu Priyanshu - 4 months ago 8
Java Question

2-D array reading from external file

this is my java code for comparing MCQ answers with the answer key in the main function, where students responses are stored in an external .txt file. It does show me an output but it's not the correct one. Below is my code

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

Answer

This for loop (Edit: might) be the culprit:

int count = 0;
for(int i = 0; i< s.length(); i+=2) {
    if(s.charAt(i) == keys[count])
        count++;
    }
}

Because you are checking the answer key at count in keys[count] you are only looking at the right part of the answer key when they get every question right.

Instead try something like:

if (s.charAt(i) == keys[i/2]) {
    count++;
}

With that change to the if inside the for loop, you now are checking the next answer in the key every time the loop executes, instead of only if the answer to the previous question was correct.

I can't guarantee that this will work because your comment with the input didn't have the newlines in it so I couldn't validate if it got the right results.

I hope this helps!

Comments