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