簡體   English   中英

從文件讀取以比較字符

[英]Reading from a file to compare characters

我需要比較從文件中讀取的測試答案。 該文件如下所示:

第一行=答案鍵

第三行及以下=學生證+學生測驗答案

TTFTFTTTFTFTFFTTFTTF

ABC54102 T FTFTFTTTFTTFTTF TF
DEF56278 TTFTFTTTFTFTFFTTFTTF
ABC42366 TTFTFTTTFTFTFFTTF
ABC42586 TTTTFTTT TFTFFFTF

我將答案鍵(第一行)放在帶有.nextLine()的ansKey字符串中。 然后,我將學生ID循環打印,並將該學生的答案放入另一個String中,並將兩者都傳遞給方法:

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。 不知道這些課程將如何幫助我。 任何幫助,將不勝感激!

好的,如果您不能使用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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM