Getting an information about type of input ( main args )

This question already has an answer here:

  • How do I convert a String to an int in Java? 30 answers

  • 最简单的方法是使用parseInt进行检查。

    public static void main(String[] args) throws InterruptedException
    {
        try
        {
            Integer.parseInt(args[0]);
        }
        catch(NumberFormatException e)
        {
            System.out.println("It is not a number.");
        }
    }
    

    args[] takes in all the arguments supplied to the main method, so args[0] although as a String, if you expected the user to enter an Integer you could cast this with...

    Integer.parseInt(args[0]);

    Consider the fact though it may through a java.lang.NumberFormatException so you'd have to check that in case the user entered an invalid input. If you wanted to do something based on if this is truly a number, look at StringUtils.isNumeric which is in Apache Commons Lang, why reinvent the wheel?

    The reason I would go for this rather than try{} catch() is because exceptions should be used for exceptional circumstances.


    The type of your argument is always just String . If that string is "", "Foo" or "182" is at this point totally arbitrary.

    These strings may, or may not be valid representations of a number. You need to convert the strings to your number type (eg Integer.parseInt ) for int .

    链接地址: http://www.djcxy.com/p/20930.html

    上一篇: 如何将String []或Object []的组件转换为其他类型

    下一篇: 获取关于输入类型的信息(主要参数)