我正在尝试在交换机内部进行切换。我已经编译了它,但是唯一的是,每次运行它时,我都会为第一个开关选择一种情况,一旦进入并为开关内部的第一个开关选择一种情况,然后还要求我为第一个开关内的第二个开关选择一个外壳,然后选择第三个开关,然后结束。在选择开关中的第一个开关后,如何使整个程序重新从头开始,还是结束程序。谢谢。

例如

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/

10-09 23:15