我正在构建一个Java应用程序,它将不同数量的命令行选项作为输入,文件名始终是最后一项。当我在下面的第二行中指定参数索引时(例如args[2]
),当我提前知道索引时,一切当然都能正常工作,但是我无法提供正确的语法来访问最终版本处理文件时String[]
中的项,或者甚至只是字符串作为输入与整数数组或当索引号变化时更简单的事项。
public static void main(String[] args) {
String inFile = args.length-1;
答案 0 :(得分:5)
你必须使用
String inFile = args[args.length-1];
//array name ^^^
//last index value ^^^^^^^^^^^^^^
答案 1 :(得分:3)
尝试:
String inFile = args[args.length - 1];
答案 2 :(得分:3)
如果您经常需要此功能,可以将其封装到方法中:
public static <T> T last(T[] them) {
return them != null && them.length > 0 ? them[them.length - 1] : null;
}
public void test(String[] args) throws Exception {
String fileName = last(args);
}