我有一个小问题。 我有一个菜单要求:
当用户选择一个选项时我希望它做其中一个选项然后在一个无限循环中询问菜单:
代码:
import java.io.InputStream;
import java.util.Scanner;
class RecordDice {
public static void main(String[] args){
int dSides, Sides, Choice;
int max, min;
Scanner s = new Scanner(System.in);
Scanner c = new Scanner(System.in);
System.out.println("How many sides should the dice have?");
Sides = s.nextInt();
if(Sides == 4 || Sides == 6 || Sides == 12 || Sides == 20 || Sides == 100){
System.out.println("Please make a choice:\n" +
"1 - reroll the dice\n" +
"2 - get the value\n" +
"3 - show the maximum\n" +
"4 - show the minimum");
} else {
System.exit(-1);
}
Dice2 d = new Dice2(Sides);
int Choice = c.nextInt();
int Value = d.getValue();
switch(Choice){
case 1:
System.out.println();
d.reroll();
break;
case 2:
System.out.println("The current value is " + Value);
break;
case 3:
System.out.println("The maximum is " );
break;
case 4:
System.out.println("The minimun is ");
break;
}
}
}
将菜单放在方法中,每次选择一个选项时只调用该方法吗?
答案 0 :(得分:1)
将"5 - quit"
添加到您的菜单中。
创建boolean
,例如exit
,初始化为false
。
添加case 5: exit = true; break;
然后将整个事物包裹在while(!exit)
boolean exit = false;
while(!exit) {
//all the code you already have, starting with:
System.out.println("How many sides should the dice have?");
//and ending with the switch statement
//Plus the addition to the menu and addition to the switch statement
}
通常,我会这样做:
while(true) {
//do stuff
if(someExitCondition) {
break;
}
}
但是看看当你使用switch
语句处理用户输入时,我上面提出的方法似乎是在这种情况下处理它的最简洁的方法。
答案 1 :(得分:1)
您可以使用while循环继续显示它。
boolean keepGoing = true;
While(keepGoing)
{
//your code
}
然后结束它询问用户是否要结束它将布尔值设置为false。
答案 2 :(得分:0)
在do-while循环中包装所有内容。
boolean userWantsToQuit = false;
do {
// code
// evaluate userWantsToQuit…
} while (!userWantsToQuit);
答案 3 :(得分:0)
boolean keepGoing=true;
while(keepGoing)
{
//user input
if(user input to exit)
{
keepGoing=false;
}
}
或
while(true)
{
//user input
if(user input to exit)
{
break;
}
}
答案 4 :(得分:0)