CH7 – The While Statement

  1. Create a new class named WhileMethod and add the following method.
public class WhileMethod {
  public static void countDown(int n){
    while(n>0){
      System.out.println(n);
      n = n-1;
    }
    System.out.println("Blastoff!");
  }
  public static void main(String[] args){
    WhileMethod.countDown(4);
  }
}
  1. Compile and run the program.
$ javac WhileMethod.java
$ java WhileMethod
4
3
2
1
Blastoff!
  1. Create a new class named Sequence and add the following code.
public class Sequence{
  public static void sequence(int n){
    while(n!=1){
      System.out.println(n);
      if(n%2 == 0){
        n = n/2;
      }
      else {
        n = n * 3 + 1;
      }
    }
  }
  public static void main(String[] args){
    Sequence.sequence(3);
  }
}
  1. Compile and run the program.
$ javac Sequence.java
$ java Sequence
3
10
5
16
8
4
2