Java中的循环逻辑

Jor*_*nes 1 java loops

我有一段时间没有编程,我正试图回到事物的摇摆中,这是我已经走了多远.我的问题是,如何循环第二个问题,以便如果响应是除了是或否之外它再次询问问题.我试过在if语句周围放一个循环,但每当我尝试从用户那里得到另一个响应时,它告诉我我不能使用变量,响应,这样做.我觉得这是一个简单的解决方法,我理解循环,但我很难绕过这个具体问题,谢谢你提前.

import java.util.Scanner;
public class Practice {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Welcome to my simulation, please enter your name");
        String name = input.nextLine();
        System.out.println("Welcome " + name + " would you like to play a game?");
        String response = input.nextLine();


        boolean yes = new String("yes").equals(response.toLowerCase());
        boolean no = new String("no").equals(response.toLowerCase());


        if (yes){
            System.out.println("Which game woudl you like to play?");
        }else if (no){
            System.out.println("Fine then, have a good day!");
        }
        else{
            System.out.println("please enter either yes or no");
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

shm*_*sel 5

有很多方法可以做到这一点.这是我想到的第一个:

while (true) {
    response = input.nextLine().toLowerCase();
    if (response.equals("yes") {
        System.out.println("Which game woudl you like to play?");
        break;
    } else if (response.equals("no") {
        System.out.println("Fine then, have a good day!");
        break;
    } else {
        System.out.println("please enter either yes or no");
    }
}
Run Code Online (Sandbox Code Playgroud)