CS 124, Fall 2011
Lab 6: Eclipse (and Subroutines)

The main point of this lab is to introduce you to the Eclipse IDE. There is also a short programming project that uses subroutines. At the end of the lab, you will find the second Longer Programming Project.

During the lab, you will create a project folder named "lab6." You should copy the folder from your Eclipse workspace into your homework folder by the start of next week's lab. The project should contain the very short first program that you will create in Eclipse, and it should contain the program that you write for the programming exercise.


Running Eclipse

Eclipse is an "Integrated Development Environment" (IDE) for Java programming, as well as for programming in other languages. It is one of the most popular professional development environments. It is already installed on our Linux computers. You can install it on your own computer, too, if you want. Eclipse is itself written in Java, and your computer needs Java to run it. (It does not need a Java compiler, since it includes its own compiler, but it does need the Java "runtime", which is used to run Java programs.)

If you want to use it on your own computer, you can download it from eclipse.org. There are several versions of Eclipse; you want to get the "Eclipse IDE for Java Developers." Note that you have to choose between a "64-bit" and a "32-bit" version of the program, which corresponds to whether you are running a 64-bit or a 32-bit version of your operating system. If you don't know which you need, ask for help.


To use Eclipse in the lab, select "Applications" / "Programming" / "Eclipse" from the Gnome menus. The first time you use Eclipse, it asks you to select a "workspace". This is where Eclipse will store your programming project. By default, the name of the workspace will be a directory named "workspace" in your home directory. You should probably use a different name, such as "workspace-cs124," or store the workspace in your cs124 directory. There is a box that you can check if you don't want to be asked to select a workspace each time you run Eclipse.

Eclipse organizes your programming projects into "workspaces." Each workspace corresponds to a directory. These workspace directories hold all the files that are used by your projects, including Java source code files and compiled class files. Usually, you should let Eclipse have complete control over the workspace directories, and you should not directly change any files that are stored in them. It is possible to have as many workspaces as you want, but for this course, you will keep all of your projects in a single workspace. You might want to create more workspaces in the future, to use for other courses.

The first time that you run Eclipse, its window will be filled with a "Welcome" screen. The icons on this screen link to a large amount of information about Eclipse. You can browse through this information some time, if you like, but for now, just close the "Welcome" screen by clicking the "X" next to the word "Welcome" near the top-right corner of the window. If you want to get back to the "Welcome" screen, just select "Welcome" from the "Help" menu.

Eclipse uses the terms view and perspective to describe the way that information is organized and presented in its window. The window typically contains several views. Each view contains a certain type of information. All the views that are visible in the window constitute a perspective. A perspective is meant to contain all the views that are used in some particular activity. For now, you will just use the Java perspective, which is used for Java programming. Later, you might use the Debug perspective, which is for debugging programs. Each perspective is highly customizable. You can add and delete views and move them around. If you ever delete a view accidently, you can get it back by selecting it from the "Show View" submenu in the "Window" menu.

After you have closed the Welcome screen, the window will show the Java perspective. Initially, all the views are empty. Here is what the Java perspective might look like after a little work has been done:

Eclipse Window showing Java Perspective

In this window, I have closed a couple of the views that I don't use, the the "Outline" view and the "Hierarchy" view. Remember that a view can be closed by clicking the small "X" next to the name of the view, and it can be reopened using the "Window/Show View" menu.

The Package Explorer view, on the left, is central to much of the work that you do in Eclipse. It contains a list of your programming projects and the Java files and resources that are contained in those projects. In the above picture, there is just one project, lab6. Clicking on the small triangle next to the project name will show/hide the resources contained in the project. The main thing in the project is the src folder, which holds Java source code files. Use the triangle next to "src" to show/hide the list of files.

The lower right section of the window contains several views. Currently, the "Problems" view is showing. It contains a list of errors and warnings from the Java compiler (but only those in files that have been saved). To see one of the other views, such as "Console" or "Javadoc", just click on the tab that contains the name of the view. Sometimes, another view will pop up automatically in this area to show the output of some command. When you run a program, standard input and output are done in the "Console" view.

The central area of the window is occupied by editor views. Here, I've opened two Java files, GreetUser.java and TextIO.java, for editing. Currently, GreetUser.java is showing; to see TextIO.java instead, click its name.

The view of GreetUser.java shows several of the nifty features of the Java editor. The source code that you type is checked for syntax errors as you type. Errors are marked with small red carets at the bottom of the line, like the one at the end of the first line in the main() routine. The error is also marked by a red rectangle in the right margin of the editor and sometimes by a marker in the left margin; if you hover your mouse over either of these, you see an error message for the error. In this case, you are told that a semicolon is missing. In the third line of main(), the word "prinltn" is underlined with error markers. (It's a misspelling of "println".) This second error has an error light bulb () in the left margin of the editor. The light bulb means that Eclipse is not just telling you about the error but is offering you some ideas for fixing it. If you hover the mouse over the error, prinltn, a list of possible fixes comes up. In this case, the list is

change to println(), and other options

Clicking on an action, such as "Change to println()", will apply that action automatically. Sometimes, you will see a warning light bulb () instead of an error light bulb. A warning indicates a potential problem, but not an error. Warnings will not prevent the source code from being compiled successfully.

In fact, Eclipse might be a little too enthusiastic in marking warnings and errors. You do not necessarily have to fix every warning. And you certainly do not have to fix every error as soon as it appears! In fact, it's impossible to do so, and in some cases the error will go away by itself after you've typed in more of your program. And remember that the fix for a programming error does not always go at the location of the error; sometimes the problem is elsewhere in the file. Furthermore, Eclipse's error system is only effective if you routinely get most of your program correct in the first place -- don't expect Eclipse to make solid Java programming skills unnecessary!

Note by the way that the misspelled word helllo is also underlined with error markers in the window. Eclipse will spell-check your comments! Hover the mouse over the misspelled word to get a list of possible corrections. To select one of the corrections, click on it.


Your First Project

It's time for you to start using Eclipse. Start up Eclipse, as described above. Close the "Welcome" screen (and maybe the "Outline" view as well).

To create your first project, select "File" / "New" / "Java Project" from the menus at the top of the Eclipse window (or right-click in the "Project Explorer" view and use the pop-up menu). A "Create Java Project" wizard will pop up. All you have to do is enter a name for the project, in the box labeled "Project Name". Enter lab6. The project name will be used as the name of a directory inside your workspace directory. After entering the project name, click the "Finish" button. The project will be added to "Project Explorer", and a directory of the same name will be created in your Eclipse workspace directory.

Now, you need to create a new Java class file in your project. To do this, right-click the project name in the "Package Explorer" view. In the pop-up menu, go to the "New" submenu again, and select "Class". A class creation dialog box will pop up. If you got to the dialog box, as instructed, by right-clicking the project name, the "Source Folder" box in the dialog is already filled in with "lab6/src." (Otherwise, you might have to fill in this box by hand.)

Now, you just have to fill in the name of the class, and click the "Finish" button. Note that you have to enter the name of the class, not the name of the file, so don't try to add a ".java" extension to the name. The name must be a valid Java class name. Use "GreetUser" (or any name you like). The class will be added to the src folder in the "Package Explorer" view, and the Java file will be created in the project directory. Furthermore, a Java editor will open, showing you the initial contents of the file. As you can see, Eclipse has already added the declaration of the class. All you have to do is fill it in! Note that you can close the editor in the usual way, by clicking the X next to the file name; to open the file again, double-click its name in the "Project Explorer."

As you can see in the "Package Explorer," the class is added to the "default package." This just means that the class is not declared to belong to any package. Eventually, you will have to work with packages, but for now the default package is OK, even though the Eclipse class creation dialog will display a warning that "use of the default package is discouraged."

Eclipse often has alternative ways of doing things. An easier way to create projects and classes is to use the "create" buttons in the toolbar. These are a group of three small buttons at the top of the Eclipse window:

buttons for creating projects, packages,  and classes

Click on the left button in this group to create a new Java project. Click the right button to create a new class. The middle button is for creating packages. (Note that when you create a class using the button, you should first click in the Package Explorer to select the location of the class that you are creating. Otherwise, you'll have to enter the location by hand in the class creation dialog box.)

Now, to create and run a program. Add a simple main() routine to the class that you created above, containing nothing but an output statement, such as

    public static void main(String[] args) {
        System.out.println("Hello World");
    }

Programs in Eclipse are compiled automatically. All you have to do is run them! To run your program, right-click either on the name of the class in the "Project Explorer" or in the editor window that contains the program. In the pop-up menu, go to the "Run As" submenu, and select "Java Application" from the submenu. The program will start. The output from the print statement appears in the "Console" view in the bottom right area of the Eclipse window.

You can also run a program simply by clicking on the "Run" button (run button) in the toolbar. Before clicking the Run button, click in the window containing the program that you want to run, or click the name of the file in the "Project Explorer," so that Eclipse will know which program you want to run. (Note that if you click the little black triangle to the right of the Run button, you'll get a list of all the programs that you have run, and you can select that program that you want to run from this list.

When you run your program, the output from the program appears in the "Console" view at the bottom of the Eclipse window. When your program does input, you will have to type your input into the "Console" view. (This can be a little annoying, since you have to remember to click in the "Console" before typing there.)


Next, you should use TextIO in your project. Since TextIO is not a standard class, you have to add TextIO.java to your project. To do this, open a file browser window and locate TextIO.java. Right-click the file icon and select "Copy". Now, in the "Project Explorer" in the Eclipse window, right-click the src folder where you want to include TextIO.java, and select "Paste". TextIO.java will be added to the folder, and be ready to use in your project.

Add an input statement to your program (for example to ask the user's name), and use the user's response in the output. Run the program, and see how input works with the "Console."


You have surely already noticed that the Java editor in Eclipse does a certain amount of work for you. It automatically inserts indentation. When you type a "{" and press return, the matching "}" is inserted in the correct position. Furthermore, when you type a period, a list of things that can follow the period will pop up after a short delay, and you can select an item from the list instead of typing it in. This is called Content Assist. You can invoke Content Assist at any time while you are typing by pressing Control-Space. If you do this in the middle of a variable name or subroutine name, pressing Control-Space will either complete the name or offer a list of possible completions. It can be used in other ways as well. For example, if you press Control-Space after typing the "(" at the beginning of a subroutine's parameter list, you will get information about the parameters of the subroutine. By the way, when Content Assist pops up a list, you can get rid of the list by pressing the Escape key.

Content Assist is a good thing, but I find the way it pops up automatically while I am typing to be very annoying. You can turn off this feature in the Eclipse Preferences. Select the "Preferences" command from the "Window" menu. In the Preferences dialog box, click the little triangle next to "Java" to open the list of Java preferences (if necessary), then click the triangle next to "Editor", and finally click "Content Assist." In the Content Assist preferences, uncheck the box labeled "Enable Auto Activation" and click "OK".

Eclipse has a huge number of preference settings that can be used to customize the environment. Most of the default settings are OK, but there are a few that I usually change. If you want to do the same: Under "Java / Editor / Mark Occurrences", turn off "Keep marks when the selection changes". Under "Java / Compiler / Errors/Warnings / Potential Programming Problems", change "Serializable class without serialVersionUID" from Warning to Ignore, and change "Empty Statement from Ignore to Warning.)


Eclipse has a lot of other useful features. We will encounter more of them as time goes on, and you can undoubtedly discover a few new ones on your own. But here are a few of the most useful:


Programming Exercise

For this lab's real programming exercise, you will write a few subroutines and a main() routine that uses them. To begin, create a new Java class in your lab6 project in Eclipse. Name the class "Palindrome."

The program will test strings entered by the user to determine whether they are palindromes. A palindrome is a string that reads the same backwards and forwards, such as "mom", "radar", "racecar", and "able was I ere I saw elba". It is customary to ignore spaces, punctuation, and capitalization when looking for palindromes. For example, "A man, a plan, a canal. Panama!" is considered to be a palindrome.

To determine whether a string is a palindrome, you can: (1) convert the string to lower case; (2) remove any non-letter characters from the string; and (3) compare the resulting string with the reverse of the same string. If they are equal, then the original string is considered to be a palindrome.

In class, we saw how to compute the reverse of str:

String reverse;
int i;
reverse = "";
for (i = str.length() - 1; i >= 0; i--) {
   reverse = reverse + str.charAt(i);
}

Write a static subroutine that finds the reverse of a string. The subroutine should have one parameter of type String and a return value of type String. Use the above code, and add a return statement.

Now write a second subroutine that takes a String as a parameter and returns a String. This subroutine should make a new string that is a copy of the parameter string, except that all the non-letters have been omitted. The new string should be returned as the value of the subroutine. You can tell that a character, ch is a lower-case letter by testing if (ch >= 'a' && ch <= 'z')

(Note that for the operation of converting str to lower case, you can simply use the built-in toLowerCase subroutine by saying: str = str.toLowerCase();)

Finally, write a main() routine that will read in a string from the user and determine whether or not it is a palindrome. The program should print the string converted to lower case and stripped of any non-letter characters. Then it should print the reverse string. Finally, it should say whether the string is a palindrome. (Use the two subroutines to process the user's string.) For example, if the user's input is "Hello World!", then the output might be:

         stripped:  helloworld
         reversed:  dlrowolleh
         This is NOT a palindrome.

and if the input is "Campus motto: Bottoms up, Mac!", the output might be:

        stripped:  campusmottobottomsupmac
        reversed:  campusmottobottomsupmac
        This IS a palindrome.

Don't forget to add a comment before the start of the program and before the definition of each subroutine! The comment on a subroutine should explain the purpose of the subroutine, and it should make clear the meaning of any parameters and return value.

To turn in your project, go to your Eclipse workspace directory. It will contain a directory named lab6. Copy that lab6 directory into your homework directory in /classes/cs124/homework, as usual.


Longer Project Number 2

Here is the second of the longer programming projects for this course. This one is due in two weeks, on Friday, October 21, by 2:00 PM. You should start a new Eclipse project named proj2 to work in, and you should put your files in that project. Place a copy of TextIO.java in the project. Here is the project:

For the second project, you are going to work with codes. That is, you are going to take strings and encode them so that they can only be read by someone who knows the secret "key" that you used to do the encoding (or by someone who is able to "break" the code).

A very simple example of coding is given in the sample program SimpleCode.java. This program uses a "Caesar Cipher" in which the key is just a single integer in the range 1 to 25. (It is very easy to break, since there are only 25 possible keys to try!) In this code, each letter in a string is moved forward in the alphabet by the key amount; if this moves the letter past the end of the alphabet, then wrap around to the beginning of the alphabet. For example, if the key is 3, then 'a' is changed to 'd' and 'y' is changed to 'b'. A string can be decoded using the same algorithm with a different key, namely by moving each letter forwards in the alphabet by the offset (26–key), with wrap-around as appropriate. In the program, a subroutine is used to encode individual letters. For convenience, all letters are converted to lower case. (Traditionally, all spaces and punctuation would also be removed from the string, but in this program I simply copy them unchanged into the coded string.) You can try running the program. A compiled copy can be found in /classes/cs124.

You are going to implement a more complex type of code in which the key is an entire word or phrase. Furthermore, your program will be able to encode and decode entire files of text and not just single lines.

You should recall that TextIO can read textual data from files and can write to files. The command TextIO.readUserSelectedFile() will pop up a file chooser dialog box where the user can select a file. TextIO will then read from that file instead of from the user's input. You can go back to reading the user's input by saying TextIO.readStandardInput(). The commands TextIO.writeUserSelectedFile() and TextIO.writeStandardOutput() work in the same way for output. For this program, you will read from an input file selected by the user, encode what you read, and write the result to an output file selected by the user.

You should write a subroutine that does the job of reading, encoding, and writing. And you should write another subroutine that will read, decode, and write the result. These subroutines should have a parameter of type String that specifies the key for he cipher. You will also use a couple of subroutines that can be copied from other sources: the encode() subroutine from SimpleCode.java and the subroutine that you wrote for this lab's programming exercise for stripping punctuation from a string.


Here's what your program should do: When the program is run, it should first ask the user to input a key, which will be a string of text. It should then ask whether the user wants to encode or decode a file. It should prompt the user to select an input file and an output file. Then it should call the appropriate subroutine to either encode or decode the input.

And here is how the coding and decoding will work: When the user enters a key, it can be any line of text. However, the program must convert the key to lower case and strip out everything except letters. The result is a key that consists of lower case letters only. (The longer this string, the harder it will be to break the code.)

When a file of "plaintext" is to be encoded using the key, proceed as follows to compute the encoded "ciphertext." Read characters one at a time, using TextIO.getAnyChar(). Keep a count of how many characters you have read; say charCount is the number of characters read. To encode or decode character number charCount, you need to use one character from the key string. The character that you should use is

       ch = key.charAt( charCount % key.length() );

Convert this character into an integer in the range 0 to 25 by computing

      offset = (int)ch - (int)'a';

This gives you the offset value to use in an encoding operation. If you are decoding, simply use (26–offset) instead.

When you read a character from the input, if the character is a letter, convert it to lower case, encode it, and write the encoded character to the output using TextIO.put(ch). If the character is not a letter, just copy it unchanged to the output. You can tell when you reach the end of the input by using TextIO.eof(). This is a function that returns a boolean value. The return value is true if the end of the file has been reached and is false is there is still some data in the file.


David Eck, for CPSC 225