1. 程式人生 > >Java 判斷命令列引數的型別

Java 判斷命令列引數的型別

/**
* This class print a triangle with '*'.
* @author Li Jialin
* @version 1.0
*/

import java.util.regex.Pattern;

public class Triangle{

    private int height;  //the height of triangle
    private char[][] array; // used to store the triangle
    
    public Triangle(){ //Constructors
        height = 0;
    }

    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 void check(String[]args){
    	try{
    	    if (args.length==0){
                String str = "Command line parameter shouldn't be null";
                Exception e = new Exception(str);  
                throw e; 
            }else {
            	<span style="color:#FF0000;">Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$"); </span>
                if(<span style="color:#FF0000;">!pattern.matcher(args[0]).matches()</span>){
                    String str = "Command line parameter isn't digit";
                    Exception e = new Exception(str);  
                    throw e; 
                }    
            }
    	}catch(Exception e){
            System.out.println(e);
            System.exit(-1);
    	}
    }

    public static void main(String[]args){
        Triangle.check(args); 
        int height = Integer.parseInt(args[0]);
        Triangle t = new Triangle(height);
        t.print();   
    }

}