0

I made a program that answers individual questions and I would like it to end after asking 3 questions in any order. I only did that when I write Bye, the program will end and I don't know how to turn it into these 3 questions. I would like the answer to this question to be related to this code, please

import java.util.Scanner;
    
class Bot {
    public static void main(String[] args) {
        System.out.println("QUESTIONS: How old are you? | What is your name? | What did you eat for breakfast?");
        System.out.println("Ask a question?");
    
        Scanner pytania = new Scanner(System.in);
        String input;
        
        boolean running = true;
        while (running) {
            System.out.println(" ");
            input = pytania.nextLine();
    
            if (input.equals("How old are you?")) {
                System.out.println("I am 125 years old");
            } else if (input.equals("Bye")) {
                System.out.println("Bye!");
                running = false;
            } else if (input.equals("What is your name?")) {
                System.out.println("My name is Christopher");
            } else if (input.equals("What did you eat for breakfast?")) {
                System.out.println("I had scrambled eggs for breakfast");
            } else {
                System.out.println("Sorry, I don't understand the question!");
            }
        }
    }
}
0009laH
  • 1,960
  • 13
  • 27
mrspjsh
  • 9
  • 3
  • 1
    Hi & welcome! ..introduce variable (before while loop) `int count = 0;` ..change your while condition to `while(running && count < 3)`.. increment `count` in the according blocks (alternatively: increment it "generally"& decrement "where needed") – xerx593 Oct 24 '22 at 20:23
  • Add an `int` variable, initialized to 0, and increase it for each question. Set `running` to `false` when your counter is 3. – Robert Oct 24 '22 at 20:23
  • Sorry Basil, but none of the dupes you linked would actually answer this question. This one's deceptively more straightforward than just a forever-loop for a break. – Makoto Oct 24 '22 at 20:31

1 Answers1

1
  1. Change running from boolean to int. Call it runningCount.
  2. Establish your while loop to only run while runningCount < 3.
  3. In each question, increment runningCount.

The application will stop after you ask three questions as you require.

Makoto
  • 104,088
  • 27
  • 192
  • 230