Dragon.java


Below is the syntax highlighted version of Dragon.java from §1.3 Conditionals and Loops.


/******************************************************************************
 *  Compilation:  javac Dragon.java
 *  Execution:    java Dragon n
 *
 *  Prints the instructions for drawing a dragon curve of order n.
 *
 *  % java Dragon 0
 *  F
 *
 *  % java Dragon 1
 *  FLF
 *
 *  % java Dragon 2
 *  FLFLFRF
 *
 *  % java Dragon 3
 *  FLFLFRFLFLFRFRF
 *
 *  % java Dragon 4
 *  FLFLFRFLFLFRFRFLFLFLFRFRFLFRFRF
 *
 *  % java Dragon 5
 *  FLFLFRFLFLFRFRFLFLFLFRFRFLFRFRFLFLFLFRFLFLFRFRFRFLFLFRFRFLFRFRF
 *
 ******************************************************************************/

public class Dragon {
    public static void main(String[] args) {
        int n = Integer.parseInt(args[0]);
        String dragon = "F";
        String nogard = "F";
        String temp;

        for (int i = 1; i <= n; i++) {
            temp = dragon;                     // save away copy of dragon
            dragon = dragon + "L" + nogard;
            nogard = temp   + "R" + nogard;    // use old value of dragon
        }
        System.out.println(dragon);
    }

}


Copyright © 2000–2022, Robert Sedgewick and Kevin Wayne.
Last updated: Thu Aug 11 10:12:31 EDT 2022.