I'm trying to create a quiz project on Java. The code seeems to be going fine. However, I want it to only take only String as an input and that if the user tries to enter anything other than a String, a message will pop-up that says they should enter a letter and let them try that item again. I am supposed to do a try-catch exception but if I input anything other than a String, InputMismatchException doesn't pop-up.
public class Question {
String prompt;
String answer;
public Question(String prompt, String answer) {
this.prompt = prompt;
this.answer = answer;
}
}
import java.util.Scanner;
public class App {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
String q1 = "What is the hottest planet in the Solar System?\n"
"a. Mercury\nb. Venus\nc. Jupiter";
String q2 = "Who is the hottest instructor in the IT Department?\n"
"a. Sir Harly\nb. Sir Daryll\nc. Sir Rhady";
String q3 = "What is largest planet in the Solar System\n"
"a. Mercury\nb. Venus\nc. Jupiter";
String q4 = "What is the closest planet in the Sun?\n"
"a. Mercury\nb. Venus\nc. Jupiter";
String q5 = "What is the Earth's 'Twin Sister'?\n"
"a. Mercury\nb. Venus\nc. Jupiter";
String q6 = "Which among these three is a 'Gas Giant'?\n"
"a. Mercury\nb. Venus\nc. Jupiter";
String q7 = "What planet is Olympus Mons located?\n"
"a. Saturn\nb. Mars\nc. Uranus";
String q8 = "Which among these three planet doesn't have a ring?\n"
"a. Saturn\nb. Mars\nc. Uranus";
String q9 = "Which of these planet appears to spin on its side, orbiting the Sun like a rolling ball.?\n"
"a. Saturn\nb. Mars\nc. Uranus";
String q10 = "On which planet does the Great Red Spot, a long-lived enormous storm system, located?\n"
"a. Jupiter\nb. Mars\nc. Uranus";
Question [] questions = {
new Question(q1, "b"),
new Question(q2, "a"),
new Question(q3, "c"),
new Question(q4, "a"),
new Question(q5, "b"),
new Question(q6, "c"),
new Question(q7, "b"),
new Question(q8, "b"),
new Question(q9, "c"),
new Question(q10, "a")
} ;
takeTest(questions);
}
public static void takeTest(Question [] questions) {
int score = 0;
Scanner userInput = new Scanner(System.in);
for (int i = 0; i < questions.length; i ) {
System.out.println(questions[i].prompt);
String answer = userInput.next();
if(answer.equalsIgnoreCase(questions[i].answer)) {
score ;
}
}
System.out.println("Your score is: " score "/" questions.length);
}
}
CodePudding user response:
Do you want to check if the answer is only one char and one of a, b or c?
private boolean isStringABC(String s){ return (s.length()==1 && (s.toLowerCase().charAt(0)=='a' || .toLowerCase().charAt(0)=='b' || s.toLowerCase().charAt(0)=='c'); }
CodePudding user response:
I think your methodology is incorrect, but if you're really married to the idea of testing for numbers, just use regex.
//Create a pattern
private static final Pattern pattern = Pattern.compile("\\d");
//testing method
public static boolean hasDigit(String input) {
Matcher matcher = pattern.matcher(input);
boolean found = matcher.find();
if (found) {
System.out.println(input " contains a digit.");
} else {
System.out.println(input " does not contain a digit");
}
return found;
}
public static void main(String[] args) throws IOException {
String good = "abc";
String bad = "a1c";
hasDigit(good);
hasDigit(bad);
}
CodePudding user response:
I am assuming this is some kind of homework assignment to learn try-catch and exceptions. If that is the case:
Exceptions are thrown by functions if you try to do something that is not allowed. To catch this error you surround the function that throws the exception with a try catch block. In this case the Scanner should throw an error, because the user might not input the correct value. The user can input a bad value when userInput.next();
is called, so this is the code we want to surround with the try-catch block. To catch the InputMismatchException we put in in between the paranthesis after the catch. Like this:
...
try {
String answer = userInput.next();
}
catch(InputMismatchException e) {
// Block of code to handle errors
}
...
There is one problem however. If we look in the documentation we can see that Scanner.next() does not throw a InputMismatchException, so this will do nothing. I can think of three easy ways to fix this.
- Rewrite the program with a function that does throw the InputMismatchException like Scanner.nextInt(). You would need to change your question options from a, b, c to 1, 2, 3. However, this would still allow a user to input 489 when the only options are 1, 2, 3.
- Add a regex pattern to your next function. See Scanner.next(Pattern pattern). If the pattern does not match you will get a NoSuchElementException.
- Write your own function that throws a InputMismatchException if the input is not a, b or c. Something like this:
public static void checkAnswer(String str) {
if (str != "a" || str != "b" || str != "c") {
throw new InputMismatchException();
}
}
Here is a bit more info on try-catch blocks and exceptions if your interested. https://www.w3schools.com/java/java_try_catch.asp
I hope this helps!