如何修复数组索引超出范围的错误? [英] How to fix array index out of bounds error?

查看:73
本文介绍了如何修复数组索引超出范围的错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到的错误

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循环切换它们?

I'm trying to store the last 5 elements of my array in temp 2. Then I will switch them. Is there an easier way to do this? Switch the first five elements of an array with the last five? How would you switch them with a for loop?

推荐答案

有效

for(int i=0;i<fiblist.length;i++){
   System.out.print(fiblist[i]+",");
}
System.out.println();

for (int i=0;i<5;i++){
    temp=fiblist[i];
    fiblist[i]=fiblist[fiblist.length-i-1];
    //the first ellement= the last
    //the second=second from last...
    fiblist[fiblist.length-1-i]=temp;
}

for(int i=0;i<fiblist.length;i++){
    System.out.print(fiblist[i]+",");
}

输出:

1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,
6765,4181,2584,1597,987,8,13,21,34,55,89,144,233,377,610,5,3,2,1,1,

这篇关于如何修复数组索引超出范围的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆