Hi:
I have to write a program generating the fibonacci sequence based on the length desired by the user. I'm using arrays and methods too. So I have to do one method to generate the sequence and another to print the other method. So far so good, except the last value is repeated. For example if I input 5, this is what it should come out
0 1 1 2 3
except this comes out
0 1 1 2 3 3
Here's what I done
import java.util.Scanner; //import scanner public class TestFibArray { public static void main(String[] args) { Scanner sc = new Scanner(System.in); //create new scanner //Prompt user for length System.out.print("How many fib terms would you like to display? "); int lenght = sc.nextInt(); int[] p = new int[lenght]; //set new array p equal the defined user length printTerms( p, lenght ); //method to print terms }//main end //method to populate and calculate array and fib sequence public static int getNTerms( int[] p, int lenght ) { //print first two terms p[1] = 0; p[2] = 1; int newTerm = 0; //new value to calculate new terms on the sequence other that the first two if ( lenght == 1 ) System.out.println(p[1]); else if ( lenght == 2 ) System.out.println( p[1] + " " + p[2]); else { //print rest of terms System.out.print( p[1] + " " + p[2] + " "); //for loop to calculate the rest of the terms for ( int index = 3; index <= lenght; index++) { newTerm = p[1] + p[2]; System.out.print( newTerm + " "); p[1] = p[2]; p[2] = newTerm; } } return newTerm; } //nterms end //print terms public static void printTerms ( int[] p, int lenght ) { //print on console System.out.print(getNTerms ( p, lenght )); } //print end } // file endAny tips would be appreciated :)
fyi, "length" is the correct spelling. A trace of p[1] and p[2] is as follows:
p[1] p[2] newTerm
0 1 1
1 1 2
1 2 3 (for loop terminates here!)
And then you return newTerm (3) to printTerms(), which displays the number again. I would delete the printTerms() method, rename the getNTerms() to printNTerms(), and remove the "return newTerm;" line and change the method type from "int" to "void".