Skip to content

Instantly share code, notes, and snippets.

@ericel
Created February 20, 2020 10:40
Show Gist options
  • Save ericel/bcf941d4e9bdf9eb9b1f1c44b5d75647 to your computer and use it in GitHub Desktop.
Save ericel/bcf941d4e9bdf9eb9b1f1c44b5d75647 to your computer and use it in GitHub Desktop.
package unit_2;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* SIMPLE QUIZ UNIT_2 UOPEOPLE.
* A simple Quiz that asks uses a question.
* @author ericel123
*/
import javax.swing.JOptionPane;
public class Quiz {
public static void main(String[] args) {
String question = "What is the name of the Stoic Roman emperor?\n";
question += "A. Seneca The Younger\n";
question += "B. Marcus Aurelius\n";
question += "C. Epictetus\n";
question += "D. Zeno The Citium\n";
question += "E. Donald J. Trump\n";
// Create a set for possible valid answers
String[] posible_answers = {"A", "B","C", "D", "E"};
Set<String> answersset = new HashSet<String>(Arrays.asList(posible_answers));
// Error Responses
String invalid;
String incorrect;
invalid = "<html><span style='font-size:2em; color: red;'><br>Invalid answer. Please enter A, B, C, D, or E.<br>";
incorrect = "<html><span style='font-size:2em; color: red;'><br>Incorrect! Try again.<br>";
// Dialog to prompt user for an answer
String answer = JOptionPane.showInputDialog(question);
while(true) {
// To take care of Case Sensitive Answers
answer = answer.toUpperCase();
// If valid answer
if (answersset.contains(answer) && answer.equals("B")) {
JOptionPane.showMessageDialog(null,"<html><span style='font-size:2em; color: green;'>Correct! It's Marcus Aurelius");
break;
} else if(answersset.contains(answer) && !answer.equals("B")){
// If valid answer but incorrect answer
// Clean up Errors
if(question.indexOf(invalid) != -1)
question = question.replace(invalid, "");
if(question.indexOf(incorrect) == -1)
question += incorrect;
// Prompt User for the right answer
answer = JOptionPane.showInputDialog(question);
} else {
question.replace(incorrect, " ");
// If it's invalid answer
// Clean up Errors
if(question.indexOf(incorrect) != -1)
question = question.replace(incorrect, "");
if(question.indexOf(invalid) == -1)
question += invalid;
// Prompt User for the right answer
answer = JOptionPane.showInputDialog(question);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment