Java 打印三角形

来源:互联网 发布:淘宝交钱需要交多少钱 编辑:程序博客网 时间:2024/06/07 06:53
/*** This class print a triangle with '*'.* @author Li Jialin* @version 1.0*/import java.util.regex.Pattern;class MyException extends Exception{    public MyException(){        super();    }        public MyException(String message){        super(message);    }}public class Triangle{    private int height;  //the height of triangle    private char[][] array; // used to store the triangle    public Triangle(int h){        height = h;        array = new char[height][2*height-1];        for(int i=0;i<height;i++){            for(int j=0;j<2*i+1;j++){                array[i][j] = '*';                }        }    }    public void print(){ // print function        for(int i=0;i<height;i++){            for(int k=height-i;k>=0;k--){                    System.out.print(' ');            }            for(int j=0;j<2*i+1;j++){                System.out.print(array[i][j]);            }            System.out.println();        }    }    public static int get_height(String[]args) throws MyException{        if (args.length==0){            throw new MyException("传入的字符串参数不能为null!");        }        int height = 0;        try{            height = Integer.parseInt(args[0]);          }catch(NumberFormatException e){            System.out.println(e);            System.exit(-1);        }        if (height<=0){            throw new MyException("高度不能小于1!");        }        return height;    }    public static void main(String[]args) throws MyException {        int height = Triangle.get_height(args);        Triangle t = new Triangle(height);        t.print();       }}

0 0
原创粉丝点击