gpt4 book ai didi

java - 从文件中读取以比较字符

转载 作者:行者123 更新时间:2023-12-01 13:09:53 24 4
gpt4 key购买 nike

我需要比较从文件中读取的测试答案。该文件如下所示:

第一行 = 答案

第 3 行及以下 = 学生 ID + 学生测试答案

TTFTFTTTFTFTFFTTFTTF

ABC54102 T FTFTFTTTFTTFTTF TF
DEF56278 TTFTFTTTFTFTFFTTFTTF
ABC42366 TTFTFTTTFTFTFFTTF
ABC42586 TTTTFTTT TFTFFFTF

我使用 .nextLine() 将答案键(第一行)放入名为 ansKey 的字符串中。然后,我在循环中打印学生 ID,并将该学生的答案放入另一个字符串中,并将两者传递给一个方法:

Scanner inFile = new Scanner(file);

while(inFile.hasNextLine())
{
//Student ID
System.out.print("\t" + inFile.next());

//Student Answers
studentAnswers = inFile.nextLine();
System.out.print("\t" + studentAnswers);

//Get examGrade
testGrade = examGrade(ansKey, studentAnswers.trim());

//Display scores
System.out.println(testGrade);
}

在我的方法中,我有一个 for 循环来比较:

public static String examGrade(String ansKey, String studentAnswers)
{
for(int i = 0; i < studentAnswers.length(); i++)
{
if(ansKey.charAt(i) == studentAnswers.charAt(i))
score += 2;
else if(studentAnswers.charAt(i) == ' ')
score += 0;
else
score -= 1;
}
}

所有这些都工作得很好。但我的教授不希望我使用trim()。如果我把它拿出来,我会得到 ArrayIndexOutOfBounds。我使用trim()的原因是因为当我用.nextLine()读取studentAnswers时,前面有一个空格;我无法使用 .next(),因为某些答案之间有空格。

我不相信我可以使用我的代码中没有使用过的任何东西(这里没有看到的类,数组等......)。不过我可以使用 StringBuffer 和 StringTokenizer 。但不确定这些类(class)对我有什么帮助。任何帮助将不胜感激!

最佳答案

好吧,如果你不能使用 trim()substring(),你就必须使用算术

public static String examGrade(String ansKey, String studentAnswers)
{
//Now only go up to the answer key length
for(int i = 0; i < ansKey.length(); i++)
{
//shift the index we are checking the student answers by 1
int j = i + 1;
if(ansKey.charAt(i) == studentAnswers.charAt(j))
score += 2;
else if(studentAnswers.charAt(j) == ' ')
score += 0;
else
score -= 1;
}
}

关于java - 从文件中读取以比较字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22971342/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com