谁帮我做下这道java的题呀

2025-04-05 08:29:51
推荐回答(2个)
回答1:

 public static int checkAnswer(String correctAnswer, String userAnswer)
    {
        int grade = 0;
        int num = 0;
        for (int i = 0; i < userAnswer.length(); i++)
        {
            // 如果用户答案某一项在正确答案中
            if (correctAnswer.indexOf(userAnswer.charAt(i)) != -1)
            {
                num++;
            }
            // 如果用户答案某一项不在正确答案中(即有错误选择项)
            else
            {
                return grade = 0;
            }
        }
        if (num == 0)
        {
            grade = 0;
        }
        else if (num == correctAnswer.length())
        {
            grade = 5;
        }
        else
        {
            grade = 2;
        }
        return grade;
    }
    
    public static void main(String[] args)
    {
        String correctAnswer = "ABC";
        String userAnswer = "D";
        int grade = checkAnswer(correctAnswer, userAnswer);
        System.out.println("本题得分 : " + grade);
    }

回答2:

public static int checkAnswer(String correctAnswer, String userAnswer) {
if (userAnswer == null || userAnswer.isEmpty()) {
return 0;
}
if (correctAnswer == null || correctAnswer.isEmpty()) {
throw new RuntimeException("No answer question!");
}
int right = 0;//正确的次数
for (char char0 : userAnswer.toCharArray()) {
if (correctAnswer.indexOf(char0) < 0) {
return 0;//一旦有一个不正确
} else {
right++;//记录正确的次数
}
}

return right == correctAnswer.length() ? 5 : 2;

}

public static void main(String[] args) {
String correctAnswer = "ACD";
String userAnswer = "ACD";
int grade = checkAnswer(correctAnswer, userAnswer);
System.out.println("本题的得分是 : " + grade);
}