Skip to content

Instantly share code, notes, and snippets.

@kenechiokolo
Created March 17, 2015 09:04
Show Gist options
  • Save kenechiokolo/7ed688fbfdb1e26f7c2d to your computer and use it in GitHub Desktop.
Save kenechiokolo/7ed688fbfdb1e26f7c2d to your computer and use it in GitHub Desktop.
CS106A: Assignment 2.6 - Hailstone Sequence
/*
* File: Hailstone.java
* Name:
* Section Leader:
* --------------------
* This file is the starter file for the Hailstone problem.
*/
import acm.program.*;
public class Hailstone extends ConsoleProgram {
public void run() {
askUserInput();
computeSequence();
displayStepNumber();
playAgain();
}
int n = 1;
private void askUserInput() {
n = readInt("Enter a number: ");
}
int i = 0;
private void computeSequence() {
while (n != 1) {
if ((n % 2) == 0) {
int nHalf = n / 2;
println (""+n+" is even, so I take half: "+nHalf+"");
n = nHalf;
i++;
} else {
int nOddOperation = n * 3 + 1;
println(""+n+" is odd, so I make 3n + 1: "+nOddOperation+"");
n = nOddOperation;
i++;
}
}
}
private void displayStepNumber() {
println("The process took "+i+" steps to reach 1.");
}
private void playAgain() {
int y = readInt("Enter 1 if you would like to play again... ");
if (y == 1) {
run();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment