Difference between revisions of "Fibonacci sequence"
From CompSciWiki
Line 34: | Line 34: | ||
} | } | ||
− | + | JOptionPane.showMessageDialog(null, "The " + n + "th Fibonacci number is " + current); | |
} | } | ||
} | } | ||
Line 47: | Line 47: | ||
An image or By Students section | An image or By Students section | ||
− | |Solution= | + | |Solution=<pre> |
+ | In order to get the user input by JOptionPane, you will first have to import the swing package. | ||
+ | You can import swing package by | ||
+ | import javax.swing.*; or import javax.swing.JOptionPane; | ||
+ | Then, the next step would be declaring variables; in this program we will need only two int variables. | ||
+ | current will be F(n) and previous will be F(n-1). Do NOT forget to declare them outside the for loop. | ||
}} | }} |
Revision as of 23:28, 1 April 2010
{{1010PrAD
|ProblemName=Fibonacci sequence
|Problem=Write a complete Java program Fibonacci that:
- prompts the user to enter an input n and cast it to integer
- get the nth fibonacci numbers using FOR loop, based on the user's input
- prints out the nth fibonacci number, using JOptionPane.showMessageDialog method.
Note that the fibonacci sequence is F(0) = 1, F(1) = 1, F(n) = F(n-1) + F(n-2) for n > 1.
Example: F(5) = 1, 1, 2, 3, 5, 8
Your output should look something like
"The 5th number of the fibonacci sequence is 5."
You may assume that the user always enters correct intenger format.
import javax.swing.JOptionPane; public class Fibonacci { public static void main(String[] args) { int current = 1; int previous = 0; int n = Integer.parseInt(JOptionPane.showInputDialog("Please enter n")); for(int i = 0; i < n; i++) { int temp = previous; previous = current; current = temp + previous; } JOptionPane.showMessageDialog(null, "The " + n + "th Fibonacci number is " + current); } }
|SideSectionTitle=...by students
|SideSection=
Taken from http://www.flickr.com/photos/daniello/565304023/
An image or By Students section
|Solution=In order to get the user input by JOptionPane, you will first have to import the swing package. You can import swing package by import javax.swing.*; or import javax.swing.JOptionPane; Then, the next step would be declaring variables; in this program we will need only two int variables. current will be F(n) and previous will be F(n-1). Do NOT forget to declare them outside the for loop. }}