Using Java in SFU Assignment Lab Tutorial

Last revised: 2002/09/16 by Russ Tront

Previous revisions by: Eddy Yip

Original taken and significantly adapted from tutorials by Tony Dixon, Russ Tront, and Mike Evans.

 

This tutorial teaches you the basics of using Java in the SFU Assignment Lab.  It includes a step-by-step guide of accessing and running a Java program along with two example Java programs. 

 

Table of Contents:

Using Java in SFU Assignment Lab Tutorial

A.    Getting Started In the Assignment Lab

B.     Create a Java Source File.

C.    Compile/Run Your Program Using Command Prompt

D.    Compile/Run Your Program Using Textpad

E.     Handling Java Error Messages

F.     Multi-file Programs

G.     Doing Your Assignments at Home

 

 

A.          Getting Started In the Assignment Lab

For those who intend to run this at home, please change directory and path names mentioned here to accommodate your own machine.  For more information on doing your work on your home computer, see the appendix section below titled “Doing Your Assignment at Home” and also any information from your instructor.

 

Before you enter anything into the computer, it is a good idea to develop a design and construct a draft of your source code on paper (unless you are going to just test one of the programs in your textbook). This will save you time at the workstation and may reduce the number of logical errors that occur as a consequence of failing to include something.   You can even use the Notepad text editor at home to enter a program into a file at home, before coming to the Assignment Lab.  Notepad is available in MS-Windows from the start menu:  Start>Programs>Accessories>Notepad.

Sign on to the ACS Assignment Lab PC, and provide a formatted 3.5” floppy disk in order to store your work between visits to the Assignment Lab.

B.           Create a Java Source File.

1)                  Start a text editor. You can use any kind of text editor (e.g. Notepad, but not a word processor).   You might already know and be comfortable with the Notepad text editor available on all MS-Windows machines from the start menu: Start>Programs>Accessories>Notepad.  However, we recommend you to use the editor TextPad in the assignment Lab to edit your code.  Textpad is simple, yet provides direct menu commands for compiling and running your Java programs.  To start Textpad in the SFU Assignment Lab select Start (in the left-lower corner) > Programs > CMPT Applications >TextPad. You can see a window is opened as shown below.  

 

2)                  A new document is created for you. You can type your Java program statements in the blank space on the right side of the window and use the functions available via the pull-down menus. From the pull-down menu labeled "File", select "New" to create another document if necessary.  Note that a new file will be needed for each public class definition you require for your program.

In a new document, type in the following code:

/**
 * CMPT101
 * Assignment 0
 * Instructor: Russ Tront
 *
* This class "FirstClass" will display the result 2 * pi on the screeen
 * you can find these codes in your section 3.1 notes)
*/
 
public class FirstClass
{
  // define a constant
  static final float PI = 3.14159F;
 
  // here is the main function
  public static void main(String[] args)
  {
    float twoPi;    // define a variable
    twoPi = 2.F * PI;
    System.out.println(twoPi);
  }
}

 

 Be Careful When You Type

 

Type all code, commands, and file names exactly as shown. The Java compiler and interpreter are case-sensitive, so you must capitalize consistently.

FirstClass  Firstclass

 

3)                  Save this code to a file. From the menu bar, select File > Save As. In the Save As dialog box: 

(Note: Do not choose or make a path that contains blank characters; Java doesn’t like this)

(Note: the file name is the same as the class name, but with a .java suffix.)

When you're finished, the dialog box should look like this:

Now click Save.


C.          Compile/Run Your Program Using Command Prompt

Almost all computer program, including the Java compiler and your resultant program can be run from the Operating System (OS) command prompt (also called command line interface, or command shell).  This section shows you how to do that.  The next section shows you how to more conveniently do this directly from Textpad.

 

1)                  From the Start menu, select Programs > Command Prompt application (or the Command Prompt application in Windows 95/98). When the application launches, it should look like this:

 

The prompt shows your current directory. When you bring up the prompt for Windows 95/98, your current directory is usually WINDOWS on your C drive.  On other versions of your OS it may be some other disk and directory (as shown above).

2)                  To compile your source code file, change your current directory to the directory where your file is located.  If the drive label displayed by the command prompt is not the drive where your project directory is located, then type the desired drive name, followed by ":" and press return. For example to change to drive A type "A:" and press return provided that your floppy disk is ready in A drive. 

Use the DOS command "cd" to define the directory path to your project folder. For example if your program is in the folder "CMPT101" on drive "A" then type "cd Cmpt101" and press return. To confirm that you have indeed made your project directory the active directory you should use the "dir" command to list all the files in the active directory. Your source files should be among those listed.  To compile your file, type the command “javac” followed by your entire file name. For example, at the prompt, type the following command and press Enter:

 javac FirstClass.java 

If the OS prompt reappears without error messages, congratulations; you have successfully compiled your program. 

However, if it does not, it may be that the OS cannot find the javac command.  The java compiler in Assignment Lab is stored in “C:\jdk1.3.1\bin”.  Though this should already be part of your OS search PATH, if it is not, you need to specify the complete path for Java compiler.

 C:\jdk1.3.1\bin\javac FirstClass.java 

 

Error Explanation

Bad command or file name (Windows 95/98)

The name specified is not recognized as an internal or external command, operable program or batch file (Windows NT)

If you receive this error, Windows cannot find the Java compiler, javac.

Here's one way to tell Windows where to find javac. Suppose you installed the Java 2 Software Development Kit in C:\jdk1.3.1, at the prompt you could type the following command and press Enter: 

C:\jdk1.3.1\bin\javac FirstClass.java

 

Note: If you choose this option, then each time you compile or run a program, you'll have to precede your javac and java commands with C:\jdk1.3.1\bin\. To avoid this extra typing, you could instead Update the PATH variable as described in the Sun web pages mentioned in the section below titled “Doing Your Assignments At Home”.

 

Once you successfully compile your file, you will have a corresponding .class file as shown below.


3)                  Run the Program.

In whatever directory your program is in, enter at the prompt:

 C:\> java FirstClass 

Note that you should not add the .class suffix. 

The value of 2 times the mathematical constant Pi=3.14159 will be displayed something like this:

 

 

Congratulations! Your program works.

 

D.          Compile/Run Your Program Using Textpad

You can also compile and run your program more conveniently using TextPad.

 

1)                  Start TextPad.  Select File > Open in the pull-down menu.  Find your file “A:\Cmpt101\Assignment0\FirstClass.java” and open it.  Then, select Tools > Compile Java in Textpad pull-down menu.  Your code will be compiled and a document “Command Results” will appear in the upper left frame of the TextPad window.  Click on it and you can view this document. You can see a line “Tool completed successfully” in this document as below.

 

 

2)                  Now, we run your program. Switch back to your “FirstClass.java” document by clicking “FirstClass.java” that is displayed on the upper left frame.  Select Tools > Run Java Application. A DOS-like Command Prompt window will be temporarily created as below, and the java Virtual Machine program will start executing your program. 

Since this is a temporary window, it will disappear as soon as you program is finished.  However, Textpad is nice enough to add (through a very sneaky mechanism) a “Press any key to continue ...” prompt that will keep the window open so you can see your program results.

 

 

Error Explanation

Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorldApp

If you receive this error, or one containing the name of your program instead of HelloWorldApp, java cannot find your bytecode file, HelloWorldApp.class.

One of the places java tries to find your bytecode file is your current directory. So, if your bytecode file is in C:\java, you should change your current directory to that. To change your directory, type the following command at the prompt and press Enter:

cd c:\java

The prompt should change to C:\java>. If you enter dir at the prompt, you should see your .java and .class files. Now enter java HelloWorldApp again.

If you still have problems, you might have to change your CLASSPATH variable. To see if this is necessary, try "clobbering" the classpath with the following command:

set CLASSPATH=

Now enter java HelloWorldApp again. If the program works now, you'll have to change your CLASSPATH variable. For more information, consult the web link Check the CLASSPATH Variable(outside of the tutorial).  See the section below titled “Doing Your Assignments at Home” for more information about the links to the Sun Microsystems JDK documenation.


E.           Handling Java Error Messages

In most cases, your program will unfortunately not successfully compile when you first time compile it.  You will likely to see many error-messages.  Don’t panic.  It is common when learning a new programming language.  Try to understand what those error messages mean and make correction accordingly.  Here, we will make some changes to the program in order to see some common error messages. 

 

1)                  Make the following change(s) in your source code, and then compile again to see what happens.

 

 
public class FirstClass
{
  // define a constant
  static final float PI = 3.14159F;
 
  // here is the main function
  public static void main(String[] args)
  {
    float twoPi;    // remove the semicolon here
    twoPi = 2.F * PI;
    System.out.println(twoPi);
  }
}
 

 

2)                  Compile your program in the Command Prompt, you will see

 

 

An error message  “FirstClass.java:20: ‘;’ expected” is displayed. The statement :

Float twoPi;

is on the line 20 in your FirstClass.java document.

 

3)                  If you instead compile this bad program in TextPad, you will see the following error messages in your “Command Results” document frame.

 

 

If you double click on the line A:\Cmpt101\Assignment0\FirstClass.java:20 ‘;’ expected, TextPad will switch to the file frame containing your source code and put the cursor on the line 20 where “float twoPi” is located.  Sometimes when compiling a program the compile will have to compile several related files.   Clicking on the first line of an error message will take you to exactly the right line in the right file.

 

4)                  Try some other changes in your original source codes (eg. Remove the word “float” in the line “float twoPi;”).  See the error message accordingly.  Note that some error messages are very confusing, because javac is not sure what is wrong (and can’t be sure because the necessary info is missing).  This makes finding problems challenging!   Also, one error can cause several error messages possibly even referring to different lines, so you might want to recompile after fixing the first error to see if the others error messages disappear too.

 

F.           Multi-file Programs

It is very common to write a big program in several smaller files.  Here is an example.  This program will request the user to input two strings and state if the second string is a substring of the first string. This program makes use of another pre-written class called SavitchIn that is provided by the textbook [CD-ROM from Savitch2001]. It is helpful for you to handle inputting from keyboard, which is otherwise rather difficult in Java. The SavitchIn helper class is already stored in the Assignment Lab. You can find it by following the path “N:\CMPT\101\tront\SavitchIn.java” or the similarly named 104 directory.  To get it, open the Windows Explorer by selecting Start > Programs > Window Explorer.  Copy the “SavitchIn.java” file into the directory where you are going to put the substring source file. For example, create a folder “Assignment0.1” in the folder “A:\Cmpt101”. Copy the file “SavitchIn.java” from “N:\CMPT\101\tront\” to “A:\Cmpt101\Assignment0.1”. Compile the file SavitchIn.java using TextPad, or “javac” in Command Prompt.

Note: You should compile the SavitchIn.java before compiling your source codes (though the compiler might do this for you if you don’t).

Type in the following program that uses SavitchIn.java using TextPad, and save it as FindSubstring.java in the folder “A:\Cmpt101\Assignment0.1”. You can now compile your FindSubString.java file and run it.

 

 

/**

 *  CMPT101

 *  Assignment 0.1

 *  Instructor: Russ Tront

 *  Created by: Eddy Yip

 *

 *  The class "FindSubstring" will request user to input

 *  2 strings. We use the SavitchIn class for our inputting

 *  If the second string is a sub-string of the first string,

 *  then the program will display the position where

 *  the second string first occurs in the first string.

*/

 

import java.io.*;

 

public class FindSubstring

{

 

  public static void main(String[] args)

  {

    System.out.println("Please input two strings.");

 

    System.out.println("Input the first string: ");

        String firstString = SavitchIn.readLine();

 

        System.out.println("Input the second string: ");

        String secondString = SavitchIn.readLine();

 

        int pos = firstString.indexOf(secondString);

        if(pos < 0)

        {

                System.out.println("The string \"" + secondString +

                                   "\" is not found in the string \"" +

                                   firstString + "\".");

        }

        else

        {

                System.out.println("The string \"" + secondString +

                                   "\" is firstly found in the position " +

                                   pos + " of the string \"" +

                                   firstString + "\".");

    }

  }

}

 

Finally, try changing some codes in the above program to create errors, see what happen. Have fun.

 

G.          Doing Your Assignments at Home

Note that if you are working at home and have a high speed Internet connection, then you can download the Java Development Kit from http://java.sun.com/j2se/downloads.html and Textpad from www.textpad.com.  If you are having problems getting your installation to work, you might want to look at Sun’s Java Tutorial at http://java.sun.com/docs/books/tutorial/   Note:  You are not allowed to surf the Internet from inside the Assignment Lab; the lab is strictly for working on computer assignments.   From Sun’s tutorial web page you can follow the links as indicated below.

·         Your First Cup of Java link to java.sun.com/docs/books/tutorial/getStarted/cupojava/index.html

·         First Steps (Win32) link to http://java.sun.com/docs/books/tutorial/getStarted/cupojava/win32.html

·         Installation Instructions link to http://java.sun.com/j2se/1.4/install-windows.html.   In particular, if you cannot compile or run Java programs, pay attention to the section on Path.

If working at home, make sure you install the Textpad text editor after the Java Development Kit, so it can find and use the JDK for compiling and running Java programs.

 

If you have a slow modem, or if you are looking for further hints on starting to as a Cmpt student, or as an Assignment Lab user (e.g. where the Java online documentation can be found in the Assignment), see Russ Tront’s Cmpt 101 hints page at:

http://www.cs.sfu.ca/CC/101/tront/hints.html

Note that you should be able to surf to this page from the Assignment Lab because it is not off campus.