Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // ***************************************************************************************/
- // File Name: JRT_Fibonacci.java Author: Justin Trubela /
- // Section: 03 /
- // /
- // Purpose: 4.Write an array that contains the first 20 using a calculation /
- // to generate the numbers /
- //The program prints the first 20 Fibonacci numbers in the array XX
- // separated by a comma and a space. XX
- //
- //Asks the user which of the numbers in this series of 20 he wants to see XX
- // and prompts for an integer input - a number between 1 and 20(inclusive).
- // So if the user wants to see the fifth (5th) number of the Fibonacci series
- // the user would input the integer 5 in response to the prompt.
- //
- //Checks that the user has not input a number lower than 1 or higher than 20 XX
- //
- //Prints in response to the user entry "The nth Fibonacci number is X", XX
- // where n is the number input by the user and X is the nth Fibonacci number.
- // (Array indexes for the elements of the array start at 0),
- // Example: If user inputs "6" in response to the prompt,
- // the program would print "The 6th Fibonacci number is 5." (without the quotes)
- //****************************************************************************************/
- import java.util.Scanner;
- public class JRT_Fibonacci {
- public static void main (String[] args) {
- Scanner scan = new Scanner(System.in);
- int limit = 20;
- long[] series = new long[limit];
- //create first 2 series elements
- series[0] = 0;
- series[1] = 1;
- long f1=0,f2=1,f3;
- for (int i= 0; i<20; i++) {
- f3=f1+f2;
- series[i]=f3;
- f1=f2;
- f2=f3;
- if(i<series.length-1) {
- System.out.print(series[i]+", ");
- }
- else {
- System.out.print(series[i]+".");
- }
- }
- System.out.println("\n\nEnter the number of the Fibonacci Series would you like to see:");
- int userInputFibNum = scan.nextInt();
- while (userInputFibNum < 1 || userInputFibNum > 20) {
- System.out.println("Number must be between 1 and 20");
- System.out.println("\n\nEnter the number of the Fibonacci Series would you like to see:");
- userInputFibNum = scan.nextInt();
- }
- String postfix = "th";
- if(userInputFibNum == 1) {
- postfix = "st";
- }
- else if(userInputFibNum == 2) {
- postfix = "nd";
- }
- else if(userInputFibNum == 3) {
- postfix = "rd";
- }
- System.out.println("The "+userInputFibNum + postfix + " Fibonacci number is: " + series[userInputFibNum-1]);
- scan.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment