Java Code Examples: Word Count, Fibonacci, Stack & Queue

Classified in Computers

Written on in English with a size of 6.62 KB

Class: CountOccurrenceOfWords

This class demonstrates how to count the occurrences of words in a given text string using a TreeMap to maintain sorted word counts.

public class CountOccurrenceOfWords {
    public static void main(String[] args) {
        // Set text in a string
        String text = "Good morning. Have a good class. " +
                      "Have a good visit. Have fun!";

        // Create a TreeMap to hold words as keys and counts as values
        Map<String, Integer> map = new TreeMap<>();

        String[] words = text.split("[ \n\t\r.,;:!?()]+");
        for (int i = 0; i < words.length; i++) {
            String key = words[i].toLowerCase();
            if (key.length() > 0) {
                if (!map.containsKey(key)) {
                    map.put(key, 1);
                } else {
                    map.put(key, map.get(key) + 1);
                }
            }
        }

        // Get key and value from each entry
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + "\t" + entry.getValue());
        }
        System.out.println();

        // Display key and value for each entry -- shorter way that uses a stream
        // map.forEach((k, v) -> System.out.println(k + "\t" + v));
    }
}

Class: ComputeFibonacci

This class calculates the Fibonacci number at a user-specified index using a recursive method.

public class ComputeFibonacci {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter an index for a Fibonacci number: ");
        int index = input.nextInt();
        input.close();

        // Find and display the Fibonacci number
        System.out.println("The Fibonacci number at index " + index + " is " + fib(index));
    }

    /** The method for finding the Fibonacci number */
    public static long fib(long index) {
        if (index == 0) { // Base case
            return 0;
        } else if (index == 1) { // Base case
            return 1;
        } else { // Reduction and recursive calls
            return fib(index - 1) + fib(index - 2);
        }
    }
}

Class: TestStackQueue

This class tests basic operations on generic Stack (LIFO) and Queue (FIFO) implementations.

public class TestStackQueue {
    public static void main(String[] args) {
        // Create a stack
        GenericStack<String> stack = new GenericStack<>();

        // Add elements to the stack
        stack.push("Tom"); // Push it to the stack
        System.out.println("(1) " + stack);

        stack.push("Susan"); // Push it to the stack
        System.out.println("(2) " + stack);

        stack.push("Kim"); // Push it to the stack
        stack.push("Michael"); // Push it to the stack
        System.out.println("(3) " + stack);

        // Remove elements from the stack (LIFO)
        System.out.println("(4) " + stack.pop());
        System.out.println("(5) " + stack.pop());
        System.out.println("(6) " + stack);

        // Create a queue
        GenericQueue<String> queue = new GenericQueue<>();

        // Add elements to the queue
        queue.enqueue("Tom"); // Add it to the queue
        System.out.println("(7) " + queue);

        queue.enqueue("Susan"); // Add it to the queue
        System.out.println("(8) " + queue);

        queue.enqueue("Kim"); // Add it to the queue
        queue.enqueue("Michael"); // Add it to the queue
        System.out.println("(9) " + queue);

        // Remove elements from the queue (FIFO)
        System.out.println("(10) " + queue.dequeue());
        System.out.println("(11) " + queue.dequeue());
        System.out.println("(12) " + queue);
    }
}

Related entries: