【问题标题】:Check if command line arguments are in a correct form检查命令行参数的格式是否正确
【发布时间】:2022-01-15 22:49:02
【问题描述】:

如果我的程序是这样正确启动的:

java Test Tim;John;10;20

但我想阻止用户输入此表单以外的其他内容。

所以每当命令行参数不是String;String;int;int 的形式时,我希望我的程序退出并打印错误代码。

我不知道该怎么做。对于如果有人没有输入任何内容的情况,我只是使用了 ArrayIndexOutofBounds 的 try catch,但我不知道如何特别捕获每个可能的命令行参数,这些参数的格式不正确。

【问题讨论】:

    标签: java exception error-handling try-catch command-line-arguments


    【解决方案1】:

    我希望它能给你一些想法:

     public static void main(String[] args) {
            args = args[0].split(";");
            if (args.length != 4) {
                throw new IllegalArgumentException("Program starts with parameters like this: (String, String, int, int)");
            }
    
            try {
                int firstInt = Integer.parseInt(args[2]);
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException("Program starts with parameters like this: (OK, OK, int, int)");
            }
    
            try {
                int secondInt = Integer.parseInt(args[3]);
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException("Program starts with parameters like this: (OK, OK, OK, int)");
            }
        }
    

    【讨论】:

    • 问题是长度不起作用,因为它们是用;而不是空格分隔的。
    • 我会更新答案
    • 看看方法体的第一行。它应该可以解决问题。
    猜你喜欢
    • 2016-04-15
    • 2021-03-31
    • 1970-01-01
    • 2011-04-21
    • 2015-05-28
    • 1970-01-01
    • 2020-12-25
    • 2017-04-11
    相关资源
    最近更新 更多