简体   繁体   English

如何在命令行参数中使用indexOf()?

[英]How to use the indexOf() in the commandline arguments?

How do I do to check if the following command line arguments - inventory make=Honda desc by_count total - have make= ? 如何检查以下命令行参数- 库存make =本田desc by_count total-是否具有make =?

I have created String[] savedArgs so I pass all the arguments to this array, but there is no indexOf() for arrays so I`ma little lost now... 我已经创建了String [] savedArgs,所以我将所有参数传递给该数组,但是数组没有indexOf(),所以我现在有点迷路了...

I want to be able to look for make= in the command line arguments so I can use the appropriate method to show a list according to the car maker. 我希望能够在命令行参数中查找make = ,以便可以根据汽车制造商使用适当的方法来显示列表。 All I could do is use the contains() to look for exact matches (Eg: make=Honda or make=BMW ) but this way I would repeat the same code many times and I believe that`s bad design. 我所能做的就是使用contains()查找完全匹配的内容(例如: make = Hondamake = BMW ),但是这样,我将重复相同的代码很多次,并且我认为这是错误的设计。

Thanks in advance 提前致谢

If you want to handle input arguments yourself, you could check if each argument contains the substring of your argument name ('make=') and then split the string: 如果要自己处理输入参数,则可以检查每个参数是否包含参数名称的子字符串('make ='),然后拆分字符串:

String make = "";
for (String arg : savedArgs) {
    if (arg.contains("make=")) {
        make = arg.split("make=")[1];
    }
}

Repeat for each argument as necessary. 根据需要对每个参数重复此操作。

A better solution might be to use Apache Commons CLI . 更好的解决方案可能是使用Apache Commons CLI

There isn't a built-in indexOf or similar method that would work out-of-the-box for what you want. 没有内置的indexOf或类似的方法可以针对您想要的内容开箱即用。 One option is something like: 一种选择是这样的:

    final String makeArgPrefix = "make=";
    Optional<String> makeArg = Stream.of(args)
            .filter(arg -> arg.startsWith(makeArgPrefix))
            .findAny();
    makeArg.ifPresent(arg -> System.out.println(arg.substring(makeArgPrefix.length())));

This requires Java 8 since I am using streams. 这需要Java 8,因为我正在使用流。 With make=Honda in the command line arguments this prints 在命令行参数中使用make=Honda进行打印

Honda

It doesn't take into account that more than one command line argument could begin with name= . 它没有考虑到多个命令行参数可以以name=开头。 It could be refined depending on your exact requirements. 可以根据您的确切要求进行完善。

Allow me to add that standard interpretation of command line arguments processes them all from left to right (a sensible thing to do if you don't want to ignore some). 让我补充一点,命令行参数的标准解释从左到右处理它们(如果您不想忽略某些参数,这是明智的选择)。 Something like 就像是

for (String arg : args) {
    if (arg.equals("desc") {
        ascending = false;
    } else if (arg.startsWith(makeArgPrefix) {
        make = arg.substring(makeArgPrefix.length());
    } else if // and so on

}

Of course, do it the way that fits best to your particular situation. 当然,以最适合您的特定情况的方式进行操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM