[英]CLI: getOptionValue always return 'null'
public class converter {
public static void main(String [] args) {
Options opt = new Options();
opt.addOption("I", "in", false, "Eingabeformat (2,8,10,16)");
opt.addOption("O", "out", false, "Ausgabeformat (2,8,10,16)");
opt.addOption("V", "value", true, "Zu konvertierende Zahl");
CommandLineParser parser = new DefaultParser();
String value = "0";
String in = "0";
String out = "0";
int inInt = 0;
int outInt = 0;
try {
CommandLine cl = parser.parse(opt, args);
if (cl.hasOption("I")) {
in = cl.getOptionValue("I");
System.out.println(in);
} else if (cl.hasOption("in")) {
in = cl.getOptionValue("in");
inInt = Integer.parseInt(in);
}
if (cl.hasOption("O")) {
out = cl.getOptionValue("O");
outInt = Integer.parseInt(out);
} else if (cl.hasOption("out")) {
out = cl.getOptionValue("out");
outInt = Integer.parseInt(out);
}
if (cl.hasOption("V")) {
value = cl.getOptionValue("V");
} else if (cl.hasOption("value")) {
value = cl.getOptionValue("value");
}
} catch (ParseException e) {
e.printStackTrace();
}
}
您好,對於我的課程,我必須學習使用CLI的方法,目前看來還不錯。 我的問題是:在使用cl.getOptionValue(“ I”)之后,變量'in'總是返回null。 有人可以幫忙嗎?
我假設您期望參數I,O和V具有選項值,否則您將不會嘗試解析它們。 但是,您只能通過將addOption
調用中的第三個參數設置為true來為V選項指定該選項。 如果要指定選項值,則應將它們全部設置為true
:
opt.addOption("I", "in", true, "Eingabeformat (2,8,10,16)");
opt.addOption("O", "out", true, "Ausgabeformat (2,8,10,16)");
opt.addOption("V", "value", true, "Zu konvertierende Zahl");
順便說一句,您應該將類Converter
命名為大寫的“ C”,這是Java約定。
public class converter {
public static void main(String [] args) {
Options opt = new Options();
opt.addOption("I", "in", true, "Eingabeformat (2,8,10,16)"); // Bei false gibts spaeter null
opt.addOption("O", "out", true, "Ausgabeformat (2,8,10,16)"); // Bei false gibt spaeter null
opt.addOption("V", "value", true, "Zu konvertierende Zahl");
CommandLineParser parser = new DefaultParser();
String value = "0";
String in, out;
int inInt = 10;
int outInt = 10;
try {
CommandLine cl = parser.parse(opt, args);
if (cl.hasOption("I")) {
in = cl.getOptionValue("I");
inInt = Integer.parseInt(in);
} else if (cl.hasOption("in")) {
in = cl.getOptionValue("in");
inInt = Integer.parseInt(in);
}
if (cl.hasOption("O")) {
out = cl.getOptionValue("O");
outInt = Integer.parseInt(out);
} else if (cl.hasOption("out")) {
out = cl.getOptionValue("out");
outInt = Integer.parseInt(out);
}
if (cl.hasOption("V")) {
value = cl.getOptionValue("V");
System.out.println(convert(value, inInt, outInt));
} else if (cl.hasOption("value")) {
value = cl.getOptionValue("value");
System.out.println(convert(value, inInt, outInt));
} else {
System.out.println("Keinen Wert eingegeben. Erneut Versuchen!");
}
} catch (ParseException e) {
e.printStackTrace();
}
}
public static String convert(String input, int srcRadix, int dstRadix) {
int value = Integer.parseInt(input, srcRadix);
return Integer.toString(value, dstRadix);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.