为什么会出现名为java.lang.ArrayIndexOutOfBoundsException的错误?
我在64位Linux系统上用Java编写了以下代码:为什么会出现名为java.lang.ArrayIndexOutOfBoundsException的错误?,java,exception,Java,Exception,我在64位Linux系统上用Java编写了以下代码: class WrapperClass1 { public static void main(String s []) { int noinput=s.length; System.out.println("Number of values entered is :- " + noinput); System.out.printl
class WrapperClass1
{
public static void main(String s [])
{
int noinput=s.length;
System.out.println("Number of values entered is :- " + noinput);
System.out.println( s[0] + "," + s[1] );
int x = Integer.parseInt(s[0]);
int y = Integer.parseInt(s[1]);
int z = x + y;
System.out.println(" Sum = " + z);
}
};
现在,当我尝试编译它时,它成功地编译了,但当我执行程序时,它会显示一个异常,称为:
Number of values entered is :- 0
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at WrapperClass1.main(WrapperClass1.java:7)
您没有传递导致此问题的任何参数
ArrayIndexOutOfBoundsException
抛出以指示已使用非法
指数索引为负数或大于或等于
数组的大小
在您的情况下,您在执行程序时没有通过。因此,它在访问
s[0]
或s[1]
时引发异常。您的数组s是空的,因此,当您尝试像s[0]那样从中弹出项时,它将引发此异常,因为它没有任何内容。输入:String[]
使用哪种方法?--><代码>主(字符串[]参数)
何时给予?-->当我们说java…
来执行
当它抛出ArrayIndexOutOfBoundsException
?-->
首字母:字符串s[]
但是在初始化变量(数组)之前,尝试访问不可用的索引
解决方案:通过命令提供输入(因为这些是命令行参数)
即使未提供输入,如何避免错误?-->检查数组的大小
希望这有助于 < P>你应该考虑使用一个if语句来检查<代码> NOPENTION/COD>至少是2。然后,您可以自由使用s[0]和s[1],而无需获得
ArrayIndexOutOfBoundsException
运行代码时,您没有在代码中传递任何命令行参数。因此,您无法访问s[0]
。您是如何执行此操作的?您在运行时是否传递了任何参数?谢谢朋友,我在命令行上传递了参数,解决了我的问题…谢谢朋友,解决了我的问题:)