2011-10-20 49 views
0

我想在开关内部做一个开关。我编译了它,但唯一的是,每次运行它时,我都会为第一个开关选择其中一个,然后一旦选择其中一个开关内部的第一个开关,然后也要求我为第一个开关内的第二个开关选择一个外壳,然后第三个和第四个开关,然后结束。如何在选择开关内部的第一个开关后重新开始整个程序,或者结束程序。谢谢。如何结束交换机内部的交换机。 Java

ex。

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("");  
     } 
    } 
} 
+0

我会尝试把更多的休息;在每个案例之后的陈述,所以你打破当前的开关。此外,我会重构你的代码,所以你有1个开关在主(颜色),然后根据这种情况,调用另一个方法来获得你的整数输入,所以你不嵌套开关语句。 –

回答

4

只要在switch语句内的switch语句之后加上break

即(为exampe)

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 

或者(和会使整个事情更易读)把那些切换到另一个功能

+0

谢谢!这正是我所需要的。 – Zack

0

你在哪里使用break语句 你应该给一个休息;您的案例完成执行后的声明。 是这样的。案例1: 中断;

如果你没有给出break语句,那么它将按顺序执行。第一次切换后它将进入下一个开关,依此类推。

0

您可以封装任何开关的条件循环(在/ DO-时间)内,当它到达终点,如果没有达到条件(比如你想变真正 ),开关将重复。

另外,你可以使用break;在开关打印功能后停止继续开关选项。

要重复整个程序,请将其包装在一段时间或do-while循环中。