Java:检查命令行参数是否为null [英] Java: Check if command line arguments are null

查看:235
本文介绍了Java:检查命令行参数是否为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一些错误检查我的命令行参数

I am looking to do some error checking for my command line arguments

public static void main(String[] args)
{
    if(args[0] == null)
    {
        System.out.println("Proper Usage is: java program filename");
        System.exit(0);
    }
}

但是,这会返回一个数组超出范围的异常,这是有道理的。我只是寻找正确的用法。

However, this returns an array out of bounds exception, which makes sense. I am just looking for the proper usage.

推荐答案

参数永远不能 null

换句话说,你需要做的是检查参数的长度。

In other words, what you need to do is check the length of your arguments.

public static void main(String[] args)
{
    // Check how many arguments were passed in
    if(args.length == 0)
    {
        System.out.println("Proper Usage is: java program filename");
        System.exit(0);
    }
}

这篇关于Java:检查命令行参数是否为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆