Home > Blockchain >  Verify User Input is a number only on Fibonacci sequence
Verify User Input is a number only on Fibonacci sequence

Time:12-19

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

CodePudding user response:

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.

CodePudding user response:

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;
    }
}

CodePudding user response:

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!

CodePudding user response:

This is the solution I have it works with most numbers but can fail if it receives numbers bigger than the number limit for integers. public static boolean checkIfNumber() {

   int pin = 21211;
   Integer pinT = pin;
   int total = 0;
  //Make a character array with all the characters that you want to have.
  char[] numbers = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'};
  
  for (int i = 0; i < number.length; i  ) {
       if (pinT.toString().contains(numbers[i]) {
       total  = 1;
       }
      }
  return total < pintT.toString().length();
    
       
  •  Tags:  
  • java
  • Related