gpt4 book ai didi

java - 通过方法传递数组(java 命令行参数)

转载 作者:太空宇宙 更新时间:2023-11-04 13:56:17 27 4
gpt4 key购买 nike

我想知道如何在方法中检查 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]);
int second = Integer.parseInt(args[1]);
commandLineCheck(first, second);
}

执行此操作时,出现“找不到符号:args”错误。现在,我想我也需要通过该方法传递 args[] 。我已经尝试过了,但它给了我一个“”错误。有没有适合初学者的解决方案?

编辑:非常感谢你们的快速回复!成功了!

最佳答案

像这样更改代码(您需要将数组的参数传递给检查方法)

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);
}

它会起作用的。但是,以下测试 (args.length==0) 没有多大意义,因为您已经通过在 main 方法中从中提取两个值来假设 args.length 大于或等于 2。因此,当您使用 commandLineCheck 方法时,此测试将始终为 false。

关于java - 通过方法传递数组(java 命令行参数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29785574/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com