Hi I am stuck with this particular question. I create a program called DriverExam which reads from user and match it to array and gets the answer but I want to read from files instead of array. so far I am able to read first line. can someone help me how to read all line and store in the appropriate class and get the output on no of people passed, failed and how many got correct and how many get more than 10 questions correct.
This is my code so far
The files have input something like this
B D A A C A B A C D B C D A D C C B D A
B D A A C A B A C D B C D A D C C B D A
A B D C A D C D A B A D C A B C D A B A
A B D C A D C D A B A D C A B C D A B A
public class DriversLicenceExam {
private char[] key = { 'B', 'D', 'A', 'A', 'C', 'A', 'B', 'A', 'C', 'D',
'B', 'C', 'D', 'A', 'D', 'C', 'C', 'B', 'D', 'A' };
private char[] answers;
public DriversLicenceExam(char[] answers) {
this.answers = answers;
}
public boolean passed(){
return(totalCorrect()>=15);
}
public int totalCorrect(){
int correct = 0;
for(int i = 0; i<key.length;i++){
if(key[i]==answers[i]){
correct++;
}
}
return correct;
}
public int totalIncorrect(){
int incorrect = 0;
incorrect = key.length - totalCorrect();
return incorrect;
}
public int questionMissed(){
int size = key.length - totalCorrect();
int[] missed = null;
if(size<1)
return size;
else
missed = new int[size];
int pos=0;
for(int i = 0; i<key.length;i++){
if(key[i]!=answers[i]){
missed[pos] = (i+1);
pos+=1;
}
}
return size;
}
}
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class DriverLicenceFilesDemo {
public static void main(String[] args) throws IOException {
// create scanner object for keyboard input
Scanner kb = new Scanner(System.in);
String fileName;
File myfile;
char[] answers = new char[20];
do {
System.out.print("Please enter the name of the file: ");
fileName = kb.next();
myfile = new File(fileName);
if (myfile.exists()) {
Scanner infile = new Scanner(myfile);
while (infile.hasNext()) {
for (int i = 0; i < answers.length; i++) {
answers[i] = infile.next().charAt(0);
}
}
infile.close();
}
else {
System.out.println("File does not exist...");
}
} while (!myfile.exists());
// create driver class
DriversLicenceExam myDriver = new DriversLicenceExam(answers);
// Display here
System.out.println();
//System.out.print("You " + (myDriver.passed() ? "passed" : "did not passed" ) + ".\n");
System.out.println("Total correct: " + myDriver.totalCorrect());
System.out.println("Total incorrect: " + myDriver.totalIncorrect());
if (myDriver.passed() == true)
{
System.out.println("Congratulations! You have passed!");
}
else
{
System.out.println("You have failed.");
}
}
}