Ch5 – Binary Numbers

  1. Create a new class named BinaryNumbers and add the following method.
public static void countup(int n){
  if(n==0) {
    System.out.println("Blastoff!");
  } else {
    countup(n-1);
    System.out.println(n);
  }
}
  1. Add a main method that calls the countUp method. Have the method take a number from the command-line.
public static void main(String[] args){
  int thenum = Integer.parseInt(args[0]);
  BinaryNumbers.countup(thenum);
}

The complete class should appear as follows.

public class BinaryNumbers {
  public static void countup(int n){
    if(n==0) {
      System.out.println("Blastoff!");
    } else {
      countup(n-1);
      System.out.println(n);
    }
  }
  public static void main(String[] args){
    int thenum = Integer.parseInt(args[0]);
    BinaryNumbers.countup(thenum);
  }
}
  1. Compile the program and then run it with a parameter.
$ javac BinaryNumbers.java 
$ java BinaryNumbers 4 
Blastoff! 
1 
2 
3 
4