I'm having problems realizing why my counter keeps printing out a different value even when I enter all the right answers. I've tried everything I could think of plus researching and still no luck. Please help, this is hour 14 of me working on this "simple" program.
import java.util.Scanner; //import scanner
public class DriverTestBlah {
public static void main(String [] args){
Scanner input = new Scanner(System.in);
char[] correctAnswers = {'A','D','C','A','A','D','B',
'A','C','A','D','C','B','A','B'};
char singleAnswer = ' ';
int number_Correct = 0;
for(int i = 0; i < 15; i++) //print question numbers/takes user input
{
System.out.println("Question " + (i + 1) + ":");
singleAnswer = input.nextLine().charAt(0);
}//end of for loop
System.out.println("number correct: " +
total_correct_answers(correctAnswers, singleAnswer));
}//end of main
public static int total_correct_answers(char []correctAnswers,char singleAnswer){
int number_correct = 0;
for (int i = 0; i < 15; i++){
if(correctAnswers[i] == singleAnswer){
number_correct++;}
}//end of for loop
return number_correct;
}//end of correct method
}//end of class
The reason your program was showing wrong value is singleAnswer
variable stores only the last value/answer given by user.
I have created an array userAnswer
to store all answers given.
Try this:
public class DriverTestBlah {
public static void main(String [] args){
Scanner input = new Scanner(System.in);
char[] correctAnswers = {'A','D','C','A','A','D','B',
'A','C','A','D','C','B','A','B'};
char[] userAnswer = new char[correctAnswers.length];
for(int i = 0; i < 15; i++) //print question numbers/takes user input
{
System.out.println("Question " + (i + 1) + ":");
userAnswer [i] = input.nextLine().charAt(0);
}//end of for loop
System.out.println("number correct: " + total_correct_answers(correctAnswers, userAnswer));
input.close();
}//end of main
public static int total_correct_answers(char []correctAnswers,char [] userAnswer) {
int number_correct = 0;
for (int i = 0; i < 15; i++){
if(correctAnswers[i] == userAnswer[i]){
number_correct++;
}
}//end of for loop
return number_correct;
}//end of correct method
}//end of class