Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a do-while loop that checks for input validation

Tags:

java

For example, I want a loop that prints out "Do you want to watch a movie?" until the user enters "yes".

Here's what I have so far:

import java.util.Scanner;

public class Testing {
    public static void main(String args[]){
        Scanner scan = new Scanner(System.in);
        do {
           System.out.println("Do you want to watch a movie?");
           scan.nextLine();
           String Answer = scan.next();
        }
        while (!Answer.equals("yes"));
like image 396
yasuomainbtw Avatar asked Mar 12 '26 09:03

yasuomainbtw


1 Answers

the test condition is out of the scope of the { and } where you read it, so move the declaration of String answer (lowcase) to before of the do statement so we can test it outside the block (the while instruction is out of itand is the condition to execute the block again).

And, nextLine() returns and consume the value readed, the result will be it.

    String answer;
    do {
       System.out.println("Do you want to watch a movie?");
       answer = scan.nextLine();
    } while(!answer.equals("yes"));
like image 101
Marcos Vasconcelos Avatar answered Mar 13 '26 23:03

Marcos Vasconcelos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!