利用Java语言打印具有"*"号的等边三角形

/**
*求一个三角形
*/

import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Triangle {
        public static void dis_second() {
                Scanner sc = new Scanner(System.in); //接受控制台输入数据
                String s = sc.nextLine();
                
                Pattern p = Pattern.compile("^[1-9]{1}[0-9]*"); //正则表达式,匹配只能输入正数
                Matcher m = p.matcher(s);
                if (!m.matches()) {
                        s = "1";
                }
                
                Integer a = new Integer(s); //将字符串转换为数字
                if (a % 2 != 0) {
                        int b = 0; //初始预先设置每行显示"*"的数目
                        int c = 0; //初始预先设置每行的空格数目
                        int n = 1;
                        while (n <= (a / 2 + 1)) {
                                b = 2 * n - 1;
                                c = (a - b) / 2;
                                int d = 0;
                                int e = 0;
                                while (d < c) { //循环打印空格
                                        System.out.print(" ");
                                        d++;
                                }
                                while (e < b) { //循环打印"*"
                                        System.out.print("*");
                                        e++;
                                }
                                System.out.println();
                                n++;
                        }
                }
        }

        public static void main(String[] args) {
                dis_second();
        }
}
posted @ 2011-04-19 17:07  无忧蜀生  阅读(1337)  评论(3编辑  收藏  举报