我正在尝试制作一个“选择”菜单,其中我使用了一个开关/案例函数来让用户选择。我的代码中的问题是,我希望它一直要求输入,直到用户输入"sair“,在葡萄牙语中,意思是”退出“。当他们键入"ajuda“(意为”帮助“)时,他们会得到一个可执行命令的列表,但是如果用户键入"ajuda”,则"sout“被执行并生成完毕,程序就在那里结束.我的目标是让它运行,直到我们选择停止,我认为有一种方法使用readln或类似的。
无论如何,下面是关于选择的代码块:
public static String escolha() {
Scanner userInput = new Scanner(System.in);
String strEscolha = userInput.next();
boolean sair = false;
do {
switch (strEscolha) {
case "ajuda":
System.out.println("Comandos disponiveis:");
System.out.println("Ajuda; Fogo; Jogo; Resposta; Estado; Acaso; Reset; Sair;");
break;
case "Ajuda":
System.out.println("Comandos disponiveis:");
System.out.println("Ajuda; Fogo; Jogo; Resposta; Estado; Acaso; Reset; Sair;");
break;
case "sair":
System.out.println("Obrigado por jogar!");
sair = true;
break;
default:
System.out.println("Comando Invalido!");
continue;
}
} while (sair == false);
return null;
}
如果有人有一个简单的方法使它不断要求命令,请让我知道:(谢谢提前!PS:我刚开始,请不要评判,我对java的知识是可以忽略的:\
发布于 2016-01-10 21:32:20
您的代码的主要问题是,您不请求用户输入在“ajuda”的情况下。
下面是一些小改动的代码,以及一些评论和建议:
// if your method isn't supposed to return anything, simply make it void
public static void escolha() {
Scanner userInput = new Scanner(System.in);
// print some useful information when the application starts, so that the user knows
// what to do
System.out.println("Comandos disponiveis:");
System.out
.println("Ajuda; Fogo; Jogo; Resposta; Estado; Acaso; Reset; Sair;");
String strEscolha = userInput.next();
boolean sair = false;
do {
// remove duplicate case by converting the input to lower letters
switch (strEscolha.toLowerCase()) {
case "ajuda":
System.out.println("Comandos disponiveis:");
System.out
.println("Ajuda; Fogo; Jogo; Resposta; Estado; Acaso; Reset; Sair;");
// read the user input
strEscolha = userInput.next();
System.out.println(strEscolha);
break;
case "sair":
System.out.println("Obrigado por jogar!");
sair = true;
break;
default:
System.out.println("Comando Invalido!");
}
} while (sair == false);
// do not forget to close the scanner, it might cause a memory leak
userInput.close();
}
发布于 2016-01-10 20:52:40
首先,删除System.exit
,否则您将在不执行后续代码的情况下关闭整个JVM (您的IDE可能给了您一个关于此的死代码警告)。
其次,您需要使用sair == false
(或者更好的是!sair
)而不是sair = false
。前者是比较,后者是赋值,使sair
错误。
do { ... } while (false)
将执行循环体一次,但不会重复。
第三,在紧接return strEscolha;
之前的while
将导致方法在尝试循环之前返回,因此应该删除它。
https://stackoverflow.com/questions/34710620
复制相似问题