Tuesday, December 17, 2013

Check type (int, float...) of args

The example check the type of the first argument:

class hello{
    public static void main(String args[])
    { 
        if(args.length == 0){
            System.out.println("No args");
            System.exit(0);
        }
        
        if(isInt(args[0]) == true){
            System.out.println("args[0] is a integer");
        }else if(isFloat(args[0]) == true){
            System.out.println("args[0] is a float");
        }else{
            System.out.println("other");
        }
        
        System.exit(0);
    }
    
    static private boolean isInt(String str){
        
        boolean result = false;
        try{
             int num = Integer.parseInt(str);
             result = true;
        } catch (NumberFormatException e) {
        }
        return result;
    }
    
    static private boolean isFloat(String str){
        
        boolean result = false;
        try{
             float num = Float.parseFloat(str);
             result = true;
        } catch (NumberFormatException e) {
        }
        return result;
    }
}




No comments:

Post a Comment