通过方法传递数组(java命令行参数)
我想知道如何在一个方法中检查args.length 例如:通过方法传递数组(java命令行参数),java,command-line-arguments,Java,Command Line Arguments,我想知道如何在一个方法中检查args.length 例如: public static void commandLineCheck (int first, int second){ if (args.length==0){ //do something with first and second } } public static void main(String[] args) { int first = Integer.parseInt(args[0
public static void commandLineCheck (int first, int second){
if (args.length==0){
//do something with first and second
}
}
public static void main(String[] args) {
int first = Integer.parseInt(args[0]);
int second = Integer.parseInt(args[1]);
commandLineCheck(first, second);
}
当我执行此操作时,会出现“找不到符号:args”错误。现在,我想我还需要通过这个方法传递args[]。我尝试过这个,但它会给我一个“”错误。有没有一个初学者友好的解决方案
编辑:非常感谢你们的快速反应!成功了 这样更改代码(需要将数组的参数传递给check方法)
它会起作用的。但是,下面的测试
(args.length==0)
没有多大意义,因为您已经通过在main方法中从args.length中提取两个值来假设args.length大于或等于2。因此,当您使用commandLineCheck方法时,此测试将始终为false。您需要将字符串[]args
传递给commandLineCheck
方法。这与为main
方法声明数组的方式相同
public static void commandLineCheck (String[] args){
if (args.length==0){
//do something with first and second
}
}
另外,您可能需要稍微更改main方法和commandLineCheck
方法
public static void commandLineCheck(String [] args) {
/* make sure there are arguments, check that length >= 2*/
if (args.length >= 2){
//do something with first and second
int first = Integer.parseInt(args[0]);
int second = Integer.parseInt(args[1]);
}
}
public static void main(String[] args) {
commandLineCheck(args);
}
public static void commandLineCheck(String [] args) {
/* make sure there are arguments, check that length >= 2*/
if (args.length >= 2){
//do something with first and second
int first = Integer.parseInt(args[0]);
int second = Integer.parseInt(args[1]);
}
}
public static void main(String[] args) {
commandLineCheck(args);
}