gpt4 book ai didi

java - 如何让我的代码继续编码直到输入 "0"

转载 作者:行者123 更新时间:2023-11-30 12:02:50 24 4
gpt4 key购买 nike

您好,我遇到了麻烦。

让键 8、4、2 和 6 分别为北、西、南和东。每当用户选择这些选项之一时,输出 You moved direction where direction is the appropriate direction。如果用户输入零,这也是一个菜单选项,则退出。

    public static void main(String[] args)
{

Scanner keyboard = new Scanner(System.in);

System.out.println("Which direction would you like to move?");
System.out.println("[8] North");
System.out.println("[4] West");
System.out.println("[2] South");
System.out.println("[6] East");
System.out.println("[0] Exit");
int input = keyboard.nextInt();



while (input == 8)
{
System.out.println("You moved north.");
System.out.println("Which direction would you like to move?");
System.out.println("[8] North");
System.out.println("[4] West");
System.out.println("[2] South");
System.out.println("[6] East");
System.out.println("[0] Exit");
input = keyboard.nextInt();
}


while (input == 4)
{
System.out.println("You moved west.");
System.out.println("Which direction would you like to move?");
System.out.println("[8] North");
System.out.println("[4] West");
System.out.println("[2] South");
System.out.println("[6] East");
System.out.println("[0] Exit");
input = keyboard.nextInt();
}
while (input == 2)
{
System.out.println("You moved south.");
System.out.println("Which direction would you like to move?");
System.out.println("[8] North");
System.out.println("[4] West");
System.out.println("[2] South");
System.out.println("[6] East");
System.out.println("[0] Exit");

input = keyboard.nextInt();
}

while (input == 6)
{
System.out.println("You moved east.");
System.out.println("Which direction would you like to move?");
System.out.println("[8] North");
System.out.println("[4] West");
System.out.println("[2] South");
System.out.println("[6] East");
System.out.println("[0] Exit");

input = keyboard.nextInt();
}

}
}

最佳答案

当您读取 8 时,您的代码会卡在 while (input==8) 循环中。然后,一旦 6 到达,它就会退出该循环并进入 while (input==6) 循环。此时除 6 以外的任何数字都将退出该循环并终止程序。

您可能想要的是将大量小循环替换为一个不断询问用户输入并打印其选择结果的循环。像这样的东西:

do{
//display menu
//read user's choice
//react to user's choice
}while(input != 0)

关于java - 如何让我的代码继续编码直到输入 "0",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58208021/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com