Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Verify User Input is a number only on Fibonacci sequence

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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");
    

    }

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading