CSC 104 Lab Session

This is your first lab session with Java. This page contains some information that we have gone over in the tutorials and some exercises to guide you along.

If you already know how to log into cdf and use the pico text editor, feel free to jump to the exercises below.

If at any point you would like some clarifications on this page, feel free to ask the TA for help.


NEW -- DO THIS FIRST IF YOU ARE USING THE CAMPUS COMPUTERS

option A is recommended over option B

OPTION A

Switch to MS-Dos. You can do this by double-clicking on the MS-Dos Prompt icon. If this icon is not on your desktop, search for it using the "Find..." function from the "Start" menu on the bottom left corner.

If you use MS-Dos, you can ignore the "Loggin In" section.

OPTION B

Go to:

http://www.cs.utoronto.ca/~andria/csc/108s01/misc/codewarrior.html

and see if you can follow the instructions on how to use CodeWarrior. CodeWarrior has a text editor, and it can also compile and run programs. Try this for now. Once you are used to it, go to the Examples and Exercises sections.

If you use CodeWarrior, you can ignore the sections on "Loggin In", "Text Editor", and "Does it work?".

option A is recommended over option B


Logging In

There is a simple interface for Java located on a cdf machine called eddie. To get to it, you can use the telnet program. To run telnet, go to the START menu on the bottom left corner and click on it. A menu pops up. Find the option that says "Run ..." and select this option. The menu disappears and another window then pops up and asks you to type something in. In this box, type in:

telnet cdf.utoronto.ca

If this is successful, a telnet window will pop up (i.e., a window with the name telnet written on the top). If you are not successful, ask a neighbour for help or ask the TA. The telnet window will prompt you to enter your something for "login:". At this prompt, enter the login name given to you. Another prompt will appear that looks like "Password:". At this prompt, enter the password you have chosen. If successful, you will see the prompt:

eddie%

If a name different from eddie appears, it's okay. However, if you do not see a prompt at all (i.e., something that looks like NAME%), then ask for help.

Now you have successfully logged in.


Text Editors

For HTML, you have learned to use some text editors. Unfortunately, the text editors we talked about before have "fancy" interfaces. What we need is something very simple and shows text only. For this reason, you will be using pico.

To start pico, type:

eddie% pico

Notice that the window changes to pico and the bottom of the window shows you some commands you can use for editing (e.g., cut and paste). This editor is very simple to use. You should familiarize yourself with the commands shown on the bottom of the window.

Now, type in the HelloWorld.java program below:

class HelloWorld
{
   public static void main( String argv[] )
   {
      System.out.println( "Hello World!!!" );
   }
}

Save this program using the command "WriteOut" (Control O). It will ask you to enter the name of the file. Here, you must type in "HelloWorld.java". Remember that the name of the file and the name of the class must be spelled exactly the same (with capitals and lowercases), with .java at the end of the file name.

After you have saved the file, you can exit. Use the "Exit" (Control X) command.

Now you should be back at the eddie% prompt.

Suppose you made a spelling mistake and you want to fix it. To modify your HelloWorld.java program, type:

eddie% pico HelloWorld.java

Now you can make whatever changes you need.

In general, once you have saved a file, to open it and modify it, you just need to type:

eddie% pico FILENAME

What if I forget the name of the file? Go to the prompt and type:

eddie% ls

A list of files that exist in your directory will appear on your screen. Now

What if I want to change the name of the file? If you want to change it from Hello.java to hello.java, for example, type:

eddie% mv Hello.java hello.java

This will move the old file to a new name. In general, you should type:

eddie% mv OLDFILENAME NEWFILENAME


Does it work? (Compiling and Running Java Programs)

Recall the steps you need to take to test your program:

  1. Write the code in some text editor (e.g. pico)
  2. Save it in a file
  3. Compile the code: eddie% javac HelloWorld.java
  4. Run the code: eddie% java HelloWorld

Steps 1 and 2 you saw in the previous section. Now we discuss what steps 3 and 4 do.

Compiling the code.

Remember what this means? It means that the English-like instructions you learned in class, i.e., the Java code, is going to be translated into something that the computer understands, i.e., zeros and ones).

In general, to compile a program, type:

eddie% javac FILENAME

Nothing shows up. After you type the javac command and nothing shows up on the screen, except for another eddie% prompt, then that means the translation was successful! Congratulate yourself! Now you can run the code.

What are all these messages on the screen? After you type the javac command and if some or lots of messages show up on the screen, then that means your program had errors in it and it could not be translated into zeros and ones. Sorry.

The messages that showed up are called "error messages". They indicate where the messages are (the line numbers at the beginning of the message) and what kind of error it is. Of course, the computer is not omnipotent. It cannot always be correct about these errors. So, these error messages are just a guess at what might be wrong. Use them as a guide to help you fix the program. Sometimes errors are due to simple mistakes like typos and missing ". Begin with those.

Running the code.

After compiling, the computer creates a file that contains the zeros and ones instructions. This file is called an "executable". If your program is called HelloWorld.java, then the corresponding executable is named HelloWorld.class. In general, the executable is named FILENAME.class. To see what it does, you have to "run" it. So, type:

eddie% java HelloWorld

Notice the command we use is java (without the "c" at the end) and that we do not type in .class. In general, the command you use is:

eddie% java FILENAME

I think it works. If the output on the screen shows what you expected, then your program works!

It doesn't do what I expected it to. Then something went wrong. Go back and see what mistakes you might have made by checking each line in the file. Ask your friends or TA for help if necessary.


Examples

These examples were taken straight out of my notes. They are all complete. Your job is to type them into your own files word for word, save them, compile them, and run them to see what the output is. The purpose of this component is to get you used to compiling and running Java code. If these are too easy for you, try the exercises below which require you to write your own code.

Each example has a set of "Things to try". These suggestions will help you understand how Java works. Try them. Try making one change in your file, save it, compile it, and if possible, run it. See what happens, and see if you understand why. If there is an error, do you know why it happened? If the output looks different, did you expect it? If the output looks the same, is this correct?

If you understand these examples and all the suggestions in "Things to try", you are ready to write your own Java programs.


1. A program that prints out the sums of numbers.

class Sum
{
   public static void main( String[] args )
   {
       // variable declarations
       int a = 2;
       int b = 3;
       int firstsum;
       double x = 4.5;
       double y, secondsum;

       // arithmetic and assignment
       firstsum = a + b;

       y = firstsum;

       secondsum = x + y;
            
       // print to screen, uses concatenation
       System.out.print( "\n The first sum is " );
       System.out.println( firstsum );
       System.out.println( "\n" + "The second sum is " + secondsum + "\n" );
   }
}

Things to try:


2. A program that calculates the area of a donut (i.e., there is a big circle with a small circle inside it, calculate the area that is taken up by the space between these two circles).

class Donut
{
   public static void main( String[] args )
   {
      // variable declarations
      double pi = 3.14;
      double outRad = 5.2;         // radius of outter circle
      double inRad = 2.79;         // radius of inner circle
      double areaO, areaI, areaDonut;

      // make calculations
      areaO = pi * outRad * outRad;
      areaI = pi * inRad * inRad;
      areaDonut = areaO - areaI;
            
      // print output to screen
      System.out.print( "\n The area of the donut is: " );
      System.out.print( areaDonut + "\n" );
   }
}

Things to try:


3. A program that

class Donut
{
   public static void main( String[] args )
   {
      // variable declarations
      double outRad = 5.2;         // radius of outter circle
      double inRad = 2.79;         // radius of inner circle
      double areaO, areaI, areaDonut;

      // make calculations
      areaO = areaCircle( outRad );
      areaI = areaCircle( inRad );
      areaDonut = areaO - areaI;
            
      // print output to screen
      System.out.print( "\n The area of the donut is: " );
      System.out.print( areaDonut + "\n" );
   }
    
   static private double areaCircle( double r )
   {
      // variable declarations
      double pi = 3.14;
      double area;

      // compute
      area = pi * r * r;

      // pass the result back to caller
      return area;
   }
}

Things to try:


4. A program that

import java.lang.Math;

class distance
{
   public static void main( String[] args )
   {
      // variable declarations
      double x1, x2, y1, y2, dist;
      double tempX, tempY;

      // initialize the (x,y) values
      x1 = 2;  y1 = 3;
      x2 = 5;  y2 = 7;

      // compute the squares
      tempX = square( x2 - x1 );
      tempY = square( y2 - y1 );

      // compute the distance
      dist  = Math.sqrt( tempX + tempY );

      System.out.print( "The distance between " +
      "(" + x1 + "," + y1 + ")" + " and " +
      "(" + x2 + "," + y2 + ")" + " is " + dist );
   }

   static private double square( double n )
   {
      return n * n;
   }
}

Things to try:


5. A program that prints out the face of a die in random (i.e., a random number between 1 and 6). Note: the material in this example is harder than the prevoius, so don't worry if you don't understand it completely. This example is just for fun.

import java.lang.Math;

class RollDice
{
   public static void main( String[] args )
   {
      int face;

      // use random to generate real random numbers between 0 and 1
      // then scale them to the faces of a die between 1 and 6
      face = 1 + ( int )( Math.random() * 6 );
      System.out.println( "Face   " + face );
   }
}

Things to try:


Exercises

These exercises were taken straight out my notes. Most of them are incomplete and they require you to fill in the blanks. So, your job here is to complete these programs. For each program, create a new file using pico. Type in what is given to you, and fill in "..." with the correct Java instructions. We went over most of these in the previous tutorial, so it should be familiar to you. (If you get stuck, ask for help.) It may also help if you have already gone through the examples in the previous section and understood them.

Once you have typed in the exercise and saved it, you can exit pico to go back to the eddie% prompt. Then, you can compile and run the program to see if it works. Going through each of these exercises will give you more practise and a better understand of how Java works.

If you understand how these work, you are in good shape for the course. Good luck!


1. A program that does nothing.

 
class Nothing
{
   public static void main( String argv[] )
   {
   }
}


2. A program that prints "Hellow World!" to the screen.

class ...
{
   public static void main( String argv[] )
   {
       ...
   }
}


3. A program that adds two integers and prints out their sum.

class ...
{
   public static void main( String argv[] )
   {
      // declare variables
      ...

      // initialize the variables
      ...

      // add them
      ... 
      
      // print output to screen 
      ... 
   }
}
\end{verbatim}


4. A program that two numbers (integers or decimals) and prints out their sum.

class ...
{ 
   public static void main( String argv[] )
   {
      // declare and initialize variables
      ...

      // add them
      ...

      // print output to screen
      ...
   }
}


5. A program that prints out what the user types in.

class ...
{
   public static void main( String argv[] )
   {
      // prepare for input from screen
      BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
      String response;

      // get some words from user
      System.out.println( ... );

      // read in the input
      response = input.readLine();

      // print output to screen
      ...
   }
}


6. A program that lets the user guess a letter in the alphabet. (We didn't go over this one in class, so don't worry if you don't know how to complete it. Do have a try anyway.)

class ...
{
   public static void main( String argv[] )
   {
      // prepare for input from screen
      ...

      // make up a default answer and store it somewhere
      letter = "b";

      // ask the user for a letter
      ...

      // read in the input 
      ...
      
      // print the result to the screen 
      if( letter.equals( ... ) ) 
         ...
      else 
         ...
   }
}


A Game

Try this robot program for fun. Copy it and run it. Do you understand how it works?


Copyright © 2001 by bowen hui