📜  Java中几个棘手的程序

📅  最后修改于: 2022-05-13 01:55:33.026000             🧑  作者: Mango

Java中几个棘手的程序

  1. 执行的评论:

    直到现在,我们总是被教导“评论不执行”。让我们今天看看“执行的评论”

    以下是代码片段:

    public class Testing {
        public static void main(String[] args)
         {
             // the line below this gives an output
             // \u000d System.out.println("comment executed");
         }
    }
    

    输出:

    comment executed

    原因是Java编译器将 unicode字符\u000d 解析为新行并转换为:

    public class Testing {
        public static void main(String[] args)
        {
            // the line below this gives an output
            // \u000d
            System.out.println("comment executed");
        }
    }
    
  2. 命名循环:
    // A Java program to demonstrate working of named loops.
    public class Testing 
    {
        public static void main(String[] args)
        {
        loop1:
        for (int i = 0; i < 5; i++)
         {
            for (int j = 0; j < 5; j++) 
            {
                if (i == 3)
                    break loop1;
                System.out.println("i = " + i + " j = " + j);
            }
        }
       }
    }
    

    输出:

    i = 0 j = 0
    i = 0 j = 1
    i = 0 j = 2
    i = 0 j = 3
    i = 0 j = 4
    i = 1 j = 0
    i = 1 j = 1
    i = 1 j = 2
    i = 1 j = 3
    i = 1 j = 4
    i = 2 j = 0
    i = 2 j = 1
    i = 2 j = 2
    i = 2 j = 3
    i = 2 j = 4

    您还可以使用 continue 跳转到命名循环的开始。

    我们还可以在带有 for 循环的嵌套 if-else 中使用 break(或 continue),以便用 if-else 中断多个循环,因此可以避免设置大量标志并在 if-else 中测试它们以便继续或不在此嵌套级别。