I'm making an application that quizzes you on politics or astronomy.
My problem is that when you say "politics" or you say "astronomy", it will ask you again 2 more times for your input, before giving the desired output of "test".
Here's the code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
do {
if (getAnswer().equalsIgnoreCase("neither")) {
System.out.println("Please enter \'astronomy\' or \'politics\'.");
}
getAnswer();
}
while(getAnswer().equalsIgnoreCase("neither"));
System.out.println("test");
}
public static String getAnswer() {
Scanner quizType = new Scanner(System.in);
System.out.println("Would you like to be quizzed on politics or astronomy?");
String typeAnswer = quizType.next();
if (typeAnswer.equalsIgnoreCase("politics")) {
return "politics";
}
else if (typeAnswer.equalsIgnoreCase("astronomy")) {
return "astronomy";
}
else {
return "neither";
}
}
}
Any ideas?
Thanks
There no need to getAnswer() 3 times, just getAnswer() into a String variable and you are good to go.
Like this:
public static void main(String[] args) {
String answer = "";
do {
answer = getAnswer();
if (answer.equalsIgnoreCase("neither")) {
System.out.println("Please enter \'astronomy\' or \'politics\'.");
}
} while (answer.equalsIgnoreCase("neither"));
System.out.println("test");
}
public static String getAnswer() {
Scanner quizType = new Scanner(System.in);
System.out.println("Would you like to be quizzed on politics or astronomy?");
String typeAnswer = quizType.next();
if (typeAnswer.equalsIgnoreCase("politics")) {
return "politics";
} else if (typeAnswer.equalsIgnoreCase("astronomy")) {
return "astronomy";
} else {
return "neither";
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With