Java Reference
In-Depth Information
The Fibonacci Series
The Fibonacci numbers are a sequence of numbers in which each successive num-
ber is the sum of the two preceding numbers. The sequence begins 1, 1, 2, 3, 5, 8,
13, and goes on from there. This sequence appears in interesting places in nature.
For example, the number of petals on most species of flowers is one of the
Fibonacci numbers.
Example 1-3 shows a program that computes and displays the first 20 Fibonacci
numbers. There are several things to note about the program. First, it again uses a
for statement. It also declares and uses variables to hold the previous two num-
bers in the sequence, so that these numbers can be added together to produce the
next number in the sequence.
Example 1−3: Fibonacci.java
package com.davidflanagan.examples.basics;
/**
* This program prints out the first 20 numbers in the Fibonacci sequence.
* Each term is formed by adding together the previous two terms in the
* sequence, starting with the terms 1 and 1.
**/
public class Fibonacci {
public static void main(String[] args) {
int n0 = 1, n1 = 1, n2;
// Initialize variables
System.out.print(n0 + " " +
// Print first and second terms
n1 + " ");
// of the series
for(int i = 0; i < 18; i++) { // Loop for the next 18 terms
n2 = n1 + n0; // Next term is sum of previous two
System.out.print(n2 + " "); // Print it out
n0 = n1;
// First previous becomes 2nd previous
n1 = n2;
// And current number becomes previous
}
System.out.println();
// Terminate the line
}
}
Using Command-Line Arguments
As we've seen, every standalone Java program must declare a method with exactly
the following signature:
public static void main(String[] args)
This signature says that an array of strings is passed to the main() method. What
are these strings, and where do they come from? The args array contains any
arguments passed to the Java interpreter on the command line, following the name
of the class to be run. Example 1-4 shows a program, Echo , that reads these argu-
ments and prints them back out. For example, you can invoke the program this
way:
% java com.davidflanagan.examples.basics.Echo this is a test
Search WWH ::




Custom Search