Stanford cs106a Assignment 2, Problem 2 – Hailstone sequence

Here is my answer to the hailstone sequence problem. The problem is as follows:

Pick some positive integer and call it n.
If n is even, divide it by two.
If n is odd, multiply it by three and add one.
Continue this process until n is equal to one.

The numbers go up and down, but eventually—at least for all numbers that have ever been tried—comes down to end in 1. In some respects, this process is reminiscent of the formation of hailstones, which get carried upward by the winds over and over again before they finally descend to the ground. Because of this analogy, this sequence of numbers is usually called the Hailstone sequence, although it goes by many other names as well.


/*
* File: Hailstone.java
* Name: Jason Coltrin
* Section Leader: n/a
* --------------------
*This file is the starter file for the Hailstone problem.
*Pick some positive integer and call it n. If n is even,
*divide it by two. If n is odd, multiply it by three and
*add one. Continue this process until n is equal to one.
*/

import acm.program.*; //needed to run ConsoleProgram

public class Hailstone extends ConsoleProgram {
public void run() {

int n = readInt("Enter a number:"); // get user's number
int evenNum; // define even number as integer
int oddNum; // define odd number as integer
int halfNum; // define Hailstone step1 if number is even as integer
int tripleOne; // define Hailstone step1 if number is odd as integer 3n+1
int count = 0; // define steps it takes to get to 1 as count and initialize at 0

if (n == 1) {
println("Please enter a number larger than 1.");
}

while (n != 1) { // run if/else statement until n is not equal to 1

if ((n % 2) == 0) {
evenNum = n;
halfNum = (evenNum / 2);
println(evenNum + " is even, so I take half: " + halfNum);
n = halfNum;

} else {
oddNum = n;
tripleOne = ((3 * n) + 1);
println(oddNum + " is odd, so I make 3n+1: " + tripleOne);
n = tripleOne;

}
count++; //increment counter 1 for every while loop
}

println("You've reached the number 1, I'm stopping.");
println("The process took " + count + " steps to reach 1.");
}
}

This problem makes use of a while/if/else loop, and increment a counter. I thought I would have to use a For loop and a Boolean to increment the counter, but once I initialized the count variable at 0, it just took a little work to place the count++ in the correct location.

Here is what the output looks like:
HailstoneConsole