CPSC 225, Spring 2011
Lab 1: Introduction to Eclipse (and First Assignment)


This lab introduces you to programming with the Eclipse IDE (Integrated Development Environment). Eclipse is used by the majority of professional Java programmers. As an IDE, it is a unified environment for editing, running, and debugging Java programs. In fact, it is really much more, since plug-ins are available that add support for many other programming languages. Eclipse is a very large and complex system, and it is very likely that you will only ever use a small subset of its features. Fortunately, it is possible to be productive in Eclipse even if you are familiar with only some of the things that it can do.


Programming Exercise: Random Math Quiz

To get you started with Eclipse and to help you get back into programming at the start of a new semester, this lab includes a moderately complex programming assignment. The assignment is due next Thursday, at the beginning of the next lab. Remember that your program will be graded for style as well as for correctness. It should follow all the rules in the style guide that was handed out on the first day of class, including the use of Javadoc comments (see below).

The assignment is to write a program that administers and grades a math quiz with randomly generated questions of several different kinds. You should target the quiz at an elementary school student who is learning basic arithmetic. The questions should ask the student to perform simple addition, subtraction, multiplication, and division problems. You can include other problems, such as finding remainders, if you want. You should probably stick to integers with a small number of digits.

For each question, the type of problem should be selected at random, and then the numbers that occur in the problem should be randomly generated. (Hint: To get a reasonable division problem, a/b, with no remainder, select b and the answer at random, and compute the value of a.)

The user should have two chances to get the right answer. If the user gets the correct answer to a problem on the first try, they get full credit for the problem. If not, they get a second try. If the user gets the correct answer on the second try, they get half credit. If the user fails to get the correct answer after two tries, tell the user the correct answer

The quiz consists of ten questions. At the end of the quiz, output a score along with the number of questions that the user got right on the fist try and the number of questions that the user got right on the second try.

You should try to write your program in a way that will make it easy to modify and improve. For example, you wouldn't want to hard code the number of questions as a literal constant in your program, would you? The preferred way to write the program is to define classes to represent the concepts that occur in the problem. You will create one such class (along with a main program) as part of your introduction to Eclipse. The program can be written using a single class to represent math questions or -- better -- with a general class to represent math questions and subclasses for specific kinds of questions. (You could even try to generalize the framework so that it can handle other types of questions besides math questions.) If you have problems with using classes, come in and get help before the assignment is due!

What to turn in and how to turn it in: To turn in your program, you should copy the program's project folder from your Eclipse workspace into the directory /classes/s11/cs225/homework/zz9999, where you should replace "zz9999" with your own user name. It is not necessary to turn in a printout of your work. If you have any problems doing this, ask for help at the beginning of lab next week.

Grading: A perfect program will get a grade of B+. (A perfect program should run correctly; should use classes appropriately; should provide a good user experience with reasonable math problems and nice, clear I/O; and should follow all the rules of good programming style.) For a grade of A, the program must also exhibit a good design that will make it easy to extend the program, for example to use a different number of questions, different types of questions, and possibly different scoring rules.


Running Eclipse

The most recent version of Eclipse is already installed on the Linux computers that you will use during the lab. You can access it in the "Programming" sub-menu of the application menu. You might want to add an "Eclipse" button to the panel at the top of the screen to make it easier to get to. To do that, simply drag the command from the application menu to the panel.


Although it is not required for the course, I encourage you to consider running Eclipse on your own computer as well. It is available for Linux, Windows, and Mac OS.

To run Eclipse, you must first have a Java JDK Version 5.0 or higher working on your computer (preferably version 6). If you do not already have it on your computer, you can download it. Windows users can get the JDK 6 from Oracles's Java download site,

http://www.oracle.com/technetwork/java/javase/downloads/index.html

Mac OS should already have come with a JDK. For Linux, the JDK should be included in your distribution's available software, or it can be downloaded from the above site. A link to installation instructions can be found on the same web page.

Once you have Java working, you can download the most recent version of Eclipse from the Eclipse downloads page, http://eclipse.org. You can download the "Eclipse IDE for Java Developers"; you won't need the much larger "Eclipse IDE for Java EE Developers."

If you would like some help installing Java or Eclipse on your computer, ask for it.


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 probably keep all of your projects in the same workspace. (In fact, you can keep all the programs that you ever write in one workspace, if you want.)

When Eclipse starts up for the first time, it asks you to select a workspace. (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.) By default, the name of the workspace will be "workspace", but I usually change it to "eclipse-workspace". If you expect to devote a workspace to CS225 only, you might name it "cs225_workspace".

The first time that you use a workspace, 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 organized for Java programming. Later, you will learn about 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. If you mess up a perspective completely, you can get back the original, default setup with the "Reset Perspective" command in the "Windows" 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 "Task List", "Outline", and "Hierarchy" views. 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, Assg1_Math_Quiz. Clicking on the small plus sign (or triangle) next to the project name will show/hide the resources contained in the project. In a new project, there will be a directory named src where the source files for the project will be stored.

The lower right section of the window contains several views. In the picture, the "Console" view is showing. To see one of the other views, such as "Problems" 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. Errors and warnings from the Java compiler are displayed in the "Problems" view.

The central area of the window is occupied by editor views. Here, I've created a Java file, MathQuiz.java, and have opened it for editing.

The view of MathQuiz.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. The error is also marked by a red rectangle in the right margin of the editor and sometimes by an icon in the left margin of the editor; if you hover your mouse over any error or error marker, you see an error message for the error. For the first error in the picture, for example, you would be 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 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 click the light bulb, you get a list of actions that can be taken to fix the problem. You will also see the list if you hover the mouse over the underlined error itself. For the above picture, the list is:

change to println(), and other options

Double clicking on an action, such as "Change to println()", will apply that option automatically. Sometimes, you will see a warning 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 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!

In fact, many of the fixes that Eclipse will offer will do things to your code that you won't understand. Not every fix is a good idea! Don't let Eclipse fix your code unless you understand what it wants to do and why!

Note that Eclipse will spell-check your comments. If you hover the mouse over a misspelled word, you will get a list of possible corrections.


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, right-click in the "Project Explorer". In the pop-up menu that appears, go to the "New" submenu, and select "Java Project." A "New Project" wizard will pop up. All you have to do is enter a name for the project, in the box labeled "Project Name". Enter "Math-Quiz", or "Lab1", or any other name that you like. (Warning: Don't use funny characters such as "&" or ":" in the name of the project, since they can cause problems when you work with the files outside Eclipse. The project name will be used as the name of a directory inside your workspace directory. Spaces are OK, but it's probably better to avoid spaces in directory names in general.) 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 the "New" submenu again, and select "Class". A class creation dialog box will pop up. Again, 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 "MathQuiz", or whatever you like. The class will be added to the src folder in your project, in the "default package." 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. 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. Later in the term, you will be working with packages, but for now the default package is OK, even though Eclipse will display a warning that "use of the default package is discouraged" when you create the class.

You will probably want to use the TextIO class in the Random Math Quiz project (although you can use some other class for user input if you know how to do that). To make TextIO available to your program, you have to add it to the project. To do this, find a copy of TextIO.java. You can download it, or, while you are logged into your Linux account, you can find it in the directory /classes/s11/cs225. The easiest way to get this file into your project is to copy-and-paste it from a directory window: Open a directory window for the directory that contains TextIO.java. Right-click its file icon and select "Copy" from the pop-up menu. Then right-click the src folder in your project, in Eclipse's "Project Explorer" and select "Paste" from the pop-up menu. TextIO should appear in the default package, inside src. (Note that you should not just copy TextIO.java into the Eclipse workspace directory.)

Eclipse often has alternative ways of doing things. Another 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 the following main() routine, or something similar, to the class that you created above:

     public static void main(String[] args) {
         System.out.print("What's your name?  );
         String name = TextIO.getln();
         System.out.println("Pleased to meet you, " + name);
     }

The program is compiled automatically. To run it, right-click either on the name of the class in the "Project Explorer" or on 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 first print statement appears in the "Console" view in the bottom right area of the Eclipse window. In order to type a response, you must first click the Console window! Type in your response and press return. The last line of the program will be executed, and the program will end.

After running the program once, you can run it again by clicking on the "Run" button (run button) in the toolbar. If you click the little black triangle to the right of the button, you'll get a list of all the programs that you have run; select a program from this list to run it.


Before starting serious work on the programming assignment, create one more test class. Create a class named AdditionProblem with the following definition:

      public class AdditionProblem {

          private int x,y,answer;

          public AdditionProblem() {
             x = (int)(10 + 40*Math.random());
             y = (int)(30 * Math.random());
             answer = x + y;
          }

          public String getProblem() {
             return "Compute the sum:  " + x + " + " + y;
          }

          public int getAnswer() {
             return answer;
          }

      }

Now, change the main() routine so that it creates an AdditionProblem, displays to the user the problem returned by the getProblem() method, reads an answer from the user, and checks to see whether the answer entered by the user agrees with the correct answer as returned by getAnswer(). (It's a good idea to complete this little exercise before you start working on the complete program, to make sure that you know how to use the class.)


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. [If this does not happen, it might be because of a misconfiguration in Eclipse; ask me how to fix it!] 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 method 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 method's parameter list, you will get information about the parameters of the method. 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 plus sign 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". It looks like this:

Eclipse Preferences Dialog

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 "Possible accidental boolean assignment", "'Switch' case fall-through" and "Null reference" 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:


Javadoc

Javadoc is a standard syntax for comments in Java source code. Javadoc was introduced in Section 4.5 of the CPSC 124 textbook, and you can read about it there. Javadoc comments can be processed to produce documentation of your code's API in the form of web pages. The API documentation for Java's standard classes was created with Javadoc.

Javadoc is thoroughly integrated into Eclipse. If you hilite the name of a class, method, or variable, its Javadoc documentation (if any) appears in the "Javadoc" view. If you just hover your mouse over a name, the Javadoc documentation appears in a pop-up window. When Content Assist shows a list of variable or method names, it will also show Javadoc documentation for items in the list. This makes it very worthwhile to use Javadoc comments in your code, even if you don't plan to generate web pages from the comments.

Furthermore, Eclipse will generate the outline of a Javadoc comment for you. To have it do this, just position the cursor on the line before a declaration, type /** (the first three characters of a Javadoc comment), and press return. An outline of the comment, including any appropriate Javadoc tags (such as @author, @param, @return, and @throws) will appear.

Some things to keep in mind: A Javadoc comment always comes before the declaration that is being commented. Any Javadoc tags, such as @param and @return, must come at the end of the comment, after any other text in the comment. Javadoc comments can contain HTML markup tags such as <p> or <b>...</b>. This means that you should not use the characters "&" or "<" in a Javadoc comment; Write them as "&amp;" or "&lt;" instead.

In this course, you are required to use Javadoc comments for any non-private classes, member variables, and methods that you write. This requirement starts now, with the Random Math Quiz programming assignment.


David Eck, for CPSC 225