java - Checking to see if two elements are the same, each element coming from a different string array -
this question has answer here:
- how compare strings in java? 23 answers
the goal of code compare 2 different string[] arrays, , check see how many of elements match. allow methods see whether student has passed or failed test, along determining letter grade. however, every test done results in true being returned them passing , "a" being returned letter grade. elements being compared correctly, still have issue of every element passing .equals(). i.e. answerkey[1] = "b"; studentanswers[1] = "c";
if these 2 elements compared, pass .equals().
public class listofanswers { static final string[] answerkey = {"a", "b", "b", "c", "d", "b", "c", "c", "d", "e", "c", "d", "d", "e", "a", "a", "a", "d", "d", "e"}; string[] studentanswers; public listofanswers(string[] ans) { studentanswers = ans; } public boolean checkpassorfail() { int answersright = 0; (int cnt = 0; cnt < studentanswers.length; cnt++) { if(studentanswers[cnt].equals(answerkey[cnt])) { answersright++; } } if (answersright >= 14) { return true; } else { return false; } } public string computegrade() { int score = 0; string grade = ""; (int cnt = 0; cnt < studentanswers.length; cnt++) { if (studentanswers[cnt].(answerkey[cnt])) { score++; } } if (score < 10) { grade = "e"; } else if (score == 10) { grade = "d"; } else if ((score==11)||(score==12)) { grade = "c-"; } else if (score==13) { grade = "c"; } else if (score == 14) { grade = "c+"; } else if (score == 15) { grade = "b-"; } else if (score == 16) { grade = "b"; } else if (score == 17) { grade = "b+"; } else if (score == 18) { grade = "a-"; } else if ((score == 19)||(score==20)) { grade = "a"; } return grade; } }
the test data looks follows
public class listofanswerstester { public static void main(string[] args) { string[] dananswers = {"a", "b", "b", "d", "d", "b", "c", "c", "d", "e", "c", "d", "d", "e", "a", "a", "a", "d", "d", "e"}; listofanswers dananswerlist = new listofanswers(dananswers); string[] bobanswers = {"a", "c", "b", "c", "d", "b", "c", "c", "d", "e", "c", "d", "a", "e", "a", "a", "a", "d", "e", "e"}; listofanswers bobanswerlist = new listofanswers(dananswers); system.out.println("student dan's pass/fail: " + dananswerlist.checkpassorfail()); system.out.println("student dan's grade: " + dananswerlist.computegrade()); system.out.println("student bob's pass/fail: " + bobanswerlist.checkpassorfail()); system.out.println("student bob's grade: " + bobanswerlist.computegrade()); } }
i see typo here:
listofanswers bobanswerlist = new listofanswers(dananswers);
should be:
listofanswers bobanswerlist = new listofanswers(bobanswers);
or give answers of dan bob ;)
oh, , others said, use equals
when comparing (non-null) strings unless want check identity (i see question updated that).
Comments
Post a Comment