Skip to content
← Back to Community
Java programming question
Profile icon
mwabonje1

The following code should count the number of correct responses and give me the count at the end. when there is invalid input it should loop the question until valid input is keyed whether right or wrong. However, it is not able to recognize valid wrong answers from invalid answers

Voters
Profile icon
AtienzaGuidel
Profile icon
mwabonje1
Comments
hotnewtop
Profile icon
a5rocks

You forgot to put braces around the stuff in the else statement on line 14.

Also, you forgot to put a break in the else if.

ALSO, you did answer2 != ("B")||answer2 !=("C")||answer2 !=("D")||answer2 !=("E"), which isn't correct as (if you apply basic boolean algebra rules) you are just checking if the answer isn't simultaneously B, C, D, and E. Basically, answer2 != ("B")||answer2 !=("C") is always going to be true, true||whatever is always going to be true.

Profile icon
mwabonje1

import javax.swing.JOptionPane;
public class Test {

public static void main(String[] args) { // TODO Auto-generated method stub int count = 0; String question = "12 * 12?\n"; question += "A.144 \nB.132 \nC.123 \nD.234 \nE.125 \n"; String answer = JOptionPane.showInputDialog(question); answer = answer.toUpperCase(); if (answer.equals("A")) { count = count + 1; } else if (answer.equals("B")||answer.equals("C")||answer.equals("D")||answer.equals("E")) { } else; JOptionPane.showMessageDialog(null,"Choose between A to E."); answer = JOptionPane.showInputDialog(question); String question2 = "12 * 12?\n"; question2 += "A.144 \nB.132 \nC.123 \nD.234 \nE.125 \n"; String answer2 = JOptionPane.showInputDialog(question2); answer2 = answer2.toUpperCase(); if (answer2.equals("A")) { count = count + 1; } else if (answer.equals("B")||answer.equals("C")||answer.equals("D")||answer.equals("E")) { } else; JOptionPane.showMessageDialog(null,"Choose between A to E."); answer = JOptionPane.showInputDialog(question); } JOptionPane.showMessageDialog(null, "You have gotten" + count+ " questions correct!");

}

i have done the above code but it is not working as per my expectation. I wanted it to record right answers and show me the number of questions i got. Also it should tell me to input a valid answer if one has entered a choice that isn't available.