# fibonacci sequence

• 04-17-2013, 08:41 PM
5imp7y
fibonacci sequence
Hallo alle,

Long time lurker, first time poster. I hate to be the one who have no posts and starts off their career on a forum with a noob question, but im stuck and there has to be a batter way to do this. I just want to point out this isnt a homework problem, I am just preparing for a java course that i will be taking next semester.

I found this on some other forum, i forget where but here is the main idea of what i need to do: Take a user input and return the next number in a fibonacci sequence for the number the user has entered and continue to enter the next number (after the preceeding one) until the user stops asking for the next number. Example. The user enters 4, Return is 4, next return is 8 next return is 12 ect... I know that the normal fibonacci sequence is 1 1 2 3 5 8 ect and to change it to start with a different number you just multiply each number by the starting digit, but im still struggling.

Here is my sad attempt at this practice problem:
Code:

```import java.util.Scanner; public class fibseq {         //scanners for 2 inputs, first a number then a choice(yes or no)                 static Scanner in = new Scanner(System.in);                 static Scanner in2 = new Scanner(System.in);                         static String choice;        // choice of yes or no                         static String yes = "yes";  // yes string to compare                         static String no = "no";    // no string to compare                         static int i = 0;          // int i is used to find the next number but save fNumber                          static int y = 0;        // this is the int that i will switch with in repeat                         static int fNumber;      // fNumber means first number                                                                 public static void main(String[] args)                         {                         getNumber();                         responce();                         }                                 public static void getNumber()                         {                                        //get the number                         System.out.println("Enter your number(single digit 1 - 9 no 0): ");                         fNumber = in.nextInt();                         nextNumber();                         }                                 public static void nextNumber()                         {                         while(i < fNumber)                                 {                                         i = fNumber;                                 }                         }                 public static void repeat()                         {                         y = i + fNumber;                                                 System.out.println(y);                         while ( >= fNumber)                                 {                                                                 }                         }                                 public static void responce()                         {                         System.out.println(i + "\n");                         System.out.println("Whould you like the number after this as well?");                         choice = in2.next();                                                         //idk if i should make another method for this....                         if (choice == no)                                 {                                 System.out.println("Goodbye!");                                 System.exit(0);                                 }                         if (choice == yes)                                 {                                 /* This is where i get lost i need to basically tell the                                 * system to take the last number which should be stored                                 * in the int i and then add it with the original number                                 * which shoould be stored in fNumber, then output it,                                 * then give the user a change to ask for the number after                                 * that as well. Below is a random attempt i have been                                 * trying to dev refer to the method repeat.                                 */                                 repeat();                                 }                         } }```
Thanks for the help, I hope this isnt an overwhelming amount of code to post. I also feel as if i have over complicated this.

Thanks again,
5imp7y
• 04-17-2013, 09:30 PM
Fou-Lu
Lets start in main. The first thing you do is ask for the number, 1 - 9 inclusive. You then scan that number in. Assign this number to two new variables, iStart and iCurrent. Set iLast to 0.

Next, there are two pretty much un-needed methods: nextNumber() and repeat(). You can do these both very easily within responce(). Just takes a little thought on which variables to use for the class. Use these for your properties:

PHP Code:

``` private static Scanner in;private static int iStart = 0;private static int iLast = 0;private static int iCurrent = 0;  ```
Start is your start number, and only required if you actually want to do something after the fact with it. Current is the current number, and last is the previous. Since the next is always current + last, there is no need to calculate with looping.
PHP Code:

```         public static void responce()        {            String sContinue = "";            int iNext = 0;            do            {                sContinue = "";                iNext = iLast + iCurrent;                System.out.println(iNext + "\n");                iLast = iCurrent;                iCurrent = iNext;                System.out.print("Would you like the next number as well?");                sContinue = in.nextLine().trim();            }            while (sContinue.equalsIgnoreCase("yes") || sContinue.equalsIgnoreCase("y"));        }  ```
I'd also override the responce to accept an integer for the next n values. That way I can simply ask for the next x numbers to show without having to get input. That would then separate the internal handling of the loop and put it into its own method to which both methods can call it.
After that, assemble the main to loop for more. That gives me an end class of:
PHP Code:

``` import java.util.Scanner;public class fibseq{    private static Scanner in;    private static int iStart = 0;    private static int iLast = 0;    private static int iCurrent = 0;    public static void main(String[] args)    {        String sContinue = "";        in = new Scanner(System.in);        do        {            sContinue = "";            getNumber();            responce();            System.out.print("Would you like to try another number? ");            sContinue = in.nextLine().trim();        }        while (sContinue.equalsIgnoreCase("yes") || sContinue.equalsIgnoreCase("y"));        in.close();        System.out.println("Goodbye.");    }    public static void getNumber()    {                System.out.print("Enter your number(single digit 1 - 9 no 0): ");        iStart = iCurrent = in.nextInt();        iLast = 0;        in.nextLine();    }    public static void responce()    {        String sContinue = "";        int iNext = 0;        do        {            sContinue = "";            iNext = iLast + iCurrent;            System.out.println(iNext + "\n");            iLast = iCurrent;            iCurrent = iNext;            System.out.print("Would you like the next number as well?");            sContinue = in.nextLine().trim();        }        while (sContinue.equalsIgnoreCase("yes") || sContinue.equalsIgnoreCase("y"));    }}  ```
Note that sContinue is always compared with .equals or .equalsIgnoreCase. You cannot reliable use == comparisons with objects in Java (for string values that is). Strings are immutable, so "y" == "y", but new String("y") == "y" is not true.

Fibonacci can of course be designed iteratively or recursively as well (which is the whole point of it), but for simple terms of fibonacci growth I'd suggest just knowing the current and previous is sufficient. I would write the actual method to recurse or iterate it to get the sequence only so it can be extended to tri and tetranocci numbers without needing to change much code.
• 04-17-2013, 10:54 PM
5imp7y
Ok, I think im getting this much better. I have never used the do or while functions outside of c++, i just have a few questions.

Why did you declare the integers and scanner private? I have a very vague understanding of the whole private world of java. I understand it means that it cannot be called from outside that method, though i might be wrong about that also.

And my last question is what exactly does the do function "do"....?

Thanks for the response and thorough instructions. :D
• 04-17-2013, 11:12 PM
Fou-Lu
Private reduces the scope of access to only this class. Java has 3 explicit scopes: private, protected and public (this class, this class and child classes, and any), as well as one implicit scope of package (anything within package). When no scope is provided, package is assumed.
I always use private/protected unless the variable is final. Anything above allows direct write to the variable which means I could end up with an invalid value (0 in the case of numbers here when 0 should be checked for an an exception tossed) and nulls for objects. You don't want these conditions to ever occur, but you can enforce them by using the setter methods instead.
do is not a function but a construct. Its the same thing as a while loop but it guarantees at least one run through the loop whilst the while loop only guarantees a run if the condition is valid to start with.