import java.util.InputMismatchException;
/**
* This is a class implements a Java application that:
*
* - executes 4 methods, 2 iterative and 2 recursive.
* - accepts an integer Q on the command line. This integer is the input for
* all 4 methods.
* - if the command line has anything other than a single integer, the
* program prints an error message and exit.
* - if the integer Q is negative or zero, the program exits without printing
* anything.
* - otherwise, executes each of the following four methods:
*
* - Method 1: use a loop to print a row of Q asterisks.
* - Method 2: use recursion to print a row of Q asterisks.
* - Method 3: use a loop to print the numbers Q, Q - 1, ... 3, 2, 1.
* - Method 4: use recursion to print the numbers Q, Q - 1, ... 3, 2, 1.
*
*
*
*
* @author Cheng Yu
* @assignment TA 2 part 2
* @date Aug 29, 2008
* @bugs None
*/
public class ChengJade01Part2 {
/**
* The entry point of the application.
*
* @param args The command line arguments.
*/
public static void main(final String[] args) {
// If the command line has anything other than a single integer, the program
// prints an error message and exits.
if (args.length != 1) {
System.err.println("Wrong number of arguments.");
return;
}
int q = 0;
try {
q = Integer.parseInt(args[0]);
} catch (final NumberFormatException e) {
System.err.print("Argument is not an integer.");
return;
}
// If the integer Q is negative or zero, the program exits without printing
// anything.
if (q <= 0)
return;
// Call the methods.
ChengJade01Part2.printAsterisksWithLoop(q);
System.out.println();
ChengJade01Part2.printAsterisksRecursively(q);
System.out.println();
ChengJade01Part2.printNumbersWithLoop(q);
System.out.println();
ChengJade01Part2.printNumbersRecursively(q);
// Exit cleanly while debugging from Eclipse.
System.exit(0);
}
/**
* Use recursion to print a row of Q asterisks.
*
* @param n The number of asterisks to print.
*/
private static void printAsterisksRecursively(final int n) {
assert n > 0;
if (n == 1) {
System.out.print("*");
return;
}
System.out.print("* ");
ChengJade01Part2.printAsterisksRecursively(n - 1);
}
/**
* Use a loop to print a row of Q asterisks.
*
* @param n The number of asterisks to print.
*/
private static void printAsterisksWithLoop(final int n) {
assert n > 0;
for (int i = 0; i < n - 1; i++)
System.out.print("* ");
System.out.print("*");
}
/**
* Use recursion to print the numbers Q, Q - 1, ... 3, 2, 1.
*
* @param n The number of numbers to print.
*/
private static void printNumbersRecursively(final int n) {
assert n > 0;
if (n == 1) {
System.out.print(1);
return;
}
System.out.print(n + " ");
ChengJade01Part2.printNumbersRecursively(n - 1);
}
/**
* Use a loop to print the numbers Q, Q - 1, ... 3, 2, 1.
*
* @param n The number of numbers to print.
*/
private static void printNumbersWithLoop(final int n) {
assert n > 0;
for (int i = n; i > 1; i--)
System.out.print(i + " ");
System.out.print(1);
}
}