Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Nested if statement with While loop stuck

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;
            }       
        }
    }   
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading