切换日食

时间:2015-12-04 14:06:12

标签: java

为什么输出"ADC"D来自哪里?此外,此代码中defaultcontinue命令的目标是什么?

char x = 'A';
while(x != 'D') {
    switch(x) {
    case 'A':
        System.out.print(x); x = 'D';
    case 'B':
        System.out.print(x); x = 'C';
    case 'C':
        System.out.print(x); x = 'D';
    default:
        continue;
 }

5 个答案:

答案 0 :(得分:3)

您从A开始。从x != 'D'开始,您输入while循环 现在流程如下:

  • 输入case 'A'
  • 打印A并指定x = 'D'
  • 直至case 'B'
  • 打印D(自x == 'D'起)并指定x = 'C'
  • 直至case 'C'
  • 打印C(自x == 'C'起)并指定x = 'D'
  • 直至default(当您找不到匹配的case时通常会到达
  • continue(表示返回while循环的开头)
  • x == 'D'起,条件评估为false,并且不会进入循环。

==>结果:打印ADC

答案 1 :(得分:2)

是的,您忘记了步骤之间的getUpdates。因此,匹配案例之后的所有步骤都将被执行。尝试使用:

break

答案 2 :(得分:2)

Switch语句具有所谓的"fall through"

在每个案例的最后都需要break,否则所有案例都会在这里发生。

char x = 'A'; //starts off as A
while(x != 'D') {
    switch(x) {
    case 'A':
        System.out.print(x); x = 'D'; //here is gets printed and changed to D
    case 'B': //you fall through here because there's no break
        System.out.print(x); x = 'C'; //print again then change to C
    case 'C': //fall through again
        System.out.print(x); x = 'D'; //print again then change to D
    default:
        continue;

如果匹配,则只输入case(如果它以C开头,则只打印一次)但是一旦找到匹配,您也可以进入其他情况。

如果您添加break s,那么您将不再失败。

char x = 'A';
while(x != 'D') {
    switch(x) {
    case 'A': //match
        System.out.print(x); x = 'D'; //print then modify
        break; //break
    case 'B':
        System.out.print(x); x = 'C';
        break;
    case 'C':
        System.out.print(x); x = 'D';
        break;
    default:
        continue;

答案 3 :(得分:1)

看看这个开关:

int a = 0;
switch(a) {
case 0:
    System.out.println("0");
case 1:
    System.out.println("1");
}

执行的代码行是:

  1. int a = 0;
  2. System.out.println("0");
  3. System.out.println("1");
  4. 为了只执行你想要执行的语句,你必须在每个案例结束时使用break

    int a = 0;
    switch(a) {
    case 0:
        System.out.println("0");
        break;
    case 1:
        System.out.println("1");
        break;
    }
    

答案 4 :(得分:1)

当第一次开关执行时,选择案例'A',打印A并将x设为'D', 在案例之间没有中断,因此下一行执行 - 打印D(之前x设置为'D')并将x设置为'C'。等等。