使用循环返回命令选项时出现问题/仅运行一个命令(JAVA)
这是我第一次访问这个网站。我现在正在学习Java课程,我在编写这个代码/程序时遇到了一些问题,该代码/程序允许用户选择他们是想看“好猴子”、“坏猴子”还是“秀猴子”。虽然还远未完成,但我在命令完成后返回命令屏幕/区域时遇到问题。我希望命令被尽可能多地使用。其次,如果有人输入“goodmonkey”,我的程序会处理每个输入。因此,如果你输入一个像“菠萝”这样的词,它仍然会用指定为“好猴子”输入的输出来问候你
我在网上看过,也许我应该使用“do while”循环并使用“switch”。如有任何意见/帮助,将不胜感激。非常感谢你
这是我的代码:public类、public static和Scanner import都在这段代码中,但由于某些原因,我无法将它们添加到这篇文章中,而不会弄乱代码的格式
Scanner jScanner = new Scanner(System.in);
System.out.println("please enter Good Monkeys, Bad Monkeys or Show Monkeys");
String userChoice = jScanner.nextLine();
for (int b= 1; b < 11000; b++)
{
if (userChoice.equalsIgnoreCase("Good Monkeys"));
{
System.out.println("You have selected Good Monkeys");
System.out.println("How many monkeys do you want? Put in a integer between 3 and 20");
Scanner goodMonkeyScanner = new Scanner (System.in);
int userChoiceGood = goodMonkeyScanner.nextInt();
if (userChoiceGood >= 3 && userChoiceGood <= 20)
{
System.out.println("Here you go");
System.out.println("Monkeys (metapohorical)");
break;
}
else if (userChoice.equalsIgnoreCase("Bad Monkeys"))
{
System.out.println("You have selected Bad Monkeys");
System.out.println("How many monkeys do you want? Put in a integer between 3 and 20");
Scanner badMonkeyScanner = new Scanner (System.in);
int userChoiceBad = badMonkeyScanner.nextInt();
if (userChoiceBad >= 3 && userChoiceBad <= 20)
{
System.out.println("Here you go");
System.out.println("Monkeys (metapohorical)");
break;
}
else
System.out.println("Sorry this doesn't work");
}
else if ((userChoice.equalsIgnoreCase("Show Monkeys")))
{
System.out.println("Monkeys");
System.out.println("0");
System.out.println("\\/");
System.out.println(" |");
System.out.println("/\\");
break;
}
else
{
System.out.println(" Wrong Answer. Try again");
}
break;
}
}
}
}
# 1 楼答案
首先,需要定义循环。其次,需要将输入指令放入循环中
我将包含一个
done
变量来检测用户何时想要转义那么,让我们编写代码:
代码说明:
while(!done)
东西可以理解为“当‘未完成’时,做下面的事情”userChoice.toLowerCase()
:我将{switch(userChoice.toLowerCase())
:。。。六羟甲基三聚氰胺六甲醚。。。我想你可以自己解决;)default
块"done"
块将done
变量设置为true
,从而终止循环break
结束case
块进一步阅读:
另外,我建议你学习Flowcharts,在开始编码之前,试着在纸上画出你的程序流程图。这样,在开始编写第一行代码之前,您将有一个清晰的程序图像