User Tools

Site Tools


it-artikel:java:my-solution-on-assignment-2-problem-6

My Solution on Assignment 2 - Problem 6

This is my Solution of Assignment 2 - Problem 6 from the Computer Science Course CS106A of Prof. Mehran Sahami at the STANFORD University.

Hailstone.java
/*
 * File: Hailstone.java
 * Name: Axel Werner
 * Section Leader: 
 * --------------------
 * This file is the starter file for the Hailstone problem.
 */
 
import acm.program.*;
 
/**
 * Class to ask User for a integer start number to 
 * calculate Hailstone Numbers sequence.
 * @author Axel Werner
 */
public class Hailstone extends ConsoleProgram {
 
	/**
	 * Main Program
	 */
	public void run() {
		println("Hailstone Calculator");
		println("===================================\n\n");
 
		int input = askForNumber();
 
		println("Calculating Hailstone Numbers now:\n");
 
		int tmp = doCalculations(input);
 
		println("Last Hailstone Number ('" + tmp + "') reached.");
		println("I needed '" + stepsCounter + "' Steps to reach this point.\n\n");
		println("Im done. == TERMINATED ==");
	}
 
	/**
	 * Method to calculate the Hailstone Numbers.
	 * It takes a single positive integer number, calculates and prints out 
	 * the Hailstone Row and then returns the last Number (1).
	 * 
	 * @param input any positive integer number
	 * @return Always returns 1, as is always the last Hailstone Number in a Calculation. Why that? 
	 * 			Just for readability.
	 */
	private int doCalculations(int input) {
		int tmp = input;
		while(tmp!=1){
			stepsCounter++; // increment the Step Counter.
			if( isEven(tmp) ){
				int oldTmp=tmp;
				tmp=tmp/2;
				println( oldTmp + " is even. So i take 1/2: " + tmp );
			}else{ // so must be Odd then...
				int oldTmp=tmp;
				tmp=tmp*3+1;
				println( oldTmp + " is odd. So i make 3n+1: " + tmp );
			}
		}
		return tmp;
	}
 
	/**
	 * Method asks User for a positive integer Number and 
	 * then return it.
	 * 
	 * @return positive integer Number given by User Input.
	 */
	private int askForNumber() {
		int input = readInt("Pick a positive integer Number: ");
		while(input<=0){
				println("ERROR: You need to pick a POSITIVE INTEGER. Please retry.\n");
				input = readInt("Pick a positive integer Number: ");
		}
		println("Thanks!\n");
		return input;
	}
 
	/**
	 * Method takes an integer number to test if its even. 
	 * It returns TRUE if Number is even. 
	 * Else it returns FALSE.
	 *   
	 * @param tmp integer number to test
	 * @return TRUE if parameter is an even Number. Else returns FALSE.
	 */
	private boolean isEven(int tmp) {
		if(tmp%2!=0){
			return false; // there is a remainder. So it must be ODD.
		}else{
			return true; // there is NO remainder. So it must be EVEN.
		}
	}
 
	/**
	 * Instance Var to keep track of the Number of Steps needed to reach 1
	 */
	private int stepsCounter=0; 
}

Axel Werner 2012-04-02 20:30

it-artikel/java/my-solution-on-assignment-2-problem-6.txt · Last modified: 2022-08-31 12:30 by 127.0.0.1