流程控制

三元运算符

expression1 ? expression2 : expression3

等同于:

if (expression1) {
    expression2;
} else {
    expression3;
}

流程控制的例子

判断季度

class QuarterDemo1 {
    public static void main(String[] args) {
        int nMonth = 5;
        switch (nMonth) {
            case 1:
            case 2:
            case 3:
                System.out.println("First Quarter");
                break;
            case 4:
            case 5:
            case 6:
                System.out.println("Second  Quarter");
                break;
            case 7:
            case 8:
            case 9:
                System.out.println("Third Quarter");
                break;
            case 10:
            case 11:
            case 12:
                System.out.println("Fourth Quarter");
                break;
        }
    }
}

class QuarterDemo2 {
    public static void main(String[] args) {
        int nMonth = 3;
        int nQuarter = (nMonth - 1) / 3 + 1;
        System.out.println(nQuarter + " " + "Quarter");
    }
}

9 * 9 乘法表

class MultiplyDemo {
    public static void main(String[] args) {
        for (int i = 1; i <= 9; i++) {
            for (int j = 1; j <= i; j++) {
                // 下面两种方式都是用来对齐打印的
                System.out.print(i + "*" + j + "=" + (i * j) + '\t');
                System.out.printf("%d * %d = %-5d", i, j, (i * j));
            }
        }
    }
}

Last updated