gpt4 book ai didi

java - 如何修复数组索引越界错误?

转载 作者:行者123 更新时间:2023-12-01 22:40:56 24 4
gpt4 key购买 nike

我遇到的错误

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 610
at Fib.sorted(Fib.java:67)
at Fib.main(Fib.java:17)

我的代码

public class Fib
{
public static void main(String args[])
{
System.out.println(Arrays.toString( fiblist) );
System.out.println(Fib.add());
System.out.println(Fib.square());
System.out.println(Fib.reversal());
System.out.println(Fib.sorted());
}

public static int fiblist[] = {1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765};
public static int fiblen = fiblist.length;

public Fib()
{
// Do nothing
}

public static ArrayList<Integer> sorted()
{
ArrayList sorted = new ArrayList();

for(int counter = 0; counter < fiblist[4]; counter++ )
{
int temp1 = fiblist[counter];
System.out.println("Elements stored " + temp1);
}
for(int counter = fiblist[14]; counter < fiblist[19]; counter++)
{
int temp2 = fiblist[counter];
System.out.println("Last Elements stored " + temp2);
}
return sorted;
}
}

我试图将数组的最后 5 个元素存储在 temp 2 中。然后我会切换它们。有没有更简单的方法来做到这一点?将数组的前五个元素与后五个元素交换?如何使用 for 循环切换它们?

最佳答案

您混淆了数组索引和值。 fiblist[19] 是 6765。您希望计数器从 0 到 4、14 到 19,而不是 fiblist[19]。

for(int counter = 0; counter < 4; counter++ )
{
int temp1 = fiblist[counter];
System.out.println("Elements stored " + temp1);
}

for(int counter = 14; counter < 19; counter++)
{
int temp2 = fiblist[counter];
System.out.println("Last Elements stored " + temp2);
}

关于java - 如何修复数组索引越界错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26149182/

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