Trying to learn how to use the popular Eclipse IDE? Trying to do all three at once? Me too. Hopefully, this tutorial will help both of us. I’m using Eclipse 3.5.2, so you may have to adapt to changes in the GUI if your version is different than mine.

Example Java Class

Let’s start out with a class I wrote that represents an alphabetized String Array. It is a good example of how to use an Array as a data buffer, and it also demonstrates how to read and write files (one method, anyway).

import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;

/**
 * This class represents a sorted list of Strings.
 * 
 * @author GreeenGuru (greeenguru@greeennotebook.com)
 * @version 1.0
 */
public class SortedStringList {
    /** The maximum length of the stringList_ */
    private static final int MAX_SIZE = 100;
    /** The list of strings */
    private String[] stringList_ = new String[MAX_SIZE];
    /** Keeps track of next available index in stringList_ */
    private int size_ = 0;

    /**
     * Constructor that initializes stringList_ from data stored in a text file,
     * sorted alphabetically
     * 
     * @param input
     *            Name of text file containing string data.
     */
    public SortedStringList(String input) {
        try {
            Scanner scan = new Scanner(new File(input));
            // Skip the heading line
            if (scan.hasNextLine()) {
                scan.nextLine();
            }
            while (scan.hasNextLine() && size_ < MAX_SIZE) {
                stringList_[size_++] = scan.nextLine();
            }
            scan.close();
        } catch (Exception e) {
            System.out.printf("Unable to read from input file: %s\n\nThe "
                    + "error encountered was:\n\n%s\n", input, e);
            System.exit(1);
        }
        // Sort the array using exchange sort
        String temp;
        for (int i = 0; i < size_ - 1; i++) {
            for (int j = i + 1; j < size_; j++) {
                if (stringList_[i].compareToIgnoreCase(stringList_[j]) > 0) {
                    temp = stringList_[i];
                    stringList_[i] = stringList_[j];
                    stringList_[j] = temp;
                }
            }
        }
    }

    /**
     * Default Constructor
     */
    public SortedStringList() {
        // Nothing to do here.
    }

    /**
     * Getter for list size.
     * 
     * @return The number of strings in the list.
     */
    public int getSize() {
        return size_;
    }

    /**
     * Adds a new string to the list.
     * 
     * @param newString
     *            The string to be added
     */
    public void add(String newString) {
        if (newString.equals("") || newString.equals(null) || size_ >= MAX_SIZE) {
            // If input is invalid or the array is maxed out
            System.out.println("The list is full or the string is invalid.");
            return;
        }
        int index = 0;
        // Find the right position for the new string
        for (int i = 0; i < size_; i++) {
            if (stringList_[i].compareToIgnoreCase(newString) < 0) {
                index++;
            } else {
                break;
            }
        }
        // Shift remaining strings to the right
        for (int i = size_; i > index; i--) {
            stringList_[i] = stringList_[i - 1];
        }
        size_++;
        // Add the new string
        stringList_[index] = newString;
    }

    /**
     * Removes the string at the given index.
     * 
     * @param index
     *            The index of the string to be removed.
     */
    public void remove(int index) {
        // If the index is invalid, do nothing
        if (index < 0 || index >= size_) {
            System.out.println("There is no string at the given index.");
            return;
        }
        // Shift the rest of the strings to the left
        for (int i = index; i < size_ - 1; i++) {
            stringList_[i] = stringList_[i + 1];
        }
        stringList_[size_ - 1] = null;
        size_--;
    }

    /**
     * Removes the string given.
     * 
     * @param string
     *            The string to be removed.
     */
    public void remove(String string) {
        int index = this.getIndexOf(string);
        // If the string is not found, do nothing
        if (index == -1) {
            return;
        }
        // Now that we know where the string is, call the other remove method
        this.remove(index);
    }

    /**
     * Returns the string at the given index.
     * 
     * @param index
     *            The index queried
     * @return The string stored at the queried index.
     */
    public String getStringAt(int index) {
        return stringList_[index];
    }

    /**
     * Get the index of the string in question or -1 if the string is not found.
     * 
     * @param string
     *            The string queried.
     * @return The index of the queried string or -1 if the string is not found.
     */
    public int getIndexOf(String string) {
        boolean stringFound = false;
        int index = 0;
        for (int i = 0; i < size_; i++) {
            if (stringList_[i].equals(string)) {
                stringFound = true;
                index = i;
            }
        }
        if (stringFound == false) {
            // If the string is not found, do nothing
            System.out.println("There is no such string in the list.");
            return -1;
        }
        return index;
    }

    /**
     * Prints the list to the screen.
     */
    public void print() {
        for (int i = 0; i < size_; i++) {
            System.out.println(stringList_[i]);
        }
    }

    /**
     * Writes the list to a file.
     * 
     * @param input
     *            The name of the file to be created
     */
    public void printToFile(String input) {
        try {
            FileWriter fw = new FileWriter(new File(input));
            PrintWriter pw = new PrintWriter(fw);
            for (int i = 0; i < size_; i++) {
                pw.print(stringList_[i] + "\n");
            }
            pw.close();
            fw.close();
        } catch (Exception e) {
            System.out.printf("Unable to write to file.  The "
                    + "error encountered was:\n\n%s\n", e);
            System.exit(1);
        }
    }

    public static void main(String[] args) {
        SortedStringList list = new SortedStringList();
        list.add("Zulu");
        list.add("2010");
        list.add("juliet");
        list.add("09");
        list.add("FOXTROT");
        list.add("27");
        list.add("alpha");
        list.add("Delta");
        list.add("papa");
        list.print();
        list.remove("FOXTROT");
        System.out.printf(
                "\nAfter removing \"FOXTROT\", the list now contains %d strings:\n\n",
                list.getSize());
        list.print();
    }
}

I’m going to assume here that you know how to create a new project in Eclipse (named whatever you want), create a new class called SortedStringList, and insert the code above to complete the class. If you haven’t learned Eclipse enough to do that, I suggest reading another Eclipse tutorial first. Specifically, I’d recommend the built-in Eclipse tutorial available from the Help menu. Go to Help → Cheat Sheets…, open the Java Development folder, and select Create a Hello World application. This will open a short tutorial as a handy side pane. If you need more guidance than that, look around under Help → Help Contents and you should be able to find anything you need to know.

You may have noticed that I’ve included a main method in my code that calls some of the methods in my class. I like to do that as a quick functional test. It gives me some instant feedback, telling me whether or not my class works at all. Of course, this small functional test does not test all my methods, nor does it tell me how they will respond to marginal or invalid parameters. A better technique is to write unit tests for each method before you even start coding the method. When you’re finished coding, all you have to do is run the test and you’ll receive instant feedback telling you whether or not your method works. That is why we’re learning how to use JUnit, which can do just that. Until then, however, let’s run the functional test. Make sure you have our new class selected in Eclipse and click on the green Run button.

This tells us that the class is keeping the String Array sorted alphabetically even after adding strings in the wrong order and removing one from the middle. Great! By the way, we could have also run this from the terminal. First, we have to know where our Elipse workspace is located. From there, we need to navigate to the project directory we created and then to the src folder to find SortedStringList.java. If you can’t find it, just go to File → Properties and Eclipse will show you the location of the file. For our sake, let’s say the path to SortedStringList.java is path/SortedStringList.java. If you’re using Windows, the commands will be the same but the prompts will look different (obviously).

 

Leave a Reply

Your email address will not be published. Required fields are marked *