一旦响应正确,如何终止while循环?

use*_*047 1 java string user-input while-loop

如果你输入"热/冷",我正在制作这个程序,上面写着"拿一些冰淇淋"/"穿上夹克".但是,即使输入热/冷,程序仍然会在while循环中继续运行.如何让这个程序不断询问用户的状况,直到他们正确回答两个答案中的一个,并防止它在用户键入正确答案后不断询问响应?

import java.util.Scanner;

public class IfStatement {
    public static void main(String[] args) {
        boolean run = true;

        while(run) {

        System.out.println("What is your condition: ");
        Scanner input = new Scanner(System.in);
        String x = input.nextLine();

        if(x.equals("hot"))
            System.out.println("Get some ice cream");

        else if(x.equals("cold"))
            System.out.println("Put on a jacket");

        else
            System.out.print("Try again, what is your condition: ");
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

gef*_*fei 5

你的循环只要迭代就run可以了true.因此,您需要做的是在输入正确后设置runfalse.像这样

if(x.equals("hot")){
   System.out.println("Get some ice cream");
   run = false;  // setting run to false to break the loop
}    

else if(x.equals("cold")) {
   System.out.println("Put on a jacket");
   run = false; // setting run to false to break the loop
}
Run Code Online (Sandbox Code Playgroud)