CS101 Lab No. 2 - Using Java Fall 2010/2011
Total Page:16
File Type:pdf, Size:1020Kb
CS101 Lab no. 2 - Using Java Fall 2010/2011
This lab assignment aims to familiarize you with the process of creating Java programs. Having designed a program, you must enter the source code into a file using an editor, then compile and build it. If the compiler reports (syntax) errors you must return to the editor, find and correct them. Once the program compiles correctly you can run/execute and test it. If you did the design properly then there shouldn’t be any problems, but if there are, you must again return to the (design and then the) editor, correct them, and recompile and execute the program again, and so on until it does work correctly. To manage this process we will be using an integrated development environment (IDE), a program that combines facilities for creating, editing, compiling and testing Java programs in a quick and efficient manner. There are many IDE’s available, but we will concentrate on using one called JCreator. Once you become a little more proficient, you may like to look at some of the others, for example, NetBeans, Eclipse, JBuilder, BlueJ, etc. When you have time, you should also look at how to use Java without an IDE –see the optional assignment on the CS101 “Bits ’n Pieces” web page. For now, carefully read and follow the steps below in sequence…
Starting JCreator Java programs often consist of several files, including the main source code, source code for any additional classes, web pages and, of course, the executable class files themselves. JCreator groups these related files together into what it calls a “project.” It also allows you to group several projects into a “workspace” (only one project being active at any one time.) It is a good idea to let JCreator create the basic workspace & project for you. This is less error-prone and much quicker than doing it yourself since JCreator not only helps you keep your files in order, it can even create some of the program code for you! On your H: drive you should already have a \private\cs101 folder containing folders for lab02, lab03, lab04, lab05, lab06, lab07, lab08, lab09, lab10, lab11, lab 12 & Lab13. If not, please do so now (see web for instructions to set up your h: drive.) Now, from the Windows START menu run JCreator (enter JCreator to the Start Search box if you are not sure where it is). When you run JCreator for the very first time only, it may require special setup. Follow the instructions on the webpage now!
Your First Java Program Begin by creating an empty workspace. Select File|New|Blank_Workspace. Change the location to h:\private\cs101\lab02 and enter Lab2 for the workspace name. To start a new project in your workspace, select File|New|Project and on the projects tab select “CS101 Console Application”. Click Next, then enter a name for your project. Since this is the first part of lab 2 let’s call it Lab02a. Make sure the “AddToCurrentProject” option is selected and click Finish. Note: Clicking Next allows you to set various other options but these should already be set correctly so we will simply accept the defaults values for now. After the project is built, press Finish. Note: There should be a narrow area on the left of the screen that includes a part called FileView. It should show a workspace named Lab02 and in it your new Lab02a project containing a folder called src in which is a file called Lab02a.java. If you do not see such a window, select View|FileView. Double click on the Lab02a.java or the icon next to it. Another window containing the source code of the program will open and allow you to make changes to your program as necessary. Look at the code. Can you predict what it will do? To actually see the program in action you must compile (build) it and then execute it. To do this, first select Build| BuildProject. You should see a message saying “Process Completed” in the BuildOutput window at the bottom of the screen. Next select Run|RunProject to actually run the program. Yet another window will open. This window (which has a black background) is the Java console and displays the output of your program. You should see a line saying “Start of Lab02a“, another saying “End of Lab02a” and another saying “Press any key to continue…”. Close the console by pressing any key. Congratulations, you have now completed your first Java program (with a little help!)
Organising & Saving your work If you wish to save your work simply select File|SaveAll in the edit window. When typing in a long program, it is a particularly good idea to save your work every so often, just in case something goes wrong (you don’t want to have to type it all in again!) Note: JCreator may be set up to automatically save your program whenever you compile or execute it. It is also advisable to keep a backup copy of your work on another disk, just in case! Use Windows Explorer to copy the entire folder containing your workspace/projects to your USB flash drive. While doing this take a look at the files comprising your project. The one called Lab02a.class (in the sub-folder called classes) is the–executable–Java bytecode corresponding to your Lab02a.java program. The other files contain information used by JCreator to keep track of your project (don’t mess with them!) Correcting Syntax Errors In the edit window, remove the semicolon from the end of the line that begins with the “System.out.” and again compile (Build|BuildProject) the program. This time it will not compile correctly because of the syntax error you just introduced. The window at the bottom of the screen should switch to show the TaskView. In it you should see a message next to a red cross (indicating an error) that says “';' expected”. Error messages are not always as clear as this one, so you sometimes have to be a bit of a detective to find the real source of the problem. Before going on to correct the error, switch from the TaskView to the BuildOutput view again and look at the messages there. You should see a line containing something like “H:\private\cs101\lab02\scr\Lab02a.java:xx:: ';' expected”. This is the output direct from the Java compiler. The “xx” in the error message actually indicates the line number on which the syntax error was detected. To correct an error you must return to the editor window and locate the problem. JCreator can help you find this point quickly. Simply double click on the line containing the error message (in either the BuildOutput or TaskView views) and the cursor will move to the beginning of the problem line, marking it with a red triangle on the left of the editor window. Go ahead and correct the problem, then try recompiling again. Try introducing other errors and see what messages you get (e.g. try removing one of the quotation marks, or changing println to Println, and main to man.) Just for fun, see if you can modify the program so that it outputs a personalized greeting message.
Online Help As with most Windows program, JCreator provides extensive online help so you can find out about the many other useful features of the program from there. You can also get help on the Java language and packages themselves by selecting the JDK-Help option from the Help menu. Note: Pressing Ctrl-F1 when the cursor is on a Java keyword should bring up the relevant documentation automatically. Exiting JCreator To finish using JCreator simply select the File|Exit menu option. If you have not already saved your work you will be prompted to do so before the program terminates.
Continuing work on an existing program If, after exiting JCreator, you wish to continue work on your project simply open JCreator (from the Start menu) again and select File|OpenWorkspace. Navigate to the desired directory (H:\private\cs101\…) and select the .jcw file. You can close the workspace without exiting JCreator by selecting File|CloseWorkspace. Applets Anyone? Java programs actually come in several flavours including: simple text-based console applications (like the one you created above), applets (restricted graphics-based programs designed to run in a web page) and standalone graphics-based applications (like normal Windows programs.) To create an applet, start JCreator again and open your Lab02 workspace. Start a new project as before, but this time select the “Basic Java Applet” icon and name the project Lab02b. Compile and execute the project. This time a small white window will also appear containing the words “Welcome to Java”. This window, known as the applet viewer, shows the graphical output of your applet (text-based output can also be sent to the Java console, if desired.) Try editing the applet source code to display a personal message and even, perhaps, draw a rectangle around it. You can also view the applet in a normal web browser using the webpage (htm) document that is automatically created by JCreator. To do this first open a web browser (such as Internet Explorer or FireFox) and then select File|Open. A file open dialog box will pop up. Now write the full path and file name of the htm document in the edit box. (i.e. H:/private/cs101/lab02/Lab02b/classes/Lab02b.htm) or browse to it, then click the OK button. You should now see your applet in the browser Note: Your web browser must be Java-enabled for this to work! It is possible to configure JCreator to automatically run the applet in your browser rather than the applet viewer; see the online help. Some Points to Note Be extremely careful when entering your programs. Java is case-sensitive, which means that a word typed with any uppercase letters is different from one typed with the same lowercase letters. If you mix them up, the Java compiler may give a syntax error! On the other hand, Java ignores blank lines and space characters (except in the middle of identifiers and string literals!) This allows you to layout your program so that it is easier to read. Blank lines can thus be used to separate sections, with sub-sections being indented progressively to the right. JCreator helps you keep things straight when entering your program code, by automatically indenting a new line the same amount as the preceding one. When you type an opening curly bracket (brace), the editor also adds a closing one at the correct indentation. Pressing Enter after the brace automatically increases the indentation (as required by CS101/2 Style Guidelines) so you have no excuse for badly laid out, and hence difficult to read, programs! Depending on the setup, JCreator may not automatically re-compile your programs after you change (edit) them. If you execute a project without re-compiling it, it will run the old (unchanged) version of your program. You have been warned! Don’t forget to complete the header comment in every program you write. In particular, make sure your name and a brief description of the assignment is added to the items automatically written by JCreator’s template. And Finally… When you have completed the preceding steps, demonstrate your ability to create, debug and run a Java program, to the lab assistant. That’s all folks. You are now well on your way to becoming professional programmers, only another four years and a few hundred thousand lines of code to go! Have fun. Oh, and don’t forget to… (logoff !)