[英]pass array through method (java command line arguments)
I was wondering how I could check args.length within a method. 我想知道如何在方法中检查args.length。
For example: 例如:
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);
}
I get a "cannot find symbol: args" error when I do this. 执行此操作时,出现“找不到符号:参数”错误。 Right now, I'm thinking I need to pass args[] through the method as well.
现在,我想我也需要通过该方法传递args []。 I've tried this but it then gives me an "" error.
我已经尝试过了,但是它给了我一个“”错误。 Is there a beginner-friendly solution to this?
有没有适合初学者的解决方案?
EDIT: Thank you so much for the quick response guys! 编辑:非常感谢您的快速响应! It worked!
有效!
Change your code like this (You need to pass the array's parameter to your check method) 像这样更改代码(您需要将数组的参数传递给您的check方法)
public static void commandLineCheck (int first, int second, String[] args){
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);
}
And it will work. 它将起作用。 However the following test
(args.length==0)
does not make much sense since you have already assumed that args.length is greater or equal to 2 by extracting two values from it inside the main method. 但是,以下测试
(args.length==0)
并没有多大意义,因为您已经通过在main方法内部从args.length中提取两个值来假定args.length大于或等于2。 Therefore when you get to your commandLineCheck method, this test will always be false. 因此,当您使用commandLineCheck方法时,该测试将始终为false。
You need to pass the String [] args
to your commandLineCheck
method. 您需要将
String [] args
传递给commandLineCheck
方法。 This is written the same way as you declare the array for your main
method. 编写方法与为
main
方法声明数组的方式相同。
public static void commandLineCheck (String[] args){
if (args.length==0){
//do something with first and second
}
}
Also you probably want to change your main method and commandLineCheck
method a bit. 另外,您可能想稍微更改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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.