'Read in input text Yes/No Boolean from user to proceed the next step

I amm at my very beginning at java and just wanted to ask. I want to ask the user to put Yes/No to a question and proceed to the next question. How do I do it?

import java.util.Scanner;

public class sff {
    
    public static void main (String args[]) {

        System.out.println("Hello There! We want to ask you some questions! but first: ");
        System.out.print("Enter your age: "); 
        
        Scanner in = new Scanner(System.in);
        int num = in.nextInt();
        
        int age = num;

        if( age == 12){
            System.out.println("Hello Dan, I know you very well! ");    
        }
        
        {
        
        System.out.println("First question: ");
        System.out.println("Do you exercise?(Yes/No) ");
        // how do i proceed from here??


Solution 1:[1]

Are you looking for something like this?

//import to use the Scanner
import java.util.Scanner;

public class Stack_Overflow_Example {
    public static void main(String[] args) {

    System.out.println("First question: ");
    System.out.print("Do you exercise?(Yes/No) ");
    Scanner in = new Scanner(System.in);
    //get the user input and store it as a String
    String exerciseQuestion = in.nextLine();
    //check what the user said.
    if(exerciseQuestion.equalsIgnoreCase("yes")){
        System.out.println("Dan does exercise");
        //do you code when he exercises
    }
    else{
        System.out.println("Dan does not exercise");
        //do your not exercise code here
    }
    System.out.println("Ask your next question so on....");

  }//main
}//class

If you want to deal with answers other than yes/no you can use this code:

import java.util.Scanner;

public class Stack_Overflow_Example {
    public static void main(String[] args) {

    System.out.println("First question: ");
    System.out.print("Do you exercise?(Yes/No) ");
    Scanner in = new Scanner(System.in);
    String exerciseQuestion;
    while (true){
        //get the user input
        exerciseQuestion = in.nextLine();
        //check if user input is yes or no
        if((exerciseQuestion.equalsIgnoreCase("yes")) || 
                     exerciseQuestion.equalsIgnoreCase("no"))
            //if yes break and continue with your code
            break;
        else
            //else loop back to get user input until answer is yes/no
            System.out.println("Please answer with yes or no only");

    }//while . i.e answer not yes or no
    if(exerciseQuestion.equalsIgnoreCase("yes")){
        System.out.println("Dan does exercise");
       //do your code
    }
    else{
        System.out.println("Dan does not exercise");
        //do your not exercise code here
    }//else

  }//main
}//class

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1