英文:
command line argument with variable name in java in specific format
问题
我正在尝试获得一个类似于以下格式的命令行界面(CLI)以用于我的课程:
java demo --age 20 --name Amr --school Academy_of_technology --course CS
我该如何实现这个?
我看到了一个解决方案,并尝试了这个链接中的方法:https://stackoverflow.com/questions/54092354/command-line-arguments-with-variable-name
Map<String, String> argsMap = new LinkedHashMap<>();
for (String arg: args) {
String[] parts = arg.split("=");
argsMap.put(parts[0], parts[1]);
}
argsMap.entrySet().forEach(arg -> {
System.out.println(arg.getKey().replace("--", "") + "=" + arg.getValue());
});
但是上述代码的输入格式是类似于javac demo --age=20 --name=Amar school=AOT course=CS
的。
而我希望我的输入格式像这样:
java demo --age 20 --name Amr --school Academy_of_technology --course CS
所以我用空格替换了"=",结果得到了预期之外的数组越界。我在考虑是否可以使用正则表达式。
该代码始终期望有4个输入参数。
英文:
I am trying to get a CLI for my class in the format of
java demo --age 20 --name Amr --school Academy_of_technology --course CS
how do I achieve this.
I saw one of the solutions and tried that over here https://stackoverflow.com/questions/54092354/command-line-arguments-with-variable-name
Map<String, String> argsMap = new LinkedHashMap<>();
for (String arg: args) {
String[] parts = arg.split("=");
argsMap.put(parts[0], parts[1]);
}
argsMap.entrySet().forEach(arg-> {
System.out.println(arg.getKey().replace("--", "") + "=" + arg.getValue());
});
but the above code's input format was like javac demo --age=20 --name=Amar school=AOT course=CS
and i want my i/p format to be like this
java demo --age 20 --name Amr --school Academy_of_technology --course CS
so i replaced the "=" with " " and i got array out of bounds as epected.
I was thinking if regex would be the way.
The code always expects 4 input.
答案1
得分: 1
以下代码将在仅以空格分隔键值对的情况下起作用。
public static void main(String[] args) {
Map<String, String> argMap = new LinkedHashMap<>();
for(int ind=0; ind<args.length; ind+=2) {
argMap.put(args[ind], args[ind+1]);
}
for(Map.Entry<String, String> entrySet: argMap.entrySet()) {
String property = entrySet.getKey().substring(2);
String value = entrySet.getValue();
System.out.println("key = " + property + ", value = " + value);
}
}
英文:
The below code will work if key and value pairs are only space-separated.
public static void main(String[] args) {
Map<String, String> argMap = new LinkedHashMap<>();
for(int ind=0; ind<args.length; ind+=2) {
argMap.put(args[ind], args[ind+1]);
}
for(Map.Entry<String, String> entrySet: argMap.entrySet()) {
String property = entrySet.getKey().substring(2);
String value = entrySet.getValue();
System.out.println("key = " + property + ", value = " + value);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论