Atorres7
Atorres7

Reputation: 1

Java: Inputting 10 multiple choice A,B,C,or D and outputting number correct, incorrect and grade

Hi I need some help with an assignment I have been asked to do and I'm pretty sure I am right near the finish but need a few things to clear up. I am tasked with getting the name of a student, inputting their 10 answers and matching them up with the answers of the answer key. There is one catch however, whatever is input as an answer has to be A, B, C or D and if it is something else I have to ask for the answer to be inputted again. So I changed the input into char and created a while statement to see if what is input does not equal A,B,C or D to be prompted to type in A,B,C, or D and prompted again for the answer. BUT it keeps asking me for A,B,C, or D even if I put in A,B,C or D. Please help, thanks

import javax.swing.JOptionPane;

public class assignment3 {
    public static void main(String[] args) {
    // TODO Auto-generated method stub
        int i = 0;
        String answer;
        int grade = 0;
        int correct =0;
        int incorrect =0;
        char input;
        char inputarray[]=new char [10];
        char[] answerkey = 
            { 'B','D', 'C', 'D', 'C', 'A', 'C', 'B', 'B', 'D' };
        String Name = JOptionPane.showInputDialog("Enter Name");
        for (i = 0; i< answerkey.length; i++) { 
        answer = JOptionPane.showInputDialog("Enter answer for question " + (1+i)); 
        input = answer.charAt(0);
        while (input != 'A' || input != 'B' || input != 'C' || input != 'D')  { 
           JOptionPane.showMessageDialog(null, "Please enter A,B,C, or D");
           answer = JOptionPane.showInputDialog("Enter answer for question "(1+i));
           input = answer.charAt(0);
        }
        inputarray[i] = input;
        i++;
        while (i < answerkey.length)
        {
            if (inputarray[i] == answerkey[i])
                correct++;
            else
                incorrect++;
        }
    }
    grade = ((correct++) / (answerkey.length)) * 100;
    JOptionPane.showMessageDialog(null, "Name: " + Name + "Answers Correct: "+ correct + "Answers Incorrect: "+ incorrect + "Grade: " + grade+ "%");
}
}

Upvotes: 0

Views: 2397

Answers (1)

rgettman
rgettman

Reputation: 178293

Your logic in this line is incorrect.

while (input != 'A' || input != 'B' || input != 'C' || input != 'D') 

It's always true that it's not 'A' or it's not 'B' or it's not 'C' or it's not 'D'. Try this instead:

while (input != 'A' && input != 'B' && input != 'C' && input != 'D') 

Incidentally, in Java, integer division will truncate your answer (an int divided by an int must yield an int), as in this line:

grade = ((correct++) / (answerkey.length)) * 100;

Declare grade as a double and cast one of the variables in the calculation as a double:

grade = ( (double) (correct++) / (answerkey.length)) * 100;

Upvotes: 4

Related Questions