<Java>用循环打印九九乘法表——for、while

标题用循环打印九九乘法表

#方法一. for 循环

for(初始化表达式①;布尔表达式②;计数器④){语句③…} 运行顺序②③④ ②③④…

public class Test1{
	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 + "  ");
			}
			System.out.println("");
		}
	}
}

控制台编译java文件生成class文件,然后运行

<Java>用循环打印九九乘法表——for、while_第1张图片

#方法二. while 循环

while(布尔表达式){语句…}

public class Test2{
	public static void main(String[] args){
		int i=1;
		while(i<=9){
			int j=1;
			while(j<=i){
				System.out.print(i+"*"+j+"="+i*j+"  ");
                j++;
			}System.out.println("");
			i++;
		}
	}
}

控制台编译java文件生成class文件,然后运行

<Java>用循环打印九九乘法表——for、while_第2张图片

注: for 循环与 while 循环编写思路相同

- 技巧拓展

九九乘法表的倒序和正序输出

package test2;

public class Demo7 {
    public static void main(String[] args) {
        //7.打印九九乘法表

        //while 倒序
        int a = 9;
        while (a>0){
            int b = 0;
            while (b<a){
                b++;
                int c = a * b;
                System.out.print(b+"*"+a+"="+c+"  ");
            }
            a--;
            System.out.println("");
        }
        System.out.println("----------------------------------------------------------------------");

        //while 正序
        int d = 0;
        while (d<9){
            d++;
            int e = 0;
            while (e<d){
                e++;
                System.out.print(e+"*"+d+"="+(e*d)+"  ");
            }
            System.out.println("");
        }
        System.out.println("----------------------------------------------------------------------");

        //for 倒序
        for (int i = 9; i >= 1; i--) {
            for (int j = 1; j <= i; j++) {
                System.out.print(j+"*"+i+"="+(i*j)+"  ");
            }
            System.out.println("");
        }
        System.out.println("----------------------------------------------------------------------");

        //for 正序
        for (int i = 1; i <= 9; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print(j+"*"+i+"="+(i*j)+"  ");
            }
            System.out.println("");
        }
    }
}

你可能感兴趣的:(java,eclipse)