Programming and Problem Solving with Java

(やまだぃちぅ) #1

CASE STUDY^505


Because the name is only printed exactly as it was read in, we do not need to use the
class Name; we can just read the line and store it into a string field,name. We can read the
line containing the T’s and F’s into a string and type cast them to an array of charusing
the Stringmethod toCharArray.


In a by-hand algorithm, we would hold the student answers next to the key and
compare them, position by position. The operational verb is “compare.” To grade a
student’s answer, the operation must compare its ordered collections of T’s and F’s with
the ordered collection of T’s and F’s of the key. The return value is the number of places
where the values match.


Responsibility Algorithms for GradeExams(the driver) The responsibilities for the driver
include the preparation of the files and reading in the number of questions, which are
concrete steps. The responsibility “Get Key” is concrete as well: We simply instantiate
an AnswerSheet object and apply “Input Name and Answers” to it. The work is in the
“Process Exams” responsibility. There must be a loop that applies “Input Name and
Answers” to an AnswerSheet object and tells it to compare itself to the key, returning
the number of correct answers. The name and the number of correct answers are then
written on the output file. The name “Input Name and Answers” is too long; let’s simply
call this method input.


Process exams
studentSheet = new AnswerSheet
whilemore exams
studentSheet.input(inFile)
numberCorrect = studentSheet.numOfMatches(key)
Write studentSheet.knowName() + “: number correct ”
+ numberCorrect

int numOfMatches(AnswerSheet answer)
Set numCorrect to 0
forcounter going from 0 through key.length-1
if (key[counter] == answer[counter])
Increment numCorrect
returnnumCorrect

Know name
returnname

Input name and answers (BufferedReader inFile)
Set name to inFile.readLine()
Set responses to inFile.readLine().toCharArray()
Free download pdf