gpt4 book ai didi

java - 如何结束开关内部的开关。 java

转载 作者:行者123 更新时间:2023-12-01 19:12:49 25 4
gpt4 key购买 nike

我正在尝试在开关内进行开关。我已经编译它了,但唯一的事情是,每次运行它时,我都会为第一个开关选择一个案例,一旦我为开关内部的第一个开关选择一个案例,它就会还要求我为第一个开关内的第二个开关选择一个案例,然后是第三个开关,然后结束。在选择开关内的第一个开关后,如何使整个程序重新从头开始,或者结束程序。谢谢。

例如。

System.out.println("Pick a color.\n");

System.out.println(" 1. Red");
System.out.println(" 2. Blue");
System.out.println(" 3. Yellow");
System.out.println(" 4. Green");

Scanner kbReader = new Scanner(System.in);
int color = kbReader.nextInt();

System.out.println("The color you chose was " + color + ".");
String s1 = kbReader.nextLine();

switch (color)
{
case 1: //Red
System.out.println("Now enter an integer from 1 through 10.");
int num1 = kbReader.nextInt();

switch (num1)
{
case 1:
case 3:
case 5:
case 7:
case 9:
System.out.println("");

case 2:
case 4:
case 6:
case 8:
case 10:
System.out.println("");
break;
}
case 2: //Blue
System.out.println("Now enter an integer from 1 through 10.");
int num2 = kbReader.nextInt();

switch (num2)
{
case 1:
case 3:
case 5:
case 7:
case 9:
System.out.println("");

case 2:
case 4:
case 6:
case 8:
case 10:
System.out.println("");

}
case 3: //Yellow
System.out.println("Now enter an integer from 1 through 10.");
int num3 = kbReader.nextInt();

switch (num3)
{
case 1:
case 3:
case 5:
case 7:
case 9:
System.out.println("");

case 2:
case 4:
case 6:
case 8:
case 10:
System.out.println("");

}
case 4: //Green
System.out.println("Now enter an integer from 1 through 10.");
int num4 = kbReader.nextInt();

switch (num4)
{
case 1:
case 3:
case 5:
case 7:
case 9:
System.out.println("");

case 2:
case 4:
case 6:
case 8:
case 10:
System.out.println("");
}
}
}

最佳答案

只需在 switch 语句内的 switch 语句后面放置一个 break 即可。

即(例如)

switch (color) 
{
case 1: //Red
System.out.println("Now enter an integer from 1 through 10.");
int num1 = kbReader.nextInt();

switch (num1)
{
case 1:
case 3:
case 5:
case 7:
case 9:
System.out.println("");

case 2:
case 4:
case 6:
case 8:
case 10:
System.out.println("");
break;
}

break; <--- this is the addition
case 2: //Blue

或者(并且会使整个事情更具可读性)将这些开关放入另一个函数中

关于java - 如何结束开关内部的开关。 java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7842159/

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