Home > Software engineering >  Nested if statement with While loop stuck
Nested if statement with While loop stuck

Time:03-19

The code is for multiple choice question. If the answer is incorrect, the user should try until they find the right answer. When the answer is correct, there is no problem, but if it is wrong then it gets stuck, and it is keep saying "Your answer is incorrect!". What should I do?

import java.util.*;

public class Question {

    public static void main(String[] args) {
  
        System.out.println();
        System.out.println("Question 1");
        System.out.println();
        System.out.println("What is 2 2?");
        System.out.println("A. 2");
        System.out.println("B. 4");
        System.out.println("C. 6");
        System.out.println("D. 8");

        Scanner input = new Scanner(System.in);
        char getAnswerFromUser = input.next().charAt(0);
        char answer = 'B';

        boolean isAnswerTrue = false;

     
        while(!isAnswerTrue) {
            if(getAnswerFromUser == answer ) {
                System.out.println("Your answer is correct!");
                    isAnswerTrue = true;
            } else{
                System.out.println("Your answer is incorrect!");
                isAnswerTrue = false;
            }       
        }
    }   
}

CodePudding user response:

You are not actually getting a new answer from the user inside your loop. You are only getting it once, in the line where you define the variable getAnswerFromUser. You need to actually get a new answer. I suggest putting it into a separate method to keep that step clean from the step where you use that answer.

  • Related