Reputation: 39
Today I was messing around and I was trying to create a multiple choice test. I got this far and it works. I was wondering though, how would I make it repeat the question if the user got the answer wrong? If anyone could help me out that would be fantastic! Thanks!
import java.util.Scanner;
public class multipleChoiceTest {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
System.out.println("What color is the sky?");
System.out.println("A. Blue");
System.out.println("B. Green");
System.out.println("C. Yellow");
System.out.println("D. Red");
String userChoice = myScanner.nextLine();
if (userChoice.equalsIgnoreCase("a")) {
System.out.println("You're right!");
} else {
System.out.println("You're wrong! Try Again.");
}
}
Upvotes: 2
Views: 2481
Reputation: 221
You can use While statement in this case! Let's look at it this way: as long as the user doesn't answer correctly, you will not continue. Now change "as long as" with "while(...)" We'll get this code:
Scanner myScanner = new Scanner(System.in);
System.out.println("What color is the sky?");
System.out.println("A. Blue");
System.out.println("B. Green");
System.out.println("C. Yellow");
System.out.println("D. Red");
String userChoice = myScanner.nextLine();
while(! userChoice.equalsIgnoreCase("a")){
System.out.println("You're wrong! Try Again.");
userChoice = myScanner.nextLine();
}
System.out.println("You're right!");
(Remember, we need to take a new input after he got it wrong the previous time!)
Upvotes: 4
Reputation: 8960
public static void main(String[] args)
{
Scanner myScanner = new Scanner(System.in);
System.out.println("What color is the sky?");
System.out.println("A. Blue");
System.out.println("B. Green");
System.out.println("C. Yellow");
System.out.println("D. Red");
while(true) // Infinite loop
{
String userChoice = myScanner.nextLine();
if (userChoice.equalsIgnoreCase("a"))
{
System.out.println("You're right!");
break; // If user was correct, exit program
}
else
{
System.out.println("You're wrong! Try Again.");
}
}
}
Upvotes: 0