Java学习实例——打印三角形

时间:2021-04-12 12:20:50   收藏:0   阅读:0

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();
    }
}

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!