gpt4 book ai didi

java - 如何克服 Integer.parseInt(args[0]) 的 ArrayIndexOutOfBoundException?

转载 作者:行者123 更新时间:2023-12-01 16:54:43 26 4
gpt4 key购买 nike

我在其中一个视频教程中看到了下面的代码。它执行得很好,但是当我尝试在我的系统中执行时,它编译得很好,但我收到运行时错误,

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0

class Test13 
{
public static void main(String[] args)
{
int i = Integer.parseInt(args[0]);
System.out.println(i);
}
}

有人可以指导我这段代码有什么问题以及如何纠正吗?

提前致谢!

最佳答案

看起来您在运行代码时没有传递任何参数。

来自Java doc for ArrayIndexOutOfBoundsException : '抛出该异常表示已使用非法索引访问了数组。索引要么为负数,要么大于或等于数组的大小。'

因此,您尝试从索引为 0 的 args 数组中提取一个值,但该数组小于此大小(在本例中为空)。

为了防止抛出异常,您可以在语句周围应用大小检查。

if(args.length>0) {
int i = Integer.parseInt(args[0]);
System.out.println(i);
}

关于java - 如何克服 Integer.parseInt(args[0]) 的 ArrayIndexOutOfBoundException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34720857/

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