Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialMille Gloerfelt-Tarp
390 PointsComparing values from 2 arrays
Hi, i am trying to compare students test answers with the correct answers. The students answers and the correct answers are stored in two different arrays. What I've done so far is to create a nestled for loop which gets the values from the students. I struggle when it comes to the part where I should compare the results.
public class Tentarep {
public static void main(String[] args) {
//students answer
char[][] svar = {
{'A', 'B', 'A', 'C', 'C'},
{'B', 'A', 'B', 'A', 'C'},
{'A', 'C', 'C', 'B', 'A'},
{'B', 'A', 'A', 'C', 'A'},
{'A', 'B', 'C', 'A', 'C'},
{'A', 'B', 'A', 'C', 'C'}
};
//correct answers
char[] korrekt = {'A', 'B', 'C', 'A', 'C'};
for (int r = 0; r < svar.length; r++) {
int antalKorrekt = 0;
//Looping through the students answers
for (int c = 0; c < svar[r].length; c++) {
//outputs students asnwers
System.out.print(svar[r][c]);
}
}
}
}
1 Answer
Ben McGrath
16,192 PointsHi Mille,
You are very close you've actually done most of the hard work (in my opinion). Inside your nested for-loop you want to compare with an if statement the current student answer svar[r][c]
and the correct answer that corresponds with that question korrekt[c]
. Now I see you have already dedicated a variable for storing the number of correct answers, just increment that number by one each time the students answer equals the correct answer i.e. svar[r][c] == korrekt[c]
. Then you could print out the number of correct answers after the nested for loop completes a full cycle (so inside the outer for loop). Then you will be able to quickly tell how many answers each student answered correctly.
Hopefully this helps you out without giving the answer away, please let me know if you have any questions and I can follow up with code examples if that would help. Happy coding!
Mille Gloerfelt-Tarp
390 PointsMille Gloerfelt-Tarp
390 PointsNo one?=)