Java statement While Doing with two conditions

I'm trying to learn java, but I'm stuck trying to make one program that deals with a Do While Statement with two conditions. In particular, I want the method to be executed until the user writes yes or no. Well, here's my thing, what's wrong with that?

    String answerString;
    Scanner user_input = new Scanner(System.in);
    System.out.println("Do you want a cookie? ");

    do{
    answerString = user_input.next();
    if(answerString.equalsIgnoreCase("yes")){
        System.out.println("You want a cookie.");
    }else if(answerString.equalsIgnoreCase("no")){
        System.out.println("You don't want a cookie.");
    }else{
        System.out.println("Answer by saying 'yes' or 'no'");
    }while(user_input == 'yes' || user_input == 'no');
    }
}}
+4
source share
2 answers

I would do something similar to Tim's answer. But in order to do what you tried to do, you have many problems that need to be addressed:

(1) String literals in Java are surrounded by double quotes, not single quotes.

(2) user_input Scanner. . String String. , answerString , user_input.

(3) == . StackOverflow 953 235 Java, 826 102 , - == . (, .) equals: string1.equals(string2).

(4) do-while, do, {, , }, while(condition);. , } . } while else, ; } while, .

(5) , , , yes no. : , , yes no. while :

while (!(answerString.equals("yes") || answerString.equals("no")));

[ , equalsIgnoreCase, .] ! "" , , !, ! . , "Loop blah-blah-blah", "Loop while ! (blah-blah-blah)".

+4

do, , "" "", .

do {
    answerString = user_input.next();

    if ("yes".equalsIgnoreCase(answerString)) {
        System.out.println("You want a cookie.");
        break;
    } else if ("no".equalsIgnoreCase(answerString)) {
        System.out.println("You don't want a cookie.");
        break;
    } else {
        System.out.println("Answer by saying 'yes' or 'no'");
    }
} while(true);
+2

Source: https://habr.com/ru/post/1614217/


All Articles