Java Sentence Reverser

This is a program I wrote in Data Structures last semester that takes a string as its input, pushes it onto a stack, and then returns the string reversed. It contains a few bits of code rather than just a single, monolithic application like you’ve seen me write so far. So if you want to compile this, you will need all the pieces.

  1. ArrayStack.java
  2. EmptyCollectionException.java
  3. SentenceReverser.java (The main program)
  4. StackADT.java

Once you’ve saved all four files in the same directory, you can compile SentenceReverser.java (which will, in turn, call the other three to be compiled.) But first, let’s look at the main program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// --------------------------------------------------------
// Programmer:  Jonathan Landrum
// Date:        6 October 2011
// Class:       CSC 216
// --------------------------------------------------------
// Program:     SentenceReverser.java
// Purpose:     Takes a sentence from the user and reverses
//              the order using a stack.
// Assumptions: None.
// --------------------------------------------------------
 
import java.util.Scanner;
 
public class SentenceReverser {
	// ------------------------------------------------
	// Main:
	// Introduces the program and takes input from
	// the user.
	// ------------------------------------------------
	public static void main (String[] args) {
 
		// ------------------
		// Variables
		// ------------------
		Scanner scan = new Scanner(System.in);
		String input = "";
		int stackSize;
 
		// ------------------
		// Introduction
		// ------------------
		System.out.println ("----------------------------------------");
		System.out.println ("-         JAVA STRING REVERSER         -");
		System.out.println ("----------------------------------------");
		System.out.println ();
		System.out.println ("Input a line of text, and this program");
		System.out.println ("will reverse it: ");
		System.out.println ();
 
		input = scan.nextLine();
 
		System.out.println ();
 
		// ------------------
		// Do all the things
		// ------------------
		stackSize = input.length();
		ArrayStack stack = new ArrayStack(stackSize);
 
		// Reverses the input
		for (int i = 0; i < input.length(); i++) {
			char c = input.charAt(i);
			stack.push(c);
		} // End reversal
 
		// Prints the output
		while (!stack.isEmpty()) {
			Object c = stack.pop();
			System.out.print (c);
		} // End printout
	} // End main
} // End SentenceReverser

This program takes a string from the user, and then tries to build a stack object to push the data to. It uses ArrayStack.java to build the stack. A stack is like any stack in nature: Last in, First out. Like a stack of plates in your cupboard, the ones just washed are the ones that will be used next. Likewise, we are taking our string and pushing it onto a stack, so the last item in will be the last character the user typed. And that will, consequently, be the first item popped off the stack (since it’s on top). Thus, a sentence reverser. Here’s ArrayStack.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
public class ArrayStack<T> implements StackADT<T> {
	// ------------------
	// Variables
	// ------------------
	private final int DEFAULT_CAPACITY = 100;
	private int top;
	private T[] stack;
 
	// ------------------
	// Constructors
	// ------------------
	public ArrayStack() {
		top = 0;
		stack = (T[])(new Object[DEFAULT_CAPACITY]);
	} // End ArrayStack default constructor
	public ArrayStack (int initialCapacity) {
		top = 0;
		stack = (T[])(new Object[initialCapacity]);
	} // End ArrayStack modified constructor
 
	// ------------------
	// Methods
	// ------------------
	public void push (T element) {
		if (size() == stack.length)
		expandCapacity();
 
		stack[top] = element;
		top++;
	} // End push
	public T pop() throws EmptyCollectionException {
		if (isEmpty())
		  throw new EmptyCollectionException("Stack");
 
		top--;
		T result = stack[top];
		stack[top] = null;
 
		return result;
	} // End pop
	public T peek() throws EmptyCollectionException {
		if (isEmpty())
		  throw new EmptyCollectionException("Stack");
 
		return stack[top-1];
	} // End peek
	public boolean isEmpty() {
		return (top == 0);
	} // End isEmpty
	public int size() {
		return top;
	} // End size
	public String toString() {
		String result = "";
 
		for (int scan=0; scan < top; scan++)
		result = result + stack[scan].toString() + "\n";
 
		return result;
	} // End toString
	private void expandCapacity() {
		T[] larger = (T[])(new Object[stack.length*2]);
 
		for (int index=0; index < stack.length; index++)
		larger[index] = stack[index];
 
		stack = larger;
	} // End expandCapacity
} // End ArrayStack

It simply contains all the normal methods of a stack: A constructor (in this case, two, so we can specify how large of a stack we want, or if that doesn’t matter, just build us one of the default size), push (to get items on the stack), pop (to get items off of the stack), peek (to see what’s on top of the stack), isEmpty (to test if the stack is empty or not), size (to see how many items are on the stack), toString (to make a printout of the stack), and expandCapacity (to grow the stack as needed).

A couple things you may have noticed: First, pop() and peek() throw an Empty Collection Exception, which you have to define:

1
2
3
4
5
public class EmptyCollectionException extends RuntimeException {
    public EmptyCollectionException (String collection) {
        super ("The " + collection + " is empty.");
    } // End constructor
} // End EmptyCollectionException

Second, you will notice in the header of our stack class that it implements StackADT. That is the abstract data type (ADT) for a generic stack, basically giving a blueprint for how to make a stack. This ADT can be used to build all kinds of stacks. In this case, we’ve built an array stack (hence the name “ArrayStack.java”). Here’s StackADT.java:

1
2
3
4
5
6
7
8
public interface StackADT<T> {
	public void push (T element);
	public T pop();
	public T peek();
	public boolean isEmpty();
	public int size();
	public String toString();
} // End StackADT

This is simply a blueprint or map to making a Stack. Once you have all four of these files compiled, you can use the Sentence Reverser program to do whatever you want that uses a stack. This is a nice starting point for 1.) Writing programs that use other programs as part of their normal operation, and 2.) Writing data structures to maintain and manipulate data sets.

~Jonathan

Collatz Conjecture

I enjoy reading geeky webcomics. It’s one of my guilty pleasures. xkcd is my favorite, by far. A few weeks ago, I was perusing the xkcd store and found the Collatz Conjecture t-shirt (I’m also incredibly partial to geeky shirts.) I wasn’t familiar with the premise of this conjecture, so I hopped over to Wikipedia to see what it’s about.

According to the article, The Collatz Conjecture is the hypothesis that if you follow the algorithm presented, you will always end up at 1. The algorithm is to start with any natural number (a positive integer), and test it: if it’s odd, multiply your number by 3 and add 1; if it’s even, divide it by 2. Continue the algorithm indefinitely, and, according to the conjecture, you will always end up at 1.

That’s the idea, anyway. But it’s never been proven to be true. It’s assumed to be true, but not proven. (It hasn’t been proven because you cannot test every positive integer.) So it’s called a conjecture rather than a rule. And that’s where I started programming. I figured, hey, that’s easy. I’ll just write a program to prove it for me! Well, sort of. There’s an infinite set of positive integers, but a finite amount of memory in my computer. It will eventually run out of memory space on the machine. But it would still theoretically run forever on a perfect computer. What follows is no formal proof, but it’s about as close to a Q.E.D. as we will see for now in this problem. It starts with 2, proves that it goes to 1 (2 / 2 = 1), and then iterates to 3:

  1. 3 * 3 + 1 = 10
  2. 10 / 2 = 5
  3. 5 * 3 + 1 = 16
  4. 16 / 2 = 8
  5. 8 / 2 = 4
  6. 4 / 2 = 2
  7. 2 / 2 = 1

and so on. Now just to find a machine with infinite memory…

~Jonathan

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// *****************************************************
// Programmer:   Jonathan Landrum
// Date:         16 December 2011
// *****************************************************
// Program:      collatz.java
// Purpose:      Testing the Collatz Conjecture
// Assumptions:  None.
// *****************************************************
 
public class collatz {
 
	// ---------------------------------------------
	// main():
	// Does ALL the things
	// ---------------------------------------------
	public static void main (String[] args) {
 
		// -------------------------------------
		// Variables
		// -------------------------------------
		int n, in = 2, out = 1;
		Scanner scan = new Scanner(System.in);
 
		// -------------------------------------
		// Introduce the program
		// -------------------------------------
		System.out.println ("---------------------------");
		System.out.println ("-                         -");
		System.out.println ("- Collatz Conjecture Test -");
		System.out.println ("-                         -");
		System.out.println ("---------------------------");
		System.out.println ();
		System.out.println ("Takes the positive integers");
		System.out.println ("and tests them against the");
		System.out.println ("Collatz Conjecture.");
		System.out.println ();
 
		// -------------------------------------
		// Main block
		// -------------------------------------
		while (out == 1) {
			n = in;
			while (n > 1) {
				if (n%2 == 0) {
					n = n/2;
				} else {
					n = n * 3 + 1;
				} // End if
			} // End while
			out = n;
			System.out.println (in);
			in++;
		} // End while
	} // End main
} // End collatz

FizzBuzz

I stumbled upon an article on Coding Horror the other day whilst perusing the web, and it made my stomach turn. Go read it, honestly. Right now. The premise of the article is there are people graduating from colleges and universities with degrees in Computer Science who can neither read nor write one single line of code.

And not just Associates or Bachelors, no. Full-fledged Masters and Doctorates who don’t know a lick of code, but they’ve earned the highest attainable degree in the field of computing. Granted, there’s definitely a philosophical side to Computer Science, and there are many Computer Science programs in academia that only focus on that end; it is, after all, a science. But if you, the applicant, are applying for a coding job, at least have the wit to familiarize yourself with the language first. If all you know is the science of computing and not the languages thereof, apply for one of those jobs instead.

To weed these codeless candidates out, hiring managers in many shops have taken to giving simple programming assignments to candidates. The one mentioned in the article above is called “FizzBuzz”. Here is my version, written in Java, that I whipped up in about five minutes. It is, quite literally, a Freshman’s problem. I won’t lie, I was a bit insulted at how easy the assignment is. I know you’re not supposed to post the answer. I understand that it’s not the point, that the point is we shouldn’t need FizzBuzz challenges. But I took that article as a personal affront. I had to prove myself, no matter how trivial the test.

“I am not one of them.”

There’s much more code to follow. FizzBuzz is just the beginning.

~Jonathan

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// ****************************************************
// Programmer:           Jonathan Landrum
// Date:                 23 January 2012
// Class:                Comp. Sci. 101 (Seriously)
// ****************************************************
// Program:              FizzBuzz.java
// Purpose:              To prove that I can program.
// Assumptions:          A lot, apparently.
// ****************************************************
 
import java.util.Scanner;
 
public class FizzBuzz {
	public static void main (String[] args) {
 
		// --------------------------------------------
		// Variables
		// --------------------------------------------
		int	c = 1;
		String	response;
		Scanner scan = new Scanner(System.in);
 
		// --------------------------------------------
		// Introduce the program
		// --------------------------------------------
		System.out.println ("-------------------------------------");
		System.out.println ("-             Fizz Buzz             -");
		System.out.println ("-------------------------------------");
		System.out.println ();
		System.out.println ("This program reproduces a traditional");
		System.out.println ("British children's counting game, but");
		System.out.println ("more specifically, it represents a");
		System.out.println ("coding challenge.");
		System.out.println ();
		System.out.print   ("Would you like to continue? [Y/N] ");
 
			response   = scan.nextLine();
 
		// --------------------------------------------
		// Main block
		// --------------------------------------------
		while (response.charAt(0) == 'y' || response.charAt(0) == 'Y') {
			while (c <= 100) {
				if (c > 3) {
					if (c % 3 == 0 && c % 5 == 0) {
						System.out.println ("FizzBuzz");
					} else if (c % 3 == 0) {
						System.out.println ("Fizz");
					} else if (c % 5 == 0) {
						System.out.println ("Buzz");
					} else {
						System.out.println (c);
					} // End test if block
				} else {
					System.out.println (c);
				} // End print if block
				c++;
			} // End main while block
 
			System.out.println ("-------------------------------------");
			System.out.println ("Process complete.");
			System.out.print   ("Would you like to continue? [Y/N] ");
 
				response   = scan.nextLine();
 
		} // End while
		System.out.println ();
		System.out.println ("\\\\//_ Live long and prosper.");
		} // End main
} // End FizzBuzz