gpt4 book ai didi

java - 运行此代码时出现异常 java.lang.ArrayIndexOutOfBoundsException?

转载 作者:行者123 更新时间:2023-12-01 07:06:04 26 4
gpt4 key购买 nike

我在将 list[array.length] 引用传递给 s 时遇到异常 java.lang.ArrayIndexOutOfBoundsException。

import java.io.*;

public class Test
{
public void demo(String [] list)
{
try
{
String s=list[list.length];// error
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("The exception is"+e);
}
finally
{
System.out.println("Finally here.");
}
}
public static void main(String [] args)
{
Test t=new Test();
String [] list={"one","two"};
t.demo(list);
System.out.println("Done!");
}
}

最佳答案

如果你有一个长度为 5 的数组,你将在索引 0-4 上有元素,并且你正在尝试访问第 5 个元素。

如果你想访问最后一个元素:

String s = list[list.length - 1];

关于java - 运行此代码时出现异常 java.lang.ArrayIndexOutOfBoundsException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23822805/

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