gpt4 book ai didi

java - Java 中计时器的 IndexOutOfBoundsException

转载 作者:行者123 更新时间:2023-12-01 14:36:43 24 4
gpt4 key购买 nike

我有一个问题,希望需要一个我似乎无法弄清楚的简单明显的解决方案。好的,我正在研究斐波那契数列:我想提示用户输入一个整数。然后它将运行将每个元素添加到 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);
}

}

}

最佳答案

顺便说一句,

iluxa 的方法更好。逻辑清晰,避免困惑。

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

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

关于java - Java 中计时器的 IndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16429764/

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