Java中带计时器的IndexOutOfBoundsException
我有一个问题,希望能有一个简单明了的解决方案,但我似乎无法解决。好的,我在玩斐波那契序列:我想提示用户输入一个整数。然后,它将运行将每个元素添加到Arraylist的序列。然后,我想用一个计时器将数组列表中的每个元素显示到控制台上——序列中的每个元素每秒显示一次——我用一个简短的方法来实现这一点 输出良好。就在我运行程序时,我得到了IndexOutOfBoundsException。我理解问题发生的原因。我的计数超过了数组列表的大小。我本想玩弄>、=,等等,但没有解决问题。我想用while循环来解决这个错误,但这不起作用。我的问题是:如何计数而不超过数组列表的索引限制 这是我的密码:Java中带计时器的IndexOutOfBoundsException,java,methods,timer,arraylist,fibonacci,Java,Methods,Timer,Arraylist,Fibonacci,我有一个问题,希望能有一个简单明了的解决方案,但我似乎无法解决。好的,我在玩斐波那契序列:我想提示用户输入一个整数。然后,它将运行将每个元素添加到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);
}
公共类序列{
静态整数秒=0;
静态定时器;
静态ArrayList fibList=新ArrayList();
公共静态void main(字符串[]args){
布尔值noError=true;
扫描仪sc=新的扫描仪(System.in);
//将存储偶数之和
int-tmp=0;
//定时器变量
int延迟=1000;
整数周期=1000;
定时器=新定时器();
//输入用户输入,尝试捕获以消除无效输入
做{
试一试{
System.out.println(“请输入一个数字:”);
int input=Integer.parseInt(sc.nextLine());
//从用户输入添加到arraylist
对于(int i=0;i=fibList.size())
timer.cancel();
返回秒++;
}
//斐波那契序列
公共静态整数fib(整数n){
if(n<2){
返回n;
}
否则{
返回fib(n-1)+fib(n-2);
}
}
}您正在从
setInterval()
返回一个seconds++
,并使用它来获取数组列表元素,即使您已经取消了计时器,因为您知道您走得太远了。相反,您应该像这样做
public void run() {
int nextIndex = setInterval();
if (nextIndex < fibList.size()) {
System.out.print(fibList.get(nextIndex)+ ",");
}
}
public void run(){
int-nextIndex=setInterval();
if(nextIndex
这样,您就不会试图打印出太大的索引;线程将在下一次迭代之前被取消。顺便说一下,iluxa的方法更好。逻辑清晰,避免了混淆 但是,如果您只是想修复测试条件,请将
if
更改为
if (seconds == fibList.size() - 1)