打印空心菱形如果一开始觉得比较困难的话,那么不妨分成几个步骤走完成菱形的打印。
代码如下:
import java.util.Scanner;//导入Scanner类所在的包 public class RightTriangle{ public static void main(String[] args){ Scanner myScanner = new Scanner(System.in);//创建一个新的Scanner类用来接受总层数totalLevel System.out.println("请输入总层数totalLevel:"); int totalLevel = myScanner.nextInt(); for (int i = 1 ; i <= totalLevel ; i++ ) {//一共要打印的总层数 for (int j = 1 ; j <= 2 * i -1 ; j ++) {//每一层要打印的星星的个数(2*N-1) System.out.print("*"); } System.out.println(); } } }
编译运行,在DOS窗口下输入5,结果如下图所
代码如下:
import java.util.Scanner; public class SolidTriangle{ public static void main(String[] args){ Scanner myScanner = new Scanner(System.in);//创建一个新的Scanner类用来接受总层数totalLevel System.out.println("请输入总层数totalLevel:"); int totalLevel = myScanner.nextInt(); for (int i = 1 ; i <= totalLevel ; i++ ) {//一共要打印的总层数 for (int j = 1 ; j <= totalLevel - i ; j++ ) {//每一层要打印的空格数 System.out.print(" "); } for (int k = 1 ; k <= 2 * i -1 ; k ++) {//每一层要打印的星星的个数(2*N-1) System.out.print("*"); } System.out.println(); } } }
编译运行,在DOS窗口下输入5,结果如下图所示:
代码如下:
import java.util.Scanner; public class HollowTriangle{ public static void main(String[] args){ Scanner myScanner = new Scanner(System.in); System.out.print("请输入总层数:"); int totalLevel = myScanner.nextInt(); for (int i = 1 ; i <= totalLevel ; i++ ) {//一共要打印的层数 if (i == totalLevel) { for (int m = 1 ; m <= 2 * i - 1 ; m++ ) { System.out.print("*"); } }else{ for (int j = 1 ; j <= totalLevel - i ; j++ ) {//每层要打印的第一批空格数 System.out.print(" "); } System.out.print("*"); for (int k = 1 ; k <= 2 * i - 3 ; k++ ) {//每层要打印的第二批的空格数 System.out.print(" "); } if (i != 1) { System.out.print("*"); } System.out.println(); } } } }
编译运行,在DOS窗口下输入5,结果如下图所示:
代码如下:
import java.util.Scanner; public class HollowDiamond{ public static void main(String[] args){ Scanner myScanner = new Scanner(System.in); System.out.print("请输入上层总层数:"); int totalLevel = myScanner.nextInt(); //打印菱形的上半部分 for (int i = 1 ; i <= totalLevel ; i++ ) {//上层所需要打印的总层数 for (int j = 1; j <= totalLevel - i ; j++) {//每层要打印的空格数(就是总层数减去所在的层数) System.out.print(" "); } for (int k = 1; k <= 2 * i - 1; k++ ) {//每一行要输入的星星的数量(所打印的星星的总数是2*N-1) if (k == 1 || k == 2*i - 1 ) {//第一个和最后一个打印星星,其余打印空格 System.out.print("*"); }else{ System.out.print(" "); } } System.out.println();//每一行结束后就进行换行的操作. } //打印菱形的下半部分 for (int m = 1 ; m <= totalLevel -1 ; m++) {//因为菱形是对称的所以下面的总层数是上层总层数减去一才能构成菱形 for (int n = 1; n <= m ; n ++ ) { System.out.print(" "); } for (int p = 1; p <= 2 * (totalLevel - m) -1 ; p++) {//每一行要输入的星星的数量 if (p == 1 || p == 2 * (totalLevel - m) - 1) {//totalLevel- m就是方便的转换,比如说上层一共有五层,那么第六行和第四行的情况一样 System.out.print( "*"); }else{ System.out.print(" "); } } System.out.println();//每一行结束后就进行换行的操作. } } }
编译运行,在DOS窗口下输入5,结果如下图所示: