Personal tools
You are here: Home Classes Fall 2004 - Spring 2005 Old CS 160 CS 160 Lab 1
Navigation
Log in


Forgot your password?
« May 2008 »
Su Mo Tu We Th Fr Sa
123
456789 10
11121314151617
18192021222324
25262728293031
 
Document Actions

CS 160 Lab 1

by admin last modified 2005-05-25 15:42

Lab 1  --  Hello, World; a Matrix class

CS 160
Fall, 2004


Our first lab has two parts.  The first part is to enter and run a simple "Hello, world" program.  In the second part, you will write a Java class which represents matrices of integers.  The objectives of the lab are to:
  • Learn how to log in to Linux and use a Linux shell.
  • Learn how to compile and execute Java programs.
  • Get started with emacs (a text editor on Linux).
  • Write a Java program that uses primitive data types, control structures, methods, arrays and classes.
  • Learn how to submit a lab using the department's handin program.

Part one.  Hello, world.

Computer Science maintains a shared file system on a server called OCCS .  An account has been set up for you on OCCS , which gives you disk space on the server.  Your user ID is the first initial of your first name followed by (up to) the first seven letters of your last name.  Your account can be accessed from any of the lab machines under either Linux or Windows XP.  We'll be using Linux for the labs in this course.

Start by logging in to Linux by typing your user ID and password in the login window and hitting the Enter key.  This should start up KDE , which is a Linux window manager.

Notice the icons across the bottom of the screen.  The third one from the left (with the shell image) represents the Unix shell .  The shell is Unix's command line interpreter.  Click on the shell icon.  This will open a shell in a new window.  You can enter any valid Unix command in that window.

Enter the command pwd, which is Unix for "print working directory".  This will display the name of your "home" directory, the last part of which is your account name.  Your home directory is your private area on OCCS where you can store the files you create for all your lab assignments.

Now, create a subdirectory of your home directory called "cs160".  You can use this directory to store all the work you do in this course.  The Unix command to create a directory is mkdir, so enter the command mkdir cs160.

To verify that the subdirectory has been created, enter the command ls.  ls is the Unix command which is used to display the contents of the current directory.  You should see the name cs160.

Next, create a subdirectory of cs160 that you can use for today's lab.  First enter the command cd cs160 to change directory to the cs160 directory.  You can use pwd to verify that your current directory is now cs160.  Then enter the command mkdir lab1 to create a directory for your work today, and use cd to make lab1 the current directory.

Note:  cd  directory_name is the Unix command to change the current working directory.  Whenever you log in to Unix, the current directory is your home directory.  You can use cd to change to the directory that contains the files you want to work with.  To return to your home directory, just give the command cd with no arguments.

Editing (i.e., creating, viewing, or modifying) files can be accomplished with any text editor.  One of the most popular text editors in the Unix world is called emacs .  The command emacs file_name & (where file_name is the name of the file to be edited) opens another window that enables you to edit the specified file. The & at the end of the command makes the emacs window run in the background (so you can still use your Console window). The specified file can be a new file (in which case an empty file is opened up) or an existing file (in which case the current contents of the file are displayed). Note that capitalization is very important, both for Unix commands and filenames.

Now let's actually create a Java program.  Type emacs HelloWorld.java & to bring up an emacs window.  Type in the following Java program:

/*
    Hello,world program which writes to the console.
*/

public class HelloWorld
{

  public void sayHello()
  {
    System.out.println("Hello, world");
  }

  public static void main(String args[])
  {
    HelloWorld helloWorld = new HelloWorld(); // Create a Hello World object
    helloWorld.sayHello();  //  Tell it to say "Hello".
  }

}

The emacs editor will automatically indent to the appropriate column after you press tab key on a new line.  When you have finished typing in the Java program, save your program by selecting files -> save buffer, or by clicking the "save" icon at the top of the emacs window..  For more information on emacs commands, see the GNU Emacs Reference Card .

Now return to your shell window by clicking on it and then hit the return key. The Unix command for listing the files in the current directory is ls. Notice that the file HelloWorld.java that we just created is the only file in the current directory.

Now let's compile (or translate) the Java program into Java bytecodes.  The Java compiler is invoked with the command javac file_name .  Compiling .java files creates .class files which contain Java bytecode.  Note that the Java compiler checks the program for syntax errors.  If you did not type in the program correctly, you may see some error messages from the compiler.  Don't be alarmed, just go back to the emacs window to make corrections.  After correcting the program, save it again and return to the shell window, and recompile the program.  Repeat this process until the program compiles without errors.

Go back to the shell window and enter the ls command.  You should see listing of both the source file (HelloWorld.java) and the class file (HelloWorld.class).

Java bytecode is executed by invoking the Java Virtual Machine (JVM) using the command java class_name (where class_name is the name of the class, not the file -- it does not have an extension).  When you run it, you should see the message "Hello, world" displayed on the command line.

Note:  The Unix shell has a feature called tab completion which can save time while typing in commands.  Tab completion enables you to type only what is necessary for the system to understand what you want.  Whenever you press the Tab key while you are entering a command, the system will complete the command as best as it can with respect to the current environment.  For example, there are several commands that start with j and even ja so if you type j or ja and then press the Tab key the system doesn't know which command you want.  On the other hand, the only commands that start with jav are commands used by the Java Development Kit (JDK) and they all start with java so if you type jav and then press the Tab key the system will complete the command to be java.  It is your responsibility to continue typing to further differentiate which JDK command you want.  To invoke the compiler, you would then type a c .  At this point, if you hit the space bar (so it knows the command is javac ) and then the Tab key the system will type in HelloWorld. since the current directory contains both HelloWorld.java and HelloWorld.class .  Typing a j followed by a tab will complete the command.


Part two.  A Matrix class

In this part of the lab you will implement a class called Matrix which can be used very much like we might use a matrix in mathematics.  For example, your class will be able to add, subtract and multiply matrices.  The specifications of the class follow:


Matrix

Data Fields

int rows, cols;   //   The number of rows and columns in the matrix.
int[][]  data;     //   A two-dimensional array of integers holding the contents of the matrix.

Methods

public Matrix( )
Requirements: none
Results: Constructor. Allocates space for and initializes a Matrix of the default size which is 5 x 5.

public Matrix(int n)
Requirements: n is a positive integer between 1 and 10 inclusive
Results: Constructor. Allocates space for and initializes an empty n x n Matrix.

public Matrix(int n, int m)
Requirements: n and m are positive integers between 1 and 10 inclusive
Results: Constructor. Allocates space for and initializes an empty n x m Matrix.

static public Matrix loadFromFile(String fname) throws IOException
Requirements:  The file for an m x n matrix should start with a line containing the values of m and n.  This is followed by m lines, each containing n integer values.  Each line represents the data in one row of the matrix.  For example, a file containing a 3 by 3 identity matrix would look like this:

3 3
1 0 0
0 1 0
0 0 1

Results:  Returns a Matrix object created from data in the given file.  

public int getCols()
Requirements: none
Results: returns the number of columns

public int getRows()
Requirements: none
Results: returns the number of rows

public void setValue(int r, int c, int val)
Requirements: the Matrix must contain an element in position [r][c]
Results: assigns Matrix element in row r and column c to val

public int getValue(int r, int c)
Requirements: the Matrix must contain an element in position [r][c]
Results: returns the value of the element in row r and column c

public String toString()
Requirements: none
Results: returns a string representation of the matrix arranged in rows and columns

public Matrix transpose()
Requirements: none
Results: creates a new Matrix which is the transpose of this matrix

public Matrix plus(Matrix rhs)
Requirements: Matrix has the same number of rows and cols as rhs
Results: creates a new Matrix of the same size that contains the sum of the two Matrix operands

public Matrix minus(Matrix rhs)
Requirements: Matrix has the same number of rows and cols as rhs
Results: creates a new Matrix of the same size that contains the difference of the two Matrix operands

public Matrix times(Matrix rhs)
Requirements: Matrix has the same number of cols as rhs has rows
Results: creates a new Matrix that contains the product of the two Matrix operands

example  Multiplying a 3x2 matrix times a 2x2 matrix gives a 3x2 matrix:

  5 6     1 2  =  23  34
  3 4  X  3 4     15  22
  1 2              7  10

 

public Matrix times(int scalar)
Requirements: none
Results: creates a new Matrix that contains each matrix entry multiplied by scalar

public boolean isSymmetric()
Requirements: none
Results: returns true if the matrix has an equal number of rows and columns and if every element in position [i][j] is equal to the element in position [j][i], false otherwise

public boolean isDiagonal()
Requirements: none
Results: returns true if the matrix has an equal number of rows and columns and if every element in position [i][j] with i != j is 0, false otherwise

public boolean isEqual(Matrix rhs)
Requirements: none
Results: returns true if the Matrix operands are of the same dimension and have equal corresponding entries, false otherwise


I'm providing an initial version of Matrix.java and MatrixTest.java to help you get started.  My version of Matrix.java includes a few of the methods you'll need:  the no-argument constructor, the getRows accessor method, the transpose method, the toString method, and the loadFromFile method.  toString and loadFromFile are needed to perform I/O; you can see how they are used by looking at my code in MatrixTest.java.  You are responsible for writing the implementations of the remaining methods, as described above, and testing them.  You should write several test cases for each method.

My version of MatrixTest.java contains a single test of the transpose method.  You should be able to compile and run it after writing the missing constructors in Matrix.java.

1.    Start by downloading the jar file lab1.jar .  This file contains my initial versions of Matrix.java and MatrixTest.java, along with a matrix data file called m1.txt.  You can use these as the starting point in completing the lab.

Make sure your current directory is cs160/lab1.  Then uncompress the archive with the command

jar xf lab1.jar

This command will extract the contents of the archive.

2.    Add the necessary implementation for each of the other methods.  Start with the missing one-argument and two-argument constructors.  After writing these, you can compile and run my MatrixTest.java program, with the commands:

javac *.java
java MatrixTest

Continue with the other methods in the specifications above.  Implement and test each method before moving on to the next one.  Document your code as you go.

3.    Write one or more Java applications to test the Matrix class.  Use appropriate names with the word "Test" in the title, such as MatrixTest.java, MatrixTest1.java, AdditionTest.java, SymmetricTest.java, etc.  Each test application should contain a main program.

Test each method thoroughly.  Your lab grade will depend in part on how thoroughly your methods have been tested.  You will want to create some more data files which can be loaded from the test programs.

Note:  I will use my own test application to test your methods, so make sure that you follow the specifications carefully.

4.    Exceptions.  Several of the methods can work properly only if the input data satisfies some condition.  For instance, to add two matrices, they must have the same number of rows and columns.  Your methods should test for these conditions.  If a required condition is not satisfied, use a throw statement to throw a RuntimeException.


Part three.  Submitting your results

The Computer Science program uses a program called handin to handle submission of labs and homeworks.  It copies an entire directory to a directory on occs which is accessible to the instructor.  You can use it to hand in the results of this lab as follows:
  • Make sure that your cs160/lab1 directory contains the files HelloWorld.java, Matrix.java, your java test applications, and any matrix data files that you use.
  • Change to the cs160 directory and type handin.
  • Enter the class number (160), the assignment number (lab1), and the file/directory name (lab1).  


 

Powered by Plone CMS, the Open Source Content Management System

This site conforms to the following standards: