简体   繁体   中英

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

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!

Edit: I made another change. I changed data.hasNextchar() to data.hasNextLine() and here's a sample text input file and output

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++;

Output:

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

I think that this is working properly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM