Java实现正,倒空心金字塔和空心菱形

 1,正空心金字塔:

import java.util.Scanner;
public class Stars {
    public static void main(String[] args){
        Scanner myScanner = new Scanner(System.in);
        int totalFloors = myScanner.nextInt();
        //层数
        int i = 1;
        while (i <= totalFloors){
            //打印每一层的空格
            int k = 1;
            while(k <= totalFloors - i){
                System.out.print(" ");
                k++;
            }

            //打印每一层的"*"
            int j = 1;
            while (j <= i * 2 - 1){
                if(j == 1 || j == i * 2 - 1 || i == totalFloors ){
                System.out.print("*");
                } else {
                    System.out.print(" ");
                }
            j++;
            }

            System.out.println("");
        i++;
        }
    }
}

2,倒空心金字塔:

import java.util.Scanner;
public class ConvertStart {
    public static void main(String[] args){
        Scanner myScanner = new Scanner(System.in);
        int totalFloors = myScanner.nextInt();
        for (int i = 1;i <= totalFloors;i++){
            //空格
            for(int j = 1;j <= i - 1;j++){
                System.out.print(" ");
            }

            for(int k = 1;k <= (totalFloors-i) * 2 + 1;k++){
                if(i == 1 || k == 1 || k== (totalFloors-i) * 2 + 1){
                    System.out.print("*");
                } else {
                    System.out.print(" ");
                }
            }
        System.out.println("");
        }
    }
}l

3,空心的菱形:

import java.util.Scanner;
public class Diamond {
    public static void main(String[] args){
        Scanner myScanner = new Scanner(System.in);
        int totalFloors = myScanner.nextInt();
        //1.正三角
        //层数
        int i = 1;
        while (i <= totalFloors){
            //打印每一层的空格
            int k = 1;
            while(k <= totalFloors - i){
                System.out.print(" ");
                k++;
            }

            //打印每一层的"*"
            int j = 1;
            while (j <= i * 2 - 1){
                if(j == 1 || j == i * 2 - 1 ){
                    System.out.print("*");
                } else {
                    System.out.print(" ");
                }
                j++;
            }

            System.out.println("");
            i++;
        }

        //2.倒三角
        for (i = 1;i <= totalFloors;i++){
            //空格
            for(int j = 1;j <= i - 1;j++){
                System.out.print(" ");
            }
            //"*"
            for(int k = 1;k <= (totalFloors-i) * 2 + 1;k++){
                if(k == 1 || k== (totalFloors-i) * 2 + 1){
                    System.out.print("*");
                } else {
                    System.out.print(" ");
                }
            }
            System.out.println("");
        }
    }
}

你可能感兴趣的:(java)