0
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

brian.p
  • 97
  • 6

3 Answers3

1

Check this out.

You can modify your code like this. The idea is to check whether the String you are getting from the Scanner is an integer or not (using the Integer#parseInt method). Also the general convention in java is to use lower camel case for the method name.

public static void userInput(){
    System.out.print("Enter a Fibonacci Number");
    Scanner test = new Scanner(System.in);
    String possibleInteger = test.next();
    if(isInteger(possibleInteger)){
      //Continue with your code
    }
}

private static boolean isInteger(String possibleInteger){
    try{
        Integer.parseInt(possibleInteger);
        return true;
    } catch( NumberFormatException ignore ){
        return false;
    }
}
Saltuk Kezer
  • 105
  • 1
  • 7
  • Hi Saltuk thanks for your answer.probably a stupid question but I could I put the for loop inside the void method and sys out the numbers as normal? Thanks again – brian.p Dec 18 '21 at 15:31
  • Thanks yair I'll look into your suggestion – brian.p Dec 18 '21 at 15:31
  • 1
    Yes you can just put the loop inside the void method and sysout the numbers as you are used to. The code i wrote is just there for checking if the input is an Integer or not. – Saltuk Kezer Dec 18 '21 at 15:37
  • Understood thanks Saltuk – brian.p Dec 18 '21 at 15:39
1

btw, i would approach this with building the fibonacci sequence in an iterative way instead of recursive and memoization (and just check if the current number is bigger than the checked one) , that way you don't need the extra space and you can support larger than fib_1000, good luck!

yair koskas
  • 134
  • 5
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 18 '21 at 15:32
  • 1
    Apologies for that – brian.p Dec 18 '21 at 15:39
1

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

    }

Note that the static set is only useful for multiple runs in the same program as is checks for previously added entries.

And the 1000 value in the loop is arbitrary and can be altered to either increase or decrease the number of terms.

Updated Answer.

As you may already know, computing fibonacci series using recursion is an excellent exercise in seeing how that would work. But in practice it is incredibly slow. As was mentioned in some comments, a simple iterative method is preferred and remembering previous computations (memoization) increases its efficiency. Here is an example:

long testValue = UserInput();
boolean has = isFibonacciTerm(testValue);

System.out.println(testValue + " is" + (has? "" : " not")
        + " a term in the standard fibonacci sequence");
    
public static List<Long> fibList = new ArrayList<>(List.of(0L,1L));
public static Set<Long> fibSet = new HashSet<>(fibList);
    
public static boolean isFibonacciTerm(long testValue) {
    long lastComputed = fibList.get(fibList.size()-1);
    int start = fibList.size()-1;
    while (testValue > lastComputed) {
        lastComputed += fibList.get(start-1);
        fibList.add(lastComputed);
        fibSet.add(lastComputed);
        start++;
    }
    return fibSet.contains(testValue);
}
  • the method only generates sufficient terms starting from the previous computed until the value under test is at least as large.
  • the the set is checked to see if it has the value under test.

The list allows for ordered access to get the most recent computed value and the set simply allows for quick lookup (a conditional could have been employed for certain cases but I decided to let the set handle that).

Note that this can also be used to generate fibonacci sequences just by putting in a limiting term and printing the list.

WJS
  • 36,363
  • 4
  • 24
  • 39
  • 1
    Thanks WJS for your time and for the example.I have a lot to learn – brian.p Dec 18 '21 at 20:38
  • Hi WJS can you explain why you don't think this code compiles because I've tested it and it does compile and run.also what other problems do you see with my original code – brian.p Dec 19 '21 at 22:10
  • It has since been corrected but the poster tried to use an int value as a reference and call a.method. Can you see the edit history? – WJS Dec 19 '21 at 22:16
  • I'm sorry are you referring to coder kids post or my original code post? In terms of using an int value as a reference...sorry for any confusion.i cant see edit history for some reason – brian.p Dec 19 '21 at 22:26
  • I was referring to `coder kid`. But they fixed their code. – WJS Dec 19 '21 at 22:49
  • Since my comment is OBE I am going to delete it. Sorry about the confusion. – WJS Dec 19 '21 at 22:57
  • My confusion really so sorry..but again I can't thank you enough for your help and code example. – brian.p Dec 19 '21 at 23:28