java - 递归主方法中的 ArrayIndexOutOfBoundsException
问题描述
此代码用记事本编写并在命令提示符下运行。输入为computer is fun
,输出为:
fun
is
computer
当我尝试在 NetBeans 中编写它时,它给了我一个错误:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
有什么问题,如何获得与在命令提示符下运行它时相同的输出?
class A{
public static void main(String[] args) {
args[0]="Computer";
args[1]="Science";
args[2]="is";
args[3]="fun";
if (args.length>1)
{
String []newargs = new String [args.length-1];
for (int i = 0 ; i<newargs.length ;i++)
{
newargs[i]=args[i+1];
}
main (newargs);
//System.out.println(args.length);
}
System.out.println(args[0]);
return;
}
}
解决方案
如果if-statement
条件为真,您正在调用main(newargs)
.
这就是递归:当一个方法调用自己时。
这里的问题是for
循环迭代直到i
等于newargs.length-1
然后,您尝试访问args[i+1]
比数组中可用的索引多 1 个索引。
这是因为在 Java 中,数组是从 0 开始索引的:大小为 5 的数组的索引是 0-4。如果您尝试访问位于 的元素array.length
,那将始终比可用元素多 1!
编辑:所以,为了使这项工作,将for
循环上的边界条件更改为i<newargs.length-1
,你不应该再得到ArrayIndexOutOfBoundsException
s
推荐阅读
- apache-spark - 可空 unicode 字符串的 Spark SQL 排名
- javascript - 这个 TypeScript Lambda 表达式中的括号是什么意思?
- javascript - 如何在一个 OData 模型中显示实体的名称
- 组件 SAPUI5
- python - 在 Windows 上使用 pyserial 将串行数据写入 Arduino
- linux-kernel - /init 后退出代码 = 0x00000004 的内核恐慌
- javascript - 如何在像laravel这样的vue js中使用组路由?
- javascript - 自动获取 Instagram 图片链接
- swift - 下载 Xcode 配置文件时出现问题
- android - 图像已下载但未显示在图库中
- sql - 如何在一个查询中使用同一张表 INNER JOIN 2 或 3 个不同的数据库