java - ArrayIndexOutOfBoundException when input is zero -


here code calculating fibonacci of n. don't when n = 0, arrayindexoutofboundexception raised. fib function when n = 0, should return 0. cause this?

import java.util.scanner; public class fibonacci {     public static int fib(int n) {         int[] t = new int[n + 1];         t[0] = 0;         t[1] = 1;         (int = 2; < t.length; i++) {             t[i] = t[i - 1] + t[i - 2];         }         return t[n];     }     public static void main(string[] args) {         scanner in = new scanner(system.in);         (;;) {             if (!in.hasnextint()) {                 in.next();                 continue;             }             int n = in.nextint();             if (n >= 0) {                 system.out.println(fib(n));             } else {                 system.out.println("invalid input!");             }             break;          }     } } 

when n = 0, array int[] t = new int[n + 1]; holds 1 element. however, try allocate 2 elements:

t[0] = 0; t[1] = 1;


Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -