Java學習實例——打印三角形


1、打印如下的三角形(可以根據輸入的值確定行數,和最長的那一行有幾個符號):

              *****
              ****
              ***
              **
              *

import java.util.Scanner;

public class TrianglePrint {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        //輸入確定的行數
        System.out.println("請輸入你想要打印的三角形的行數:");
        int num = sc.nextInt();
        triPrint(num);
    }
    //使用嵌套循環實現倒直角三角形的打印
    public static void triPrint(int n){
        for(int i = 1 ; i <= n ; i++){
            for(int j = n-i ; j >= 0 ; j--){
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

2、打印如下的三角形(可以根據輸入的值確定行數,和最長的那一行有幾個符號):

            *
            **
            ***
            ****
            *****

import java.util.Scanner;

public class TrianglePrint {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        //輸入確定的行數
        System.out.println("請輸入你想要打印的三角形的行數:");
        int num = sc.nextInt();
        triPrint(num);
    }
    //使用嵌套循環實現倒直角三角形的打印
    public static void triPrint(int n){
        for(int i = 1 ; i <= n ; i++){
            for(int j = 1 ; j <= i ;j++){
                System.out.print("*");
            }
            System.out.println();
        }

    }
}

3、打印如下的三角形(可以根據輸入的值確定行數,和最長的那一行有幾個符號):

           *****
            ****
             ***
              **
             *

import java.util.Scanner;

public class TrianglePrint {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        //輸入確定的行數
        System.out.println("請輸入你想要打印的三角形的行數:");
        int num = sc.nextInt();
        triPrint(num);
    }
    //使用嵌套循環實現倒直角三角形的打印
    public static void triPrint(int n){
        for(int i = 1 ; i <= n ; i++){
            for(int j = 1 ; j < i ; j++){
                System.out.print(" ");
            }
            for(int s = n-i ; s >= 0 ; s--){
                System.out.print("*");
            }
            System.out.println();

        }

    }
}

4、打印如下的三角形(可以根據輸入的值確定行數,和最長的那一行有幾個符號):

               *
              **
               ***
              ****
               *****

import java.util.Scanner;

public class TrianglePrint {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        //輸入確定的行數
        System.out.println("請輸入你想要打印的三角形的行數:");
        int num = sc.nextInt();
        triPrint(num);
    }
    //使用嵌套循環實現倒直角三角形的打印
    public static void triPrint(int n){
        for(int i = 1 ; i <= n ; i++){
            for(int j = 1 ; j <= n-i ; j++){
                System.out.print(" ");
            }
            for(int m = 1 ; m <= i ; m++){
                System.out.print("*");
            }
            System.out.println();
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM