
I am trying to write 2 different Fibonacci programs. The first one, I want to allow the user to input 2 integers and then print out the next 10 numbers in the fibonacci sequence. On the next one, I want to allow the user to input 2 integers again and also allow the user to input how many fibonacci numbers they would like the program to print. I need to use a main method that calls the fibonacci method. Here is the code I have so far:
import java.util.Scanner;
public class Fibonacci {
public static void main(String[] args) {
Scanner s = new Scanner( System.in);
System.out.println("How many fibonacci numbers would you like to print: ");
int length = s.nextInt();
long[] series = new long[length];
series[0] = 0;
series[1] = 1;
//Scanner first = new Scanner( System.in);
//System.out.println("Please enter the first number of the Fibonacci series: ");
//firstInt = first.nextInt();
//Scanner second = new Scanner( System.in);
//System.out.println("Please enter the second number of the Fibonacci series: ");
//secondInt = second.nextInt();
//long series[0] = new long[firstInt];
//long series[1] = new long[secondInt];
//create the Fibonacci series and store it in an array
//public static int fib(int n)
for(int i=2; i < length; i++){
series[i] = series[i-1] + series[i-2];
}
//print the Fibonacci series numbers
System.out.println("Fibonacci series to " + length);
for(int i=0; i< length; i++){
System.out.print(series[i] + " ");
}
}
}

Hi Friend,
Try the following code:
1)
import java.util.*;
public class Fibonacci {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Please enter the first number of the Fibonacci series: ");
int f1 = s.nextInt();
System.out.println("Please enter the second number of the Fibonacci series: ");
int f2 = s.nextInt();
int f3=f1+f2;
for(int i=1;i<=10;i++){
System.out.println(f3);
f1=f2;
f2=f3;
f3=f1+f2;
}
}
}
2)
import java.util.*;
public class Fibonacci {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("How many fibonacci numbers would you like to print: ");
int num = s.nextInt();
int f1=0,f2=0,f3=1;
for(int i=1;i<=num;i++){
System.out.println(f3);
f1=f2;
f2=f3;
f3=f1+f2;
}
}
}
Thanks
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.