import java.util.Scanner;
public class Fibonacci {
public static void main(String args[]) {
int result = UserInput();
fibArray[0] = 1;
fibArray[1] = 1;
for (int i = 0; i < result; i++)
System.out.print(fibonacci(i) + " ");
}
public static long fibArray[] = new long[1000];
public static long fibonacci(long n) {
long fibValue = 0;
if (n == 0) {
return 0;
} else if (n == 1) {
return 1;
} else if (fibArray[(int) n] != 0) {
return fibArray[(int) n];
} else {
fibValue = fibonacci(n - 1) + fibonacci(n - 2);
fibArray[(int) n] = fibValue;
return fibValue;
}
}
public static int UserInput() {
System.out.print("Enter a Fibonacci Number ");
Scanner test = new Scanner(System.in);
int n = test.nextInt();
return n;
}
}
Hi This is not homework nor is it a college assignment. I’m just learning java and I would like to implement a check in my UserInput method on Fibonacci sequence, I want only numbers to be entered and not special characters or letters. I’ve read other similar topics here but
I’m still a bit unsure as to how to do this.
How would I achieve this ?
And btw sorry if the code is sloppy.
Thanks
>Solution :
To check if an entered value is part of a fibonacci series
- first add a set to add the fibValue in your method where you add it to the long array
public static Set<Long> fibSet = new HashSet<>();
-
then do the following:
int value = UserInput(); boolean has = fibSet.contains(value); for (int i = 0; i < 1000 && has == false; i++) { if (value == fibonacci(i)) { has = true; break; } } System.out.println(value + " is" + (has ? "" : " not") + " a term in the standard fibonacci sequence");}