Java之旅_高级教程_实例_打印图形
1.打印菱形
public class MainClass{ public static void main(String[] args){ printStar(10); } public static void printStar(int star){ if(star%2==0){ star++; } int bank = (star-1)/2; for(int n=1;n<star+1;){ for(int k=bank;k>0;k--){ System.out.print(" "); } for(int i=1;i<n+1;i++){ System.out.print("*"); } System.out.println(); n=n+2; bank--; } for(int n=star-2;n>0;){ for(int k=1;k<bank+3;k++){ System.out.print(" "); } for(int i=0;i<n;i++){ System.out.print("*"); } System.out.println(); n=n-2; bank++; } } }
2.九九乘法表
public class MainClass{ public static void main(String[] args){ for(int i=1;i<10;i++){ for(int j=1;j<i+1;j++){ System.out.print(j+"X"+i+"="+i*j); System.out.print(" "); } System.out.println(); } } }
3.打印三角形
public class MainClass{ public static void main(String[] args){ printStar(10); } public static void printStar(int star){ if(star%2==0){ star++; } int bank = (star-1)/2; for(int n=1;n<star+1;){ for(int k=bank;k>0;k--){ System.out.print(" "); } for(int i=1;i<n+1;i++){ System.out.print("*"); } System.out.println(); n=n+2; bank--; } } }
4.打印倒立的三角形
public class MainClass{ public static void main(String[] args){ printStar(10); } public static void printStar(int star){ if(star%2==0){ star++; } int bank = 0; for(int n=star;n>0;){ for(int k=0;k<bank+1;k++){ System.out.print(" "); } for(int i=n;i>0;i--){ System.out.print("*"); } System.out.println(); n=n-2; bank++; } } }
5.打印菱形
public class MainClass{ public static void main(String[] args){ printDiamonds(4); } public static void printDiamonds(int line){ int bank=line-1; for(int ln=1;ln<line+1;ln++){ for(int i=0;i<bank+1;i++){ System.out.print(" "); } for(int j=0;j<5;j++){ System.out.print("*"); } bank--; System.out.println(); } } }
6.打印矩形
public class MainClass{ public static void main(String[] args){ printDiamonds(4); } public static void printDiamonds(int line){ for(int ln=0;ln<line+1;ln++){ for(int j=0;j<5;j++){ System.out.print("*"); } System.out.println(); } } }