此代码的目标是比较两个不同的 string[] 数组,并检查有多少元素匹配。这将允许这些方法查看学生是否通过了测试,以及确定他们的字母等级。但是,完成的每项测试都会返回 true 以表示他们通过,并返回“A”表示他们的字母等级。现在元素被正确比较了,我仍然有每个元素都通过 .equals() 的问题。即
answerKey[1] = "B";
studentAnswers[1] = "C";
如果要比较这两个元素,它将通过.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;
for (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 = "";
for (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;
}
}
测试数据如下
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());
}
}