California State University, Chico UPE
       
   
 
  Computer
            Survival
            Guide

Table of Contents
 

Getting Started...................3-6
 
Where are the ECT Computer Systems ....................3
Accessing the ECT Computers Remotely (using PuTTY) ............3
Getting and using PuTTY...........................3
 
The Joy of Unix..................6-11
 
Basic commands.............................6
Working with files and directories .......................7
Permissions .................................8
Special characters .............................9
OOOPS (dealing with mistakes) ........................9
VI editor ...............................10
 
HTML ......................11-13
            Basic page ...............................11
Tables ................................12
Meta tags .................................13
 
SQL .......................13
 
Visual Basic ..................... 14-19
Procedures ................................14
Syntax definitions ...........................16
Collection object .............................18
 
Java .......................19-23
Windows and Java ............................19
Coding Recommendations .........................19
Example ................................20
Installing and Using the Java SDK ........................21
More Examples ..............................22
 
C++ ......................23-28
Compiling ................................23
Debugging tips............................... 25
Pointers and functions ..........................25
Basic loop syntax ............................27
 
 
Order of Operations ................. 27
 
Basic Linked List.................... 28
 
Various Coding Examples ..............29
 
Programming Tips .................... 31
 
Suggestions before getting help ........... 32
 
***NOTE***
 
This is NOT a substitution for your textbooks; this is just a quick-reference on basic elements and a guide to using some of the computers at school. Use the guide to get started using the system at school. Use the references and tips WITH your textbooks.
 
If you find any errors or would like us to add something to the guide please email the officers of UPE at:   upe@ecst.csuchico.edu
 
To access the ìSurvival Guideî online go to: http://www.ecst.csuchico.edu/upe/survivor.html
 
 
 
 

Getting Started
 
The computer systems at CSU Chico are varied.  There are several computer labs with different types of equipment in them.  Here is a summary of the computer labs available in OCNL. There are also many other labs scattered across Campus for your use.
OCNL 133
Windows NT or 2000
OCNL 136
Sun Ultrasparc 10's (your back to the soda machine)
HP Pavilion, Windows 2000 (you facing the soda machine)
OCNL 241
Sun Ultrasparc 5's
OCNL 244
Mixed Unix Lab
OCNL 251
Windows NT or 2000
The primary server at the College of Engineering, Computer Science and Technology (ECST or ECT) is a Sun 3500 server named tiglon.  All of the servers at ECST are named for wildcats.  (see if you can guess what a tiglon is.  Hint, I always thought it should have been spelled tiglion.) Tiglon is replacing 27 HP workstations that were providing server facilities to the college.  Tiglon is more than capable of handling the load for many years to come.
Lynx is the ECST web server, although you will never have need to access it directly and most of its functions are hidden from the casual user. Students get to lynx's file system by accessing their public_html directory, which is linked symbolically to the lynx machine.
 
 
You can use telnet to access the servers (not the labs), although it is not recommended because it does not allow secure authentication with the UNIX system. If you choose to do so anyway, you will be restricted from accessing the labs. Instead, use ssh (secure shell) to log in. There are several free ssh clients for the Microsoft Windows operating system. One such client is PuTTY and can easily be found by browsing to http://www.google.com/search?q=putty+ssh
 
When you first log in to ect-unix.ecst.csuchico.edu, you will be prompted with a warning that the serverís host key is not cached. This is expected since it has not been written yet. You must say yes to this prompt to save the serverís key. This should only happen the first time you log into a new server using ssh.
 
Getting and Using Putty
Putty is a telnet/ssh client that can be used to connect to a Unix system.  It will allow a text based connection to the ECT Unix systems at California State University, Chico.  Putty is a free download from:
 http://www.chiark.greenend.org.uk/~sgtatham/putty/
Putty is available on all of the Windows NT / 2000 machines in OCNL 251, OCNL 133 and OCNL 136.  It may or may not be set up for a connection to ect-unix.ecst.csuchico.edu.  Setting it up on these systems or on your home system is the same process.
Putty comes as a single executable file (putty.exe) that can be placed anywhere on a Windows system.  I find it convenient to just put it on the desktop.  When you open up Putty, you will get a screen similar to the following:
The "ect-unix' line will not be in the default Putty window.  You will need to input ect-unix.ecst.csuchico.edu into the Host Name text box and choose SSH as the Protocol.  Your window will look similar to the following:
You can click Save to save the settings for this session.  You will be prompted to give the session a name.  I chose ect-unix.  From now on, all you have to do is double-click on the ect-unix session and it will open a connection to ect-unix.ecst.csuchico.edu.
That connection will look similar to the following:
 
 
Login using your ECST Unix account login and password.  You will now be connected and logged in to tiglon, the application server at the College of Engineering, Computer Science and Technology and you will get a screen similar to the following:
However, your prompt will probably be just a dollar sigh ($) rather than the name of the host and the path information.  I have modified my prompt from the original.
From this screen, which is resizable, you will be able to enter Unix commands and also edit and debug your Java programs. 
Keep in mind that you can have multiple Putty windows open so you can edit and save in one window and you can compile in another.  This is what most developers do in order to save the time of exiting and then reloading a file for editing.
 
 
The Joy of Unix
 
Changing your password:
passwd                                                            Do this ASAP!
 
Cruising the Shell :
cd                                     moves you to your home directory
 
cd directoryname           moves you to that directory named directoryname
 
cd ..                                 moves you to the parent of the current directory
 
pwd                                  displays the path of the working (current) directory
 
ls                                      displays a listing of files in the current directory
 
ls -a                                 displays all f iles, including hidden f iles such as .profile and .login *
 
ls -l                                  displays more information on each file, including permissions
 
r command     r                will search command buffer as you type and will substitute a match..
                                        can save time when executing same command many times
 
clear                                  clears the screen
 
script  filename                starts a log f ile of your Unix session and writes it to filename
                                          end the script by typing Control-d
 
man commandname        displays documentation for that command, use space bar to move
                                          from page to page
 
man -k word                     displays all commands where word is a keyword
 
*Attempting to modify any of these special files can wreak havoc on your environment if you don't know what you are doing!
 
help commandnam          similar to man, less technical
 
exit                                     end the Unix session logout may also work
 
Working with Files and Directories:
mkdir directoryname       creates a subdirectory off of the current directory named
                                         directoryname
 
rmdir directoryname        removes the directory named directoryname from the current
                                         directory (the directory being removed must be empty first)
 
cp filel file2                        copies filel to file2
 
cp -i filel file2                    prompts for confirmation if file2 already exists
 
cp fname dname                 copies file fname into directory dname
 
rm filename                        deletes filename
 
rm - i filename                   prompts for y or n before deleting file
 
lpr ñppname fname           prints the file fname to the printer pname
 
lpq -ppname                        shows the printer queue (including job numbers) for pname
 
lprm ñ ppname jobnumber             removes jobnumber from pname's job queue
 
more filename                    shows the contents of filename, one page at time, use the
                                            spacebar to see the next page, q to quit
                                            also can be used as a "pipe" to control system output
                                            ex. ls ñl |  more
 
page filename                   a little more versatile than more, press ë-ë   to go back a
                                            page or type a number to go to that page
 
cat filename                     will display contents of filename
 
cat file1 file2 > file3         concatenates file1 and file2into file3
 
Permissions:
Access to files and directories is controlled through the granting and revoking of permissions. You must have permission to read (r), write(w) or execute(x) a file (even your own!), and similarly you must have permission to view filenames(r), add or delete files(w), or search through (x) a directory. The owner (creator) of a file or directory can assign permissions to himself, to all members of a specific group, or to everyone. You can view permissions for files by performing a long listing (ls -l).
 
The permissions will look something like this: _rwxrw_r_ _
The first space is only there to differentiate files from directories (blank for file, d for directory). The following three characters (rwx) are the permissions for the owner aka user(u) of the file. In this case the user has read (r), write(w) and execute(x) permissions. The next three characters (r _ _) are the permissions for other members of the owner's group(g). They have permission to read(r) and write(w). The last three characters are the permissions for everyone else(o). They only have read(r) permission.
 
chmod u=rwx,g=rw,o=r filename               Sets the above permissions for filename
chmod o+w filename                                    Grants write priviledges for filename to
others
 
chmod 777 filename                                     Grants all permissions to everyone for
          filename, using octal notation
 
 
 
 
 
Octal notation: Each group of 3 permissions is assigned a 3 digit binary value
∑      22 21 20
r w x
 
                           _ _ _ = 0 = no permissions            _ _ 1 = 1 = execute permission
                           _ 1 _ = 2 = write permission         1 _ _ = 4 = read permission
 
111 = 4+2+1 = 7 = read, write and execute permissions
 
In general, your directory permissions should be set to: r wx     - - - - - (700).
Permissions to your no non-executable files shouId be set to r w- - - - - - -(600), and
permissions for executable files should be set to r w x    - - - - - - (700). This will
protect your work from being copied or vandalized by others.
 
Special Characters:
The following characters have special meaning in Unix and should not be used in
filenames:      &; | * ? ë ì [ ] ( ) $ < > { } ^ # \ /
 
OOOPS:
If you need to stop a currently executing command (process),
 
kill anumber                          kills the process with the pid number anumber.
 
ki1l -9 anumber                    kills the process and all associated processes.
 
ps -u username                     displays all current processes (and their PID's) belonging to
                               username
 
ps -lu username                       displays more info about username's currentprocesses
 
control-u                                   kills the current command line (before you hit enter)
 
control-c                                   may interrupt the current process
 
control-d                                   exits some processes (such as script)
 
control-z                                   sends a process to the background
 
control-h                                   erase a character
 
backspace                                 same
 
delete                                        same
 
Being a VIP (a VI (editor) Person)-.
VI operates in 2 modes. When you start VI, you are in the command mode. You can move around to different lines, delete text, copy, paste, save changes and exit VI. In order to enter text you must change to input mode. Input can begin before or after the cursor, before or after the current line, or on an entirely new line before or after the current line. The same line editing commands available at the Unix command line work here also. Within input mode you are restricted to editing the current line, or creating a new line. To enter command mode from input mode, hit the escape key. To return to input mode, hit either i, I, a, A, o, or 0, depending on where you wish text entry to start. Sometimes the screen may become badly distorted. This often happens across a Telnet when the buffer size is too large (over 25). The screen can be repainted with the control-d key stroke combination. Below is a listing of the most common VI editing commands.
 
COMMAND MODE:
            Move it:
                  H                                Top of screen
                  L                                Bottom of screen
                  M                               Middle of screen
 
                  h                                 Left            l                                     Right
                  j                                  Down         k                                     Up
                  0                                 (zero)         Beginning of line         $                   End of the line
                  b                                 Previous word                                 w                   Next word
                  (                                 Previous sentence                           )                    Next sentence
 
                  control-b                   Previous screen                               control-f      Next screen
                  control-d                   Down 1/2 screen                             contrl-u        Up 1/2 screen
                  nG                              Move to line n                                
                  G                                Move to end of doc
 
            Seek and you shall find:
                                    ?abc                 Searches backward for "abc"
                                    /abc                 Searches forward for "abc"
                                    n                      Repeat search
                                    N                     Repeat search in opposite direction
 
                        Cut and Paste:
                                    x                      Cut character under cursor
                                    nx                    Cut n characters after cursor
                                    x                      Cut character before cursor
                                    nX                   Cut n characters before cursor
 
                                    dw                   Cut current word
                                    dd                    Cut current line
                                    D                     Cut to end of line
 
                                    xp                    Transpose characters
 
                                    y                      Copy current word
                                    yy                    Copy current line
 
                                    p (lower)                 Paste after cursor
                                    p (upper)         Paste before cursor
 
                        Ready to Write:
                                    i                       Start writing before cursor
                                    I                       Start writing at beginning of line
                                    a                      Start writing after cursor
                                    A                      Start writing after end of line
                                    o                      Start writing on a new line after current line
                                    0                      Start writing on a new line before current line
 
            I'm outta here: - get into command mode first by pressing the escape key
                                    :q                     quit - will be prompted to save if changes were made
                                    ZZ or :wq       save and quit
                                    :q!                    quit and don't save changes
 
            Other editors:
pico                 easy to use, multi-line editing capability. Editing commands are a subset of the emacs commands
 
emacs             very powerful development environment, including a text editor.
 
 
HTML
 
Below is the very basic format for an HTML document. You can copy this into a text file and save it with a .html extension and view it in your browser.
 
 
<html>
<head>
                        <title>"put a title here, it will appear at the top of the browser"</title>
</head>
 
<body>
<p> This is a paragraph tag
<br> This is a break tag, you would use it when you wanted to go to a new line
 
&nbsp;"Put text and/or images here" ;&nbsp;&nbsp Since whitespace is ignored, you need to use these no break spaces when you want extra spaces. You can use as many of them as you need, each one is one space.
 
<div align="center">To Center text</div>
 
<b>This will make your text bold</b> </p>
 
</body>
</html>
 
 
To put an image on your web page:
img src="PathToImage.jpg" width="" height="" border="0" alt="">
 
To put a hyperlink on your page:
                        <a href="SomeURLgoesHere.html">Then and Image or text describing what your
            linking to, goes here.</a>
 
<!-- Comments go between these tags -->
 
Tables:
 
You can cut and paste the tags below in the body of your page, save it, then view it in your browser.
 
 
<table cellspacing="2" cellpadding="2" border="1">
 
<!-- First Row -->
<tr>
    <!-- First Column, First Row -->
    <td> Put stuff that you want in the cells here, between the td tags </td>
    <!-- Second Column, First Row -->
    <td></td>
    <!-- Third Column, First Row -->
    <td>and so on.</td>
</tr>
 
<!-- Second Row -->
<tr>
                        <!-- First Column, Second Row -->
    <td></td>
                        <!-- Second Column, Second Row -->
    <td></td>
    <td></td>
</tr>
<!-- Third Row -->
<tr>
    <td></td>
    <td></td>
    <td></td>
</tr>
</table>
 
 
This is an example of meta tags being used by a student here a CSU Chico, something as simple as this can get you great results on googleís search engine.
 
<head>
<meta name="description" content="Giant Shower Heads ">
 <meta name="keywords" content="Giant Shower Heads, large shower heads, 12 inch shower heads">
</head>
 
This example was taken with permission from:
 
Links:
Go to http://www.blooberry.com/ if you need a good online HTML reference.
 
 

SQL

 

 

 

 

 

SELECT         [DISTINCT]    {*, column [alias], .}
FROM            table
WHERE         condition(s);
 
DESCRIBE    tablename
 
SQL *Plus File commands:
 
  • SAVE filename
  • GET filename
  • START filename
  • @ filename
  • EDIT filename
  • SPOOL filename
  • EXIT
 
Comparison Operators:
(to use in the where condition)
.
WHERE           ColumnName BETWEEN lower limit AND upper limit;
.
WHERE           ColumnName IN (values);
.
WHERE           ColumnName LIKE value;
.
WHERE           ColumnName IS NULL;
 
Creating Tables:
 
CREATE TABLE        tablename
                                    ( ColumnName            NUMBER(2),
                                    ColumnName2            VARCHAR(50));
                                   And so on . giving the column name and data type.
Then:
 
INSERT INTO table VALUES value;
 
Some Data Types


 


CHAR(size)   
Fixed length character data
VARCHAR2(size) 
Variable ñlength character data
NUMBER(p,s)  
Variable-length numeric data
DATE            
Date and time data
LONG            
Variable-length character data up to 2 gigabytes(gb)      
RAW AND LONG RAW    
Raw binary data
CLOB          
Single byte character data up to 4 gb (ex. A Book)
BLOB              
Binary data up to 4 gb (ex. Photos)         
BFILE
Binary data stored in an external file; up to 4 gb (ex. Movies)
 
 
 
 
In Visual Basic, all executable code must be in procedures. You cannot define one procedure within another. VB allows several different types of procedures to meet the programmerís needs. Note that while serving distinctly different purposes, the different procedure types do share some common syntax. Here are the various procedure types allowed, along with their signatures, along with a brief description of the various syntactic elements:
 
        Sub Statement:    Declares the name, arguments and code that form the body of a Sub procedure. A Sub procedure can take arguments, perform a series of statements, and change the value of its arguments. Note that a Sub procedure does not return a value, so it cannot be used in an expression.
[Private | Public | Friend] [Static] Sub name [(arglist)]
[statements]
[Exit Sub]
[statements]
 End Sub
                  
        Function Statement:               Declares the name, arguments, return type and code that form the body of a Function procedure. Like the Sub procedure, a Function procedure can take arguments, perform a series of statements, and change the value of its arguments. Unlike a Sub, however, a Function may return a value and may therefore be used in an expression.
[Public | Private | Friend] [Static] Function name [(arglist)] [As type]
[statements]
[name = expression]
[Exit Function]
[statements]
[name = expression]
End Function
                       
        Property Get Statement:        Declares the name, arguments and code that form the body of a Property Get procedure, which gets (returns) the value of a property. A Property Get procedure can take arguments, perform a series of statements, and change the value of its arguments. It can also be used on the right side of an expression in the same way you would use a Function, a property name, or a constant.                 
[Public | Private | Friend] [Static] Property Get name [(arglist)] [As type]
[statements]
[name = expression]
[Exit Property]
[statements]
[name = expression]
End Property
 
        Property Let Statement:         Declares the name, arguments and code that form the body of a Property Let procedure, which assigns a value to a property. Like a Function and PropertyGet procedure, a PropertyLet procedure is a separate procedure that can take arguments, perform a series of statements, and change the value of its arguments. However, unlike a Function and PropertyGet procedure, both of which return a value, you can only use a PropertyLet procedure on the left side of an expression.
[Public | Private | Friend] [Static] Property Let name ([arglist,] value)
[statements]
[Exit Property]
[statements]
End Property
                       
        Property Set Statement:         Declares the name, arguments and code that form the body of a Property Set procedure, which sets a reference to an object.
[Public | Private | Friend] [Static] Property Set name ([arglist,] reference)
[statements]
[Exit Property]
[statements]
End Property
 
Note: In the preceding syntax definitions, [] denotes an optional item, and the | separates the possible values for an item. Hereís a list of the various terms and what they mean:
 
Part
Description
Public
Optional. Indicates that the procedure is accessible to all other procedures in all modules. If used in a module that contains an Option Private, the procedure is not available outside the project.
Private
Optional. Indicates that the procedure is accessible only to other procedures in the module where it is declared.
Friend
Optional. Used only in a class module. Indicates that the procedure is visible throughout the project, but not visible to a controller of an instance of an object.
Static
Optional. Indicates that the procedure's local variables are preserved between calls. The Static attribute doesn't affect variables that are declared outside the procedure, even if they are used in the procedure.
name
Required. Name of the procedure; follows standard variable naming conventions.
arglist
Optional. List of variables representing arguments that are passed to the procedure when it is called. Multiple variables are separated by commas.
type
Optional. Data type of the value returned by the Function or Property Get procedure; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Date, String, Stream, Object, Variant, or any user-defined type.
statements
Optional. Any group of statements to be executed within the procedure.
expression
Optional. Return value of the Function or Property Get.
value
Required. Used in a Property Let procedure, a variable to contain the value to be assigned to the property. When the procedure is called, this argument appears on the right side of the calling expression. The data type of value must be the same as the return type of the corresponding Property Get procedure.
reference
Required. Used in a Property Set procedure, a variable containing the object reference used on the right side of the object reference assignment.
 
The arglist argument has the following syntax and parts:
[Optional] [ByVal | ByRef] [ParamArray] varname[( )] [As type] [= defaultvalue]
Part
Description
Optional
Optional. Keyword indicating that an argument is not required. If used, all subsequent arguments in arglist must also be optional and declared using the Optional keyword. Optional can't be used for any argument if ParamArray is used.
ByVal
Optional. Indicates that the argument is passed by value.
ByRef
Optional. Indicates that the argument is passed by reference. ByRef is the default in Visual Basic.
ParamArray
Optional. Used only as the last argument in arglist to indicate that the final argument is an Optional array of Variant elements. The ParamArray keyword allows you to provide an arbitrary number of arguments. ParamArray can't be used with ByVal, ByRef, or Optional.
varname
Required. Name of the variable representing the argument; follows standard variable naming conventions.
type
Optional. Data type of the argument passed to the procedure; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Date, String (variable-length only), Object, Variant, or a specific object type. If the parameter is not Optional, a user-defined type may also be specified.
defaultvalue
Optional. Any constant or constant expression. Valid for Optional parameters only. If the type is an Object, an explicit default value can only be Nothing.
 
 
Once youíve spent a semester or three mastering the implementation of various data structures in languages such as C++, you probably feel as though youíve earned the right to simply use a ready made, intuitively simple yet versatile data structure. Enter VBís Collection object. The Collection object provides a convenient way to refer to a related group of items as a single object. The items, or members, in a collection need only be related by the fact that they exist in the collection. Members of a collection don't have to share the same Data type.
A collection can be created the same way other objects are created. For example:
Dim X As New Collection
 

Once a collection is created, members can be added using the Add method and removed using the Remove method. Specific members can be returned from the collection using the Item method, while the entire collection can be iterated using the For Each...Next statement.

The For Each...Next statement also provides the flexibility to iterate through only the specific members of a collection that are of the same data or object type as your iterator. For example, assuming that we have defined object types Dog and Horse and that we have a collection mItemCol, we can step through it looking for objects of different types and performing the appropriate actions within a procedure as follows:
 
Dim oHorse as Horse
Dim oDog as Dog
Dim str as String
 
ëadd a carriage return / line feed to each String in the collection
For Each str in mItemCol
 str = str & vbcrlf
Next str
 
 ëfeed or walk each Dog in the collection
For Each oDog in mItemCol
 If oDog.Fiesty Then
    oDog.Walk
 ElseIf oDog.Hungry Then
    oDog.Feed Alpo
 End If
Next oDog
 
(Here weíve assumed Public or Friend Property Get procedures Fiesty and Hungry defined within the Dog class, as well as a Sub procedure Feed, which takes 1 argument)
 
ëand finally.
For Each oHorse in mItemCol
 If oHorse.Dead Then Beat oHorse
Next oHorse
 
(Here weíve assumed a Sub procedure Beat, which takes 1 argument of type Horse, Object, or Variant.)
 

 

 

 

JAVA

 
Microsoft, in their infinite wisdom, has left Java support out of Windows XP.  Primarily a political move to try to dissolve some of Sun's gains in the areas of client / server systems and to promote their .NET strategy(?), Microsoft requires a completely separate download to install Java support for XP.  This should not affect users of Microsoft Internet Explorer, but if you need to get the latest Java Virtual Machine (JVM) for Internet Explorer, the URL is: http://www.microsoft.com/java/vm/dl_vm40.htm
If for some reason, you need to get the Microsoft Java SDK ( not sure why you would want this over the Sun version but it is possible that some third party programs might require it to be installed) you can get it at: http://www.microsoft.com/java/download/dl_sdk40.htm
Keep in mind that Microsoft does not, and never will, support Java2.  Therefore, applets that use Java2 features like Swing, will not work in the Microsoft web browser.  You can get the new Netscape web browser at: http://home.netscape.com/computing/download/index.html
Netscape 6.x allows you to use Java2 technology, like Swing in your applets.  In the past, I have told people not to use Swing; however, this semester, I might be using some Swing in examples and in labs.  If you choose to not download Netscape, you are not lost, you can still use the program appletviewer, which comes with Sun's Java SDK, to view any applets that have Swing components.
  • Do not use single character variable names. This practice will irritate your grader and put them in a bad mood.
There are acceptable uses of single character variables such as loop counters or coordinates a few others. Loop counters usually start with a lowercase "i" and continue alphabetically as the nesting of loops deepens. Coordinates are usually x, y, and z Some classes, traditionally, have been represented by one character variable names, used by most programmers. An example of this is an instance of the Graphics class is generally refered to simply as g.
  • Use meaningful variable names. TxRt is not very explanitory; however, taxRate is very explanitory.
  • Do not use excessivly long variable names. The length of this_is_the_variable_for_the_tax_rate is just silly.
  • Constant values should be in ALL_CAPS:
public static final double PI=3.1415; or
public static final int MAX_VALUE=100;
Class names should use Title Case (i.e. begin with a capital letter and each change of word in the class name should be started with a capital letter) ex: public class MyClass{}
Variable names should begin with a lower case letter and then follow the rules for class names. ex: public int taxRate;
Names for Java GUI components should begin with an abreviation of the component type:
public Button btnOk;
public Label lblDescription;
You can also separate words in a variable name by using the underscore character; however, we generally do not do this for variables but typically reserve the underscore character for constants.
public static final double MAX_TAX_RATE = 0.0725;
These simple coding conventions are fairly universal. There is a formal Java Coding Convention that is used by Sun to code Java.
//********************************************************************
// Boxes.java Author: Lewis and Loftus from Software Solutions
//                    Addison Wesley
// Demonstrates the use of conditionals and loops to guide drawing.
//********************************************************************

import java.applet.Applet;
import java.awt.*;

public class Boxes extends Applet{

 //field / data area of class

  private final int NUM_BOXES = 50;
  private final int THICKNESS = 5;
  private final int MAX_SIDE = 50;
  private final int MAX_X = 350;
  private final int MAX_Y = 250;

 // method / action area of class.
  /*-----------------------------------------------------------------
   * Paints boxes of random width and height in a random location.
   * Narrow or short boxes are highlighted with a fill color.
   */-----------------------------------------------------------------
  public void paint(Graphics page){
    int x, y, width, height;

    setBackground (Color.black);

    for (int count = 0; count < NUM_BOXES; count++){
      x = (int) (Math.random() * MAX_X);
      y = (int) (Math.random() * MAX_Y);

      width = (int) (Math.random() * MAX_SIDE);
      height = (int) (Math.random() * MAX_SIDE);

      if (width <= THICKNESS) // check for narrow box{
        page.setColor (Color.yellow);
        page.fillRect (x, y, width, height);
      }
      else
        if (height <= THICKNESS) // check for short box{
          page.setColor (Color.green);
          page.fillRect (x, y, width, height);
        }
        else{
          page.setColor (Color.white);
          page.drawRect (x, y, width, height);
        }
    }
  }
}
The latest version of the Java Software Development Kit (JSDK) is available from Sun Microsystems at: http://java.sun.com/j2se/1.3/
The JSDK is Java, as defined by Sun Microsystems, the creator of Java.  The JSDK will allow students to develop Java applets and applications on their home computers.  Installation is pretty straight-forward.  Make sure to check the system hardware requirements.  Although Java2 will run on those requirements, I would say that the machine they describe is very underpowered.  My personal recommendation for Java development would be:
  • Pentium 433 or faster,
  • Minimum of 128 MB RAM
  • Windows 2000 (if you use Windows) or any distribution of Linux.
The steps in using the JSDK are as follows:
  • edit your .java source code files (easy for me to say, right?).
  • compile those .java source code files into .class files using the command line tool javac,
    •  example: javac HelloWorld.java
  • if it is an application program, execute the program using the java command,
    • example: java HelloWorld (notice the lack of a file extention)
  • if it is an applet, write a .html file and place an appropriate <applet> tag in it and then load that .html file into a web browser that supports Java 2 or use appletviewer to view the .html file.
    •  example <applet> tag:  <applet code="HelloWorld.class"></applet> (notice the .class extention)
Example .html file that can be used as a template:

 

<!-- This is an HTML comment -->
<html>
 <head>
    <title>My Web Page</title>
 </head>
 <body>
    <applet code="MyClassName.class"></applet>
    <a href="MyClassName.java">Source Code</a>
    <!--The above line is an example of how to link
        to a file in the current same directory
        that the .html file is in.
    -->
 </body>
</html>

Example Java Applet file named TestAppletFile.java

/** This is a javadoc comment.
 * It can span across lines and will terminate
 * with the next occurrence of and astrisk (*) character
 * followed immediately by a / character. These types of comments
 * may not be nested. When placed correctly, this comment will appear
 * inside the documentation produced by the javadoc command.
 **/

// This type of comment will comment out whatever follows it
// on the line.

/* This is a normal block comment that follows the same rules as a javadoc
 * comment. Its contents will not be displayed in the javadoc documentation.
 **/

// The following import statements are required by an applet file.

import java.awt.*;
import java.applet.Applet;

 // the following header defines the applet class.

  public class TestAppletFile extends Applet{
    // The following header defines the init method.

    public void init(){
      //applet initialization code goes here.
    }// end of the init method.
// The following header defines the paint method.
public void paint(Graphics g){
      // code to display graphics text and figures goes here.
    }// end of the paint method.

  }// end of the TestAppletFile class.
 
Recommended text:
         Java In A Nutshell (3rd ed.), David Flanagan, O'Reilly Press. (an excellent Java reference.)  It is over at the O'Reilly website.
 Links:
 
¸      Java 2 API Documentation:
 
¸      Sun Java Tutorial:
¸      The official Java JDK information is available at: Sun Microsystems
o       http://java.sun.com/
¸      Thinking in Java - an online book that is free. Big download but well worth it. You can get it in PDF or in HTML. I prefer the PDF file myself but, to each his own.
 
 

C++

 
Compiling:
 
If you are currently programming using Visual C++, stop. If you really want to learn how to program and understand what goes on behind the scenes (very important for understanding debugging), then begin programming on the UNIX system. Visual C++ is a great complier but hides all the underlying details of program compilation and debugging. Visual C++ assumes you already know what it is doing and it tries to make life easier by hiding this information. However, it is difficult to learn the basics of compiling and linking programs if you do not see what is going on. Furthermore, Visual C++ is not a beginner compiler. It is much more difficult for beginners to get their programs compiled on Visual C++ than to do it on the command line in UNIX. This is due to the assumption that you already know what you are doing and how to program in C++. The many hours spent in frustration with Visual C++ could be better spent learning new programming techniques . or just relaxing.
 
There are several tools in UNIX that are similar to Visual C++ and these should be avoided as well. It is much better to use a simple editor with syntax highlighting, a must for your own sanity, and either compile on the command line or use make files. If you must use Microsoft Windows you can download and install Cygwin (http://www.cygwin.com), which will give you a UNIX-like shell and programming tools for Windows. This has the advantage that whatever you write in Cygwin will most likely compile and run on the UNIX system where your project will probably be graded. Alternatively, if you insist on using Visual C++, write your own makefiles and compile using nmake.exe. The compiler is called cl.exe and the linker is link.exe.
 
A very good compiler for working on UNIX (and Cygwin) is the GNU compiler g++. You may compile and link your program in one step by typing:
 
            g++ myprog.cpp
 
This will compile, link, and write out an executable called a.out. If you use the ño option, you can tell the compiler what to name the output file:
 
            g++ -o myname myprog.cpp
 
The disadvantage to doing this is that you do not have any intermediate files. In order to debug your program using a debugger like gdb, you must have an object file. You can create and object file by using the ñc (compile only) option to g++:
 
            g++ -c myprog.cpp
 
This will create an object file called myprog.o. You can then run:
 
            g++ -o myname myprog.o
 
If you want to use a debugger with your program, you will need to compile in the debug information into the object file using the ñg option:
 
            g++ -c ñg myprog.cpp
 
Then you can open it in gdb. Even better, if you are working in the labs, you can run DDD (Data Display Debugger) and debug the program graphically. This program will show pictures of the objects in your program very similar to the way you would visualize them (or at least should be).
 
All of this mess can be put into a makefile and done in one step using make. The structure of the makefile is:
 
Label: files to include
<tab>compiler options files
 
ex:
 
myprog: myprog.o
                        g++ -o myname myprog
myprog.o: myprog.cpp myprog.h
                        g++ -c ñg myprog.cpp myprog.h
 
There are many other options that can be used with g++. Just type ìman g++î at the command line and read the options. One very important option is ñW, which displays warnings. Using ñWall will display all warning allowing you to see how your code can be interpreted differently than you may have expected.
 
 
 
C++ Debugging Tips:
 
Most beginner problems are the result of syntax errors. It is easy to forget a semi-colon in one line and get multiple errors on unrelated lines. I once forgot a semi-colon at the end of my class declaration in my header file and spent well over an hour trying to figure out the multitude of errors I received that referred to my cpp file. You must remember that the compiler sees only one big file with all the includes replaced by the file referenced. To the compiler, my header file information was right above my cpp file.
 
More complicated debugging will require a debugger. Using a graphical debugger like DDD will allow you to examine the contents of your variables as they change. In addition, you can see the address of your variables to verify that variables or objects that you expect to be the same really are the same when passed in and out of functions.
 
C++ Pointers and Functions:
 
Variables can be passed into functions by making a copy of the variable, sending a pointer to the variable location, or by passing the address of the variable (by reference). In order to understand this, we need to see how things work in memory. Ex:
 
int main()
{
            int a;
            a = 56;
            int* b;
            b = &a;
 
cout << "a is: " << a << endl;
             cout << "b is: " << b << endl;
             cout << "*b is: " << *b << endl;
             cout << "&a is: " << &a << endl;
            cout << "&b is: " << &b << endl;
return 0;
}
 
                                    Address           Memory           Name in Source
100
56
a
101
 
 
102
 
 
103
 
 
104
100
b
 
ìint aî creates a memory location for an integer (4 bytes on UNIX). 
ìa=56î puts the value 56 in the memory location assigned to ìaî. 
ìint* bî creates a memory location for an integer pointer (also 4 bytes).
ìb=&aî puts the address of ìaî in the memory location of ìbî.
 
            The output of the previous program:
a is: 56
b is: 100
*b is: 56
&a is: 100
&b is: 104
 
Simply read ì*bî as the thing that b points to. Read ì&bî as the address of b. ìbî contains the address of ìaî since it is a pointer.
 
Now we look at the parameters to functions:
 
            Declaration:
                                    void foo(int a);
 
            Call:
                                    int bar;
                                    bar = 20;
                                    foo(bar);           //variable copied
 
This will take an integer and make a copy of it for use in the function. A separate location is made in memory for the integer ìaî that is used in this function.
           
            Declaration:
                                    void foo(int* a);
 
            Call:
int bar;
bar = 20;
foo(&bar);                    //address passed and accessible by ì*aî
 
This will take the address of the integer. A location in memory is created for the pointer ìaî. In order to change the value of the variable pointed to by ìaî, you must use ì*aî. If you change ìaî, you will change the address that is stored in ìaî and ì*aî will no longer point to the same place.
 
Declaration:
                                    void foo(int& a);
 
Call:
                        int bar;
                        bar = 20;
                        foo(bar);           //passed by reference accessible by ìaî
 
This will not create a memory location but will use the address of ìaî as if the variable were created in the function. In other words, you can access and change the value of the variable passed into the function by changing ìaî itself. This is passing by reference.
 
Loops:
 
If (condition)
{}
 
While (condition)
{}
 
switch variable {
                        case value : code;
                        break;
                        case value2 : code;
                        break;
}
 
 
 
Basic Order of Operations
 
Precedence
Type
Operator
Association
1
Primary
( ) [ ] -> .
 L TO R
2
Unary
! ~ - ++ -- (TYPE) * &   size of
R TO L
3
Multiplicative
* / %
L TO R
4
Additive
+ -
L TO R
5
Shift
<<   >>
L TO R
6
Relational
< <=   > >=
L TO R
7
Equality
== =!
L TO R
8
Bitwise
&
L TO R
9
Bitwise
^
L TO R
10
Bitwise
|
L TO R
11
Logical
&&
L TO R
12
Logical
||
L TO R
13
Conditional
?:
R TO L
14
Assignment
=
R TO L
15
Comma
,
L TO R
 
 

 
Basic Linked List

 

 
 

 

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Example:

If (Headptr->Nextptr->Nextptr = = NULL)
{do something;}
 
This is an easy way to check the pointer one or two nodes in front of where you want to move, before you move there.
 
 
 
 

 

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Example:

While (Headptr->Nextptr ! = NULL)
{
       Headptr = Headptr->Nextptr; 
}
 
This will move your headptr to the last nodeptr in your linked list, which equals null.
 
 
 
 

 

 
 
 
 
 
 
 
 
 
 
 
 

 
       
 
Various Coding Examples
 
 
   
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

 
 
*** These examples were taken with permission from Lee Greenbank, a member UPE and instructor at Sierra Community College.
 

PROGRAMMING TIPS
 

1.      Start when the program is assigned.
a.    Don't wait until the night before it's due! By beginning to plan your project right away you'll better understand the project requirements, the comments and suggestions made by the professor, and the questions asked by other students. Start Now.
 
2.      Read the assignment all the way through.
a.    Read it again. Make sure you understand what you are supposed to do before you start. Halfway through your project, read the assignment again - all the way through - to make sure you're on the right track. When your project is finished, read the assignment once more to make sure you've met all the requirements.
 
3.      Plan your project. DON'T start by sitting down at a computer and typing code.
a.    Start your project by sitting down with the assignment and paper and pencil. Draw a representation of what the program looks like - the data structures, the input, the output, the relationships among different parts. Figure out what things depend on each other, which stand alone, and what data or cases you will use to test your program. Make sketches, draw pictures, or make lists - whatever works for you, but get a firm picture in your mind of what you are doing before you start to write code. Not only will this help you decide where to start, but it will serve as a guide and a reference as you proceed to write the code.
 
4.      Have a good reference book at hand.
a.    Whatever language you're using, there are many good reference books that explain concepts, give code examples, and list commonly-used libraries. It's amazing how many programmers don't want to stop to look something up because they're sure that the next compile will be correct. Five minutes looking up a principle or standard technique can save you hours of constant retrying and recompiling - and frustration!
 
5.      Write and compile your program a little bit at a time.
a.    Test frequently. It's much easier to find a bug in the last 10 lines of code you've written than in the last 100 lines.
 
6.      Don't despair when the compiler gives you many errors.
a.    Usually an error early in the code will create other errors further on. Fix the first couple of errors that the compiler lists, then compile it again.
b.   Hint: If you find no error on the line number cited by the error message, check the line before it. The error may be as simple as missing punctuation.
 
7.      Use function stubs.
a.    When writing a larger project, write your function headers or method declarations with empty bodies and compile your project to see that the structure works. Once your program compiles, go back and write one piece at a time. This is the incremental build method.
 
8.      Try a different compiler if you get stuck trying to find an error.
a.    Different compilers give different error messages or find different problems. For example, when using C++ the "CC" compiler will not tell you about an uninitialized pointer, but the "g++" compiler will.
 
9.      Learn to use a debugging program before you need it.
a.    When you need to use a debugger, you probably won't have time to stop and figure out how it works. Running through a debugger tutorial now will prepare you for using it when that mystery bug shows up the night before your program is due. To use the school Unix system debugger for C++, type "help debug" at the system prompt.
 
10. Insert print statements in your code to help isolate a problem location.
a.    Sometimes it's useful to know the value of a variable before and after a calculation; when a program is entering into, inside of, or returning from a function or method; or to confirm that a pointer points to what you expect it to.
 
 
Before getting help.
 
For Programming:
 
¸      Check to see if all of your braces match up.
 
¸      Check your upper and lower cases.
 
¸      Check your spelling.
 
¸      Check syntax (remember what language your in)
 
¸      Step through your code.
 
 
¸      Be careful with slashes:
o       Forward (/)on Unix
o       Backward (\)on Microsoft
 
For Technical Support:
 
¸      Check all of your plugs and wires are plugged in.
 
¸      Shut down your computer and restart.