【问题标题】:IndexOutOfBoundsException with Timer in JavaJava 中带有 Timer 的 IndexOutOfBoundsException
【发布时间】:2013-05-07 22:40:34
【问题描述】:

我有一个问题,希望需要一个我似乎无法弄清楚的简单明显的解决方案。好的,所以我在玩斐波那契数列:我想提示用户输入一个整数。然后它将运行将每个元素添加到 Arraylist 的序列。然后,我想使用计时器将数组列表中的每个元素显示到控制台 - 序列中的每个元素每秒显示一次 - 我以简短的方法执行此操作。

输出很好。就在我运行程序时,我得到了 IndexOutOfBoundsException。我明白为什么会出现问题。我的计数超过了数组列表的大小。我想过只是弄乱>,=等-但没有解决问题。我想过用一个while循环来解决这个错误——那没用。我的问题是:如何在不超过数组列表索引限制的情况下进行计数?

这是我的代码:

public class Sequence {

static int seconds = 0;
static Timer timer;
static ArrayList<Integer> fibList = new ArrayList<Integer>();

public static void main(String[] args) {

    boolean noError = true; 
    Scanner sc = new Scanner(System.in);

    //will store sum of evens
    int tmp = 0;

    //timer variables
    int delay = 1000;
    int period = 1000;
    timer = new Timer();

    //enter user input, try catch to eliminate invalid input
    do{
        try{
            System.out.println("Please enter a number: ");
            int input = Integer.parseInt(sc.nextLine());

            //add to arraylist from user input
            for (int i=0; i<=input; i++){
                   fibList.add(fib(i));

                   //sum even numbers
            if(fib(i)%2 == 0){
                tmp += fib(i);
            }

            }

        }catch(Exception e){
            System.out.println("Not a valid Number!");

        }

        noError = false;
    }while(noError);

     System.out.println(fibList);
     System.out.println("Sum of Even Numbers is: "+tmp);


     timer.scheduleAtFixedRate(new TimerTask() {

            public void run() {      

                System.out.print(fibList.get(setInterval())+ ",");
            }
        }, delay, period);

}

    //This is where I count up through my ArrayList and probably cause the Error
//counts up for every element through the array
public static final int setInterval() {

    if (seconds >= fibList.size())
        timer.cancel();
    return seconds++;


}

//does fibonacci sequence
public static int fib(int n) {
    if (n < 2) {
         return n;
      }
      else {
   return fib(n-1)+fib(n-2);
      }

}

}

【问题讨论】:

    标签: java methods timer arraylist fibonacci


    【解决方案1】:

    顺便说一句,iluxa 的方法更好。逻辑清晰,避免混淆。

    但是,如果您只是想修复您的测试条件,请将您的 if 更改为

    if (seconds == fibList.size() - 1)
    

    【讨论】:

      【解决方案2】:

      您正在从setInterval() 返回一个seconds++ 并使用它来获取数组列表元素,即使您已经取消了计时器,因为您知道您已经走得太远了。相反,你应该这样做

      public void run() {      
        int nextIndex = setInterval();
        if (nextIndex < fibList.size()) {
          System.out.print(fibList.get(nextIndex)+ ",");
        }
      }
      

      这样,您就不会尝试打印出太大的索引;并且线程将在下一次迭代之前被取消

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-05-02
        • 2014-09-13
        • 2018-12-03
        • 1970-01-01
        • 2013-09-30
        • 1970-01-01
        • 2016-01-01
        • 2016-11-15
        相关资源
        最近更新 更多