【问题标题】:Error-checking for command line arguments命令行参数的错误检查
【发布时间】:2014-02-16 05:03:34
【问题描述】:

对于我的程序,如果用户没有输入命令行参数并显示错误消息,我会在创建错误检查时遇到问题。而不是崩溃。 没有文本文件参数,我得到一个 ArrayIndexOutOfBoundsException :o ?

public static void main(String[] commandlineArgument) {
      Integer[] array = ReadFile7.readFileReturnIntegers(commandlineArgument[0]);
      ReadFile7.printArrayAndIntegerCount(array, commandlineArgument[0]);
      if(commandlineArgument.length == 0){
         System.out.println("Please file name " +
               "as the first commandline argument.");
      }
   }

【问题讨论】:

  • 只需将 'if(commandlineArgument.length == 0){...' 块移动到 main 方法的顶部。并添加'return 1;'在 if 块内停止执行

标签: java arrays error-handling command-line-arguments


【解决方案1】:

检查一下:

if(commandlineArgument.length == 0){ ... }

使用前:

commandlineArgument[0]

【讨论】:

  • 天哪,当然是o___o...不敢相信我搞砸了。非常感谢。
【解决方案2】:

它远非完美,但对于命令行 API,我一直在使用很多 commons-cli:http://commons.apache.org/proper/commons-cli/usage.html

【讨论】:

    【解决方案3】:

    首先检查commandlineArgument是否大于0:

    if (commandlineArgument.length == 0){
        System.out.println("Please enter the file name " +
            "as the 1st commandline argument.");
    } else {
        Integer[] array = ReadFile7.readFileReturnIntegers(commandlineArgument[0]);
        ReadFile7.printArrayAndIntegerCount(array, commandlineArgument[0]);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-15
      • 1970-01-01
      • 2013-09-13
      相关资源
      最近更新 更多