Department of Computer Science   

   Dr. Donald Yessick

csci140lab csci170 csci220 csci370 csci399

Research Interest: My dissertation focused on rapid prototyping of domain specific languages and I have more recently developed interests in the field of robotics and embedded systems. I have developed and explore interesting algorithms for Selected interelated graph problems, (vertex cover, independent set, maximum clique). More recently I have been focused on the rising complexity of human-computer interfaces. Specifically the challenges programmers face in developing intuitive systems. I would like to further explore and compare the merits of Java as an educational languages. And I am continually exploring the perverted world of HTML and CSS. [ more ]


Teaching Statement: It is important to encourage exploring beyond instruction. Students must learn to ask questions before thay can provide real answers and learning encompasses more than regurgitation, so students need to creatively apply new knowledge to novel problems. Student-teacher dialogs never cease; the end of class only marks the end of formal instruction; the student-teacher relationship remains open. In the end, I am successful as a teacher, when I begin to learn from my students. [ more ]


CSCI 140L-01 Introduction to Algorithmic Design I Laboratory

Meeting: TTH 2:00 p.m. - 3:15 p.m. in CSCC 129
Corequisite: CSCI 140
Catalog Description: Laboratory demonstrates the topics and principles presented in the lecture.


Lab 0 - Getting Started Lab 1 - Object-Oriented Programming Concepts Lab 2 - Primitives and Strings Lab 3 - Operators Lab 4 - Calculations
Lab 5 - Graphics Lab 6 - Graphics Lab 7 - Graphics 2D Lab 8 - COI Lab 9 - Catch up day
Lab 10 - Java2D Rotation Effect Lab 11 - Scanner, Files, FileDialog/JFileChooser, If-Else, Console Lab 12 - File Dialog, If-Else Lab 13 - BlueScreenTV (Simulation of a 1952 Panasonic TV) Lab 14 - The Monte Carlo method of Estimating π
Lab 15 - CannonBall Lab 15 - Continue CannonBall Lab 16 - Loops Lab 17 - printf Lab 18 - TBA Tuesday
Lab 19 - TBA Tuesday Lab 20 - TBA Thursday Lab 21 - TBA Tuesday Lab 22 - TBA Thursday Lab 23 - TBA Tuesday

Syllabus

Glossery of Error Messages


Lab - General Instructions

Generally in each lab you will be asked to write one or more java programs.

/*
 * 	Program 1
 *	CSCI 140lab-01
 *	
 *	Author: Polly Programmer
 *	Due: June 1, 2010
 *	Last Revised: January 1, 2015
 *
 *	A description of the problem goes here.
*/


import java.blah.blahdy.BlahBlah;

public static final int BLAH_CONSTANT = 10 ;		//  The number of blah days in the month

public static void main( String[]  args)
{
      int firstNum;			// The first occurrence of blah.
      int secondNum;			//  The second occurrence of blah.

     //  Compute the average number of blah days per decade.
     if ( firstNum > 0 )
     {
            code here;
            code here;
      }
      else
      {
            code here;		// comment here if needed
            code here;		// you should not need to comment every line of code!
       }


       // Input the list of blah days for last decade from file blah.dat
       while( someCondition)
       {

	code here;
	code here;
       }

}

At the end of each lab you are requested to attach your program to an email addressed to dyessick@gmail.com and cc (carbon-copy) your coastal email address with a subject line that reads csci140labN (where N is the number of the lab).

Save all of your labs. At the end of the year you are asked to submit your collection of labs as a portfoilio. If at the end of the day you lab is not completed you must submit via email your lab in its current state (you may attempt to finish it that day) but you must complete the lab for credit in your portfolio.


Lab 17 - printf

http://java.sun.com/javase/6/docs/api/java/util/Formatter.html#syntax

1. Review http://java.sun.com/javase/6/docs/api/java/util/Formatter.html#syntax and prepare a program that illustrates useful examples. By useful I mean to examples using types you are familiar with or examples you think you are most likely to use later.

2. None of printf is required, everything can be done via println and String concatonation but printf's formatting can make life easier. Consider a report in which you need to generate a column of figures.

	     5.67
	    24.43
	   236.2311
  	 53427.1223
	  1448.4331	
	    29.00

Standard practice is to align the decimal point. Write a program to print these numbers (or 6 numbers randomly generated or input at runtime) such that the decimal point aligns. Do this with and without printf.





Lab 16 - Loops

Lab16.java

In Lab16.java you'll find stubs for some simple looping exersizes. Complete each function and test it.

You'll also see an example of measuring processing time. Compare an iterative solution for sum of series to the direct method.











Lab 15 - CannonBall

Lab15.java (extends CannonBall)
CannonBall.java (You need this but all your work is should be in Lab15.java)

Think 9.8meters/sec2

Just make the cannonball fly using using a physics mdel. Fill in the provided methods in Lab 15.java and the cannonball will fly

Of course you'll have to scale your values to keep the cannonball on the screen.

And make sure the cannonball starts at 350,350 at t=0

The methods getX(time)And getY(time) are called from t=0 to t=110)





Lab 14 - The Monte Carlo method of Estimating π

Lab14.java (extends PiDarts)
PiDarts.java (You need this but all your work is should be in Lab14.java)

A Monte Carlo method is any algorithm that uses a random number generator (like a roulette wheel) to learn about non-random things. For example, we can use random numbers to estimate the value of π. Imagine that we have a dartboard on a square surface.

If we randomly throw darts at the dartboard, some will hit the target and others strike the square (we'll ignore any that miss entirely). If we count up the darts, the ratio of darts hitting the dartboard to darts hitting the square will approach the ratio of the areas of the circle to the the square.

If we assume the radius of the circle is 1 unit; (the diameter of the circle (or length of a square side) will then be 2 units), the area of the square will be 22 = 4. The area of the circle will be π * 12 or π

And so the ratio of circle area to square area will be π to 4. That is to say, the probability of hitting the circle with a dart is π / 4. Put yet another way, if you calculate the ratio darts hitting the target to the number of darts thrown and multiply the answer by 4, you'll get an estimate of the value of pi.

Modify the program to throw a number of random darts and print the resulting estimate of π rounded to 4 decimal places. How many darts must you throw to approximate π reasonably accurately?


Lab 13 - BlueScreenTV

For today you'll need the following two files:
Lab13.java
BlueScreenTV.java

Today we'll animate and simulate a 1952 Panasonic T.V.

Your instructions are in Lab13.java. I've hidden the critical and complex portions of this task in BlueScreenTV. What's left for you in Lab13.java will give you some practice working with if statements, classes, inheritance and graphics.

There's no need for you to examine BlueScreenTV.java but I'll be happy to answer any questions you have later regarding the program.

/**
 * @author Donald Yessick
 *
 */
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
/**
 * Lab 13 describes methods and attributes inherited from BlueScreenTV 
 * You need to provide implementations of these methods to override the 
 * BlueScreenTV definitions
 */
public class Lab13 extends BlueScreenTV {
	/**
	 *  protected boolean isPowerOn
	 *  true = on, false is off
	 * 	defaults to true; 
	 * 
	 * 	protected int channel = 1; 
	 *  we have channel 1 and channel 2
	 *  defaults to channel 1
	 */
	
	/**
	 * toString() This is called when the program needs a string TV
	 * for example as a Window title. BlueScreenTV indicated channel or power status
	 */
	public String toString(){
		return "replace this meaningless string";		
	}
	/**
	 * This is called when the user clicks the mouse
	 * mouseEvent has many useful methods. Try printing getX() and getY()
	 * I started it for you. by showing you how to call it.
	 */
	public void mouseClicked(MouseEvent mouseEvent) {
		this.getGraphics().drawString("mouseEvent.getX(), mouseEvent.getY()", mouseEvent.getX(), mouseEvent.getY());
	}
	/**
	 * define what happens (state change) when the user presses the power button
	 */
	public void pushPowerButton() {
		// toggle protected boolean isPowerOn
	}
	/**
	 * define what happens (state change) when the user changes channels
	 */
	public void changeChannel() {
		// toggle protected int channel
	}
	/**
	 * this is called when the user starts the program
	 * @param args
	 */
	public static void main(String[] args) {
		BlueScreenTV.lab13(new Lab13());
	}
	/**
	 * this is called when the window refreshes every 33 millisecs
	 * it's painting over the mouse message -- how can you fix that?
	 * perhaps you could move the drawing to here
	 */
	public void paintComponent(Graphics oldGraphics) {
		Graphics2D g = (Graphics2D) oldGraphics;
		super.paintComponent(g);
	}
}

Toggle values come up in programming a lot. It's important to realize there's always more than one way to do things. Below you'll find some different ways of toggling between two values. Some are better than others and believe it or not, the lists are incomplete. Because of the many different ways to accomplish the same task, writing a program is a lot like writing a paper. No two people writing about the same subject will write the same paragraph (even the structure will vary). Programs are as unique as the individuals who write them. Implementation details are a matter of technique, and style.

Consider a boolean toggle value
	//1 Explicit 
	if (isPowerOn==false)
		isPowerOn=true; //toggle value if isPowerOn was false
	else 
		isPowerOn = false;//toggle value if isPowerOn was true

	//2 semiExplicit
	if (!isPowerOn) //it's a boolean -- use it!
		isPowerOn=true; //toggles value to true
	else 
		isPowerOn = !isPowerOn; //toggles value to the false condition

	
	//3 using logic to toggle power 
	isPowerOn = isPowerOn==false; //toggles value
	isPowerOn = isPowerOn!=true; //also toggles value
	isPowerOn = !(isPowerOn==true); //toggle value
	
	//4	using an immediate if
	isPowerOn = (isPowerOn)?false:true;

	//5 simple negation
	isPowerOn = !isPowerOn; //toggle power	

Consider an integer value toggling between 1 and 2
	//1 & 2 toggle channel via expression		
	channel = 2-(channel-1);
	channel = 2-(channel)+1;

	//3 both of the above can be simplified
	channel = 3-channel;

	//4 test then set
	if (channel == 1)
		channel = 2;
	else if (channel == 2) //this test is not needed
		channel =1;

	//5 a general method  -- 2 here is the number of channels -- replace 2 with N
	//where N is the number of channels
	if (channel == 2)
		channel = 1;
	else 
		channel++;
		
	//6 another  general method uses modulus -- 2 here is the number of channels  -- replace 2 with N
	//where N is the number of channels
	channel = channel %2 + 1;



Lab 12 - File Dialog, If-Else

Examine FileDialogDemo.java which shows various file dialogs at work.

Reference reading for today


Lab 11 - Scanner, Files, File Dialog, If-Else

Examine Lab9.java which shows a scanner at work. The window is superfluous, the console is where the action is at.

Browse the scanner api.

The Scanner class is relatively new. It was not around as recently as 2005. All of the functionality of the scanner was formerly available through a combination of:

By combining these classes into the scanner, io operations are greatly simplified. For future reference, it is important to keep in mind that there are lower level routines which are combined to give us a relatively simple interface for io. Often examples on the web rely on these older methods. Indeed, programmers, like everybody else often loathe change. Many have not discovered the scanner io class and may instead be relying on their knowledge of the underlying architecture.

Today. Create a program, Lab11, that uses a file dialog to find a text file (or java file) and opens the file using a scanner. Use next() and nextLine() to write the file to the screen. Correct any problems with whitespace. (a single space or new line character will suffice).

Next create a text file full of numbers (whole and real). Use nextInt() and nextDouble() to read this file.

File processing can be helped using helper methods, hasNext(), hasNextInt(), etc.... Create a file with mixed contrent and use an if/else statement to control the processing of a file.

Java 6 has introduced a new console class. The console has many *neat* features such password mode. Use this to retrieve a password. Use an ifstatement to test whether the entered password matches the phrase "secret!42" and print an appropraite message using console's output methods.

Recommended reading on files: http://java.sun.com/javase/6/docs/technotes/guides/io/io-maj.html http://java.sun.com/javase/6/docs/api/java/io/File.html http://java.sun.com/javase/6/docs/api/java/awt/FileDialog.html http://java.sun.com/docs/books/tutorial/uiswing/components/filechooser.html

           FileOpenService fos = null;
           FileContents fileContents = null;

            try {
                	fos = (FileOpenService)ServiceManager.
                          lookup("javax.jnlp.FileOpenService"); 
			fileContents = fos.openFileDialog(null, null);
			fileContents.getName()
                
            } catch (Exception e) {
 			e.printStackTrace();//where?
			System.out.println(e);//the exception
                }
            }

Java2D Rotation Effect

Examine Lab8.java We will spend the day discussing the architecture of this class, the rotation effect using affine transforms, Java2D, and a timer. Incorporate these the rotation into one or more of the objects that you are developing. (Ideas, make dials spin, make tires rotate, make a rotation effect around an antena, etc...).


Lab 9 - Another Catch Up Day

I noticed many were still stuck on lab 3 so another day to catch up is in order. If you have completed lab 3 create another graphics object. An additional object and graphics is due for the portfolio.


Lab 8 - COI

If you are not attending COI during this time you may use this time to finish any previous lab assignment.


Lab 7 - Graphics 2D

Today we will play with more graphics. In Lab 1 you created 2 or 3 random "objects." In labs 5-6 you drew the objects with java's graphics library. Today we are going to redraw them using java's 2d graphics library.

For next time read over (all thgree links have exactly the same info)
book form, http://www.corewebprogramming.com/PDF/ch10.pdf
web form html version with links to code samples
slideshow form pdf slideshow

Last time we looked at basic graphics. Today we'll explore more complex operations supported by Java's Graphics 2D library which was added in Java 2 (Java is now at version 6 but they still call it 2).

Key idea: Java 2 must be backwards compatable so how do we add new capabilities without destroying legacy applications. Solution for Java 2D: require a downcast to the new library. This is which you will see

public void paintComponent(Graphics g) {
	Graphics2D g2 = (Graphics2D) g;
existing (legacy) applications would be confused if the parameter was changed so the requirement to downcast the graphics context was required to gain access to the new advanced graphics capabilities. <\p>

Todays assignment: Create an updated verion of your objects using Graphics 2D and inheritance. More about inheritance will be explained later. For now let us simply say do this

class JBottle extends Bottle {
   public void PaintComponent(Graphics g){
	//super.paintComponent(g); //uncomment this line and see what happens
	Graphics2D g2 = (Graphics2D) g;   
	//..drawing code will go here
  	java.awt.geom.Ellipse2D.Double circle =
    		new java.awt.geom.Ellipse2D.Double(10, 10, 350, 350);
	g2d.fill(circle);
   }
}

and JBottle is a Bottle too. Of course instead of Bottle you need to use the class that you defined in earlier labs.


Lab 5 - Graphics

Today w will play with graphics. In Lab 1 you created 2 or 3 random "objects." Today we are going to take them to the next level and draw them in a window.

Graphics in Java or any language are not trivial but Java provides excellent library suport and you can do a lot with the basics. This presentation goes well beyong the basics, but should give you a glimpse of what is possible. Don't fret if you do not understand most of the presentation. We will start with a smaller example and you can work your way up to the complex issues at your leisure.

So how do we use graphics in a Java program?. The first step is having a window and we also need to have a place to draw. Back in lab 1 you created a random object (You should have created 2 or 3 actually). Pick one to illustrate. Open the class in your editor and add the following to the code in the appropriate places. <\p>

		/* add these to the import section, we'll need them later */
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import javax.swing.JComponent;

		/* add extends JComponent after your class name */
public class .... extends JComponent {

		/* add the method paintComponent(Graphics g) with a stubb */
    public void paintComponent(Graphics g) 
    { //empty body for now
    }

Now we can create our Lab 5 java file I have posted an example below but you need to replace class Bottle with the name of the class you modified in the first step. You can modify my code to save time.

import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JFrame;

public class Lab5 {

    public static void main(String[] args) {
		//a basic set up. Examples will vary.
        Bottle bottle = new Bottle();
        JFrame win = new JFrame("Title bar = "+bottle.toString()); //add a title to the window
        win.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // annoying but neccessary
        win.setBounds(50,50,600,500);//50 pixels from top left, width=400, height=500
        win.setContentPane(bottle); //adds a paintable JComponent to the window
        win.setVisible(true); //opens the window and indirectly triggers a automagic call to paint
    }
}

now it's time to draw our picture. Here's my example. Experiment until you have a picture that represents your object.

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import javax.swing.JComponent;



public class Bottle extends JComponent {
    int oz = 12;
    boolean empty = false;
    String content = "Soda";
    
    public void paintComponent(Graphics g) {
        /*
         * use blue to fill the window
         */
        g.setColor(Color.BLUE.darker().darker());//A color two stages darker
        g.fillRect(0,0,600,500); //fill the screen
        
        /*
         * define the basic bottle shape (squareish here)
         */
        g.setColor(Color.orange);//predefined colors defined in upper and lower case
        g.fillRect(50,50,150,400);  
        /*
         * a overlay in the background color gives the bottle it's more refined shape
         */
        g.setColor(Color.BLUE.darker().darker());//A color two stages darker
        g.fillOval(2,0,95,195);   
        g.fillOval(152,0,95,195);   
        
        /*
         * create the bottle cap
         */
        g.setColor(Color.WHITE); //got renamed to coding conventions     
        g.fillRect(100,25,50,25);
        
        /*
         * create a label for my bottle
         */
        g.setColor(new Color(200,200,50)); //red(R) green(G) blue(B) values (VIOLET=R+B, CYAN=B+G YELLOW=R+G       
        g.fillOval(55,200,140,140);   
        
        /* 
         * write on the label
         */
        g.setColor(Color.RED);//predefined color
        g.drawString(this.toString(), 65,250);
        /*
         * more text at the bottom
         */
        g.setColor(Color.BLACK);//predefined color
        g.drawString(""+oz+" fluid oz", 145,440);
        
        /*
         * this bottle is recyclable
         * the unicode /u00a2 is the cent sign 
         * we use a big font here
         */
        g.setColor(Color.BLACK);//predefined color
        g.drawString("deposit ", 75,420);
        g.setColor(Color.GREEN.darker().darker());//predefined color
        g.setFont(new Font( "Serif", Font.BOLD + Font.ITALIC, 42 ) );
        g.drawString("5\u00a2", 125,420);
        g.setColor(new Color(190,0,0));
        g.setFont(new Font( "Serif", Font.BOLD + Font.ITALIC, 42 ) );
        g.drawString(content,85,300);
        
    }
    //accessor methods
    //setter methods
    public void setOz(int size){
        oz = size;
    }
    
    //getter methods
    public int getOz(){
        return oz;
    }
    
    //other methods
    boolean isEmpty() {
        return empty;
    }
    void drink () {
        empty = true;
    }
    void fill (String stuff) {
        empty = false;
        content = stuff;
    }
    public String toString() {
        if (!empty) 
            return ""+oz+" oz bottle of "+content;
        return ""+oz+" oz empty bottle";
    }
}

Don't forget to email in your code to dyessick@gmail.com.


Lab 4 - Calculations

Last time we looked at basic operators and methods. Today we want to build on that and create useful numeric calculations. I define useful liberally. Your milage may vary.

As always create a java class file, this time call it called Lab4. It will need a main method with the usual syntax. The main will have to have statements executing (perhaps printing results will be useful) the various functions we write today.

You should look over Java's Math library. We'll try to introduce some bits and pieces today. Math API

  1. Gauss's Formula. A sum of the numbers from 1 to N can be computed by the formula

                               n ( n + 1)
                      sum =   -----------
                                    2
    
    write a function that computes this value. Your function will look something like this:
    	/**
    	* sumSeries computes the sum of the numbers from 1 to n using Gauss's formula
    	* @param n the last number in the series
    	*/
    	public static int sumSeries(int n)
    	{
    		int sum;
    		//sum = ...; //do your computation here
    		return sum;
    	}
    

  2. Quadratic Formula For this you'll need to use the Math library functions. Assume all variables are float variables and compute both solutions for the quadratic formula:

    	                 _______________
    		-b +/- \/ b^2 - 4ac
    		--------------------------
    			2a
    
    A better picture and explanation can be found here
    	/**
    	* firstQuadraticRoot computes the 1st quadratic solution of the standard quadratic equation form: ax^2 + bx + c = 0
    	* @param a from the standard quadratic equation: ax^2 + bx + c = 0
    	* @param b from the standard quadratic equation: ax^2 + bx + c = 0
    	* @param c from the standard quadratic equation: ax^2 + bx + c = 0
    	*/
    	public static float firstQuadraticRoot(float a, float b, float c)
    	{
    		float root;
    		//root = ...; //do your computation here
    		return root;
    	}
    	/**
    	* secondQuadraticRoot computes the 2nd quadratic solution of the standard quadratic equation form: ax^2 + bx + c = 0
    	* @param a from the standard quadratic equation: ax^2 + bx + c = 0
    	* @param b from the standard quadratic equation: ax^2 + bx + c = 0
    	* @param c from the standard quadratic equation: ax^2 + bx + c = 0
    	*/
    	public static float secondQuadraticRoot(float a, float b, float c)
    	{
    		float root;
    		//root = ...; //do your computation here
    		return root;
    	}
    

  3. Circle Write a function that prints the area and circumference of a circle given the (int) diameter. π is defined in the Math class.

  4. Radius from circumference Write a function that computes the radius of a circle given the circumferene. Use it to demonstrate a well known fact that adding 6 inches to a string that encircled the globe (or a beachball) has the same effect on the circles radius as would 6 inches added to a string around a basketball or even a golfball.

  5. reverse a number We're going to write a

    	public static int reverse(int num) {
    		//discussion of content follows
    	}
    
    that takes a number and reverses the digits (e.g. reverse(321) will give you 123). We'll use the mystical % operator to help us. For now let us assume all input will be positive numbers. The key step in our algorithm will be to discover and prune the last digit from our input number. The % and / operators come to our rescue.
    		int digit = num % 10;  //the remainder of num/10 will be the last digit
    		int prune = num / 10;  //dividing by 10 truncates the last digit
    
    now we need to compute and build our reversed number. The digit we just pruned will be the first digit or our new number.
    		int result = digit;
    
    We can repeat the above two statements until all the digits have been "pruned" from our input value. A simple while loop gives us the ability to repeat statements until a condition is met.
    		while (prune > 0) // if there are more digits   <<<--------------------+
    		{     //prune and build the new number                                 |
    			digit = prune % 10; //pick of the last digit                     |
    			result *=  10;	  //shift our answer left	                 |
    			result +=  digit; //add the last digit                           |
    			prune = prune / 10; //prune the digit from our original number   |
    		}			  //repeat loop as neccessary >>>--------------------+
    


Lab 3 - Operators

For today you were asked to read:

Operator precedence refers to the order in which math functions are carried out. Consider the statement x = 200 - 100 / 10; Without understanding rules of precedence you might expect this to evaluate to 10 (via (200 - 100) / 10 ) and be surprised when the computer gives you the correct result of 190 (since division has higher precedence than subtraction the expression is evaluated as 200 - (100/10)). As this simple example shows the results can be dramatic. If you are ever in doubt about the precedence rules you can always add parenthesis to clarify. Expressions within parenthesis are always at higher precedence.

For lab3 you will need to create a class file (Lab3.java) that has a main method declared as we have done previously. At the end of lab3 you should attach and email your completed lab assignment to dyessick@gmail.com with the subject line "csci140lab03" (and don't forget to cc to your coastal account).

Examine the following code. Predict the values (compute by hand) and then write a Java program to test your predictions. Using parenthesis to write the expressions in an equivelent meaning. Did any values surprise you?

	public static void intCalculations(){
		//declare
		int a,b,c,d,e;
		int x,y,z;
		//init
		a = 5;
		b = 10;
		c = 50;
		d = 100;
		e = 250;
		//eval using precedence
		x = e + d * a - d / b;
		y = a * b * c + d - e;
		z = e / d - c / b + a;
		//print result
		System.out.print( "x=" + x + "\ty=" + y + "\tz=" + z + "\n" );
		//eval using parenthesis
		x = ( e + d * a - d / b );
		y = ( a * b * c + d - e );
		z = ( e / d - c / b + a );
		//print result for comparison
		System.out.println( "x=" + x + "\ty=" + y + "\tz=" + z + "\n" );

Repeat the experiment with float rather than int values. Why are the results different? Try it again with floats only for the results, and again with floats for the operands only. Make sure you can explain differences in each run. Java may give you an error or a warning when you assign ints to floats or visa versa. Your instructor will help you through this problem.

	public static void floatCalculations() {...} //make all variables floats
	public static void floatCalculations2() {...} //let just x,y, and z be floats
	public static void floatCalculations3() {...} //let just operands a,b,c,d, and e be floats

Two operators deserve special attention. The ++ and -- operators come in two flavors: postfix and prefix. The following program can help you understand these operations.

	static public void demoOperatorsPrefixPostfix(){
		int a;
		a = 1;
		//postfix
		System.out.println("postfix before a=" + a);
		System.out.println("postfix use a=" + a++); //note a++
		System.out.println("postfix after a=" + a);

		a = 1;
		//prefix
		System.out.println("prefix before a=" + a);
		System.out.println("prefix use a=" + ++a); //note ++a
		System.out.println("prefix after a=" + a);
	}

Java has a lot of assignment operators. Assignment is used to store a value in a variable and we've been doing that in our programs already. Certain assignments are so common that programmers have shortcuts. Add print statements to the following block to echo the results,

	static public void demoOperatorsAssingment(){
		int a = 100;

		//the following all increment a by 1
		a = a + 1;
		a += 1;
		a++; //use first
		++a; //increment first

		//the following all decrement a by 1
		a = a - 1;
		a -= 1;
		a--; //use first
		--a; //decrement first

		//the following all multiply by 8
		a = a * 8;
		a *= 8;
		a = a << 3; //bitwise shift left
		a<<=3; 

		//the following all divide by 8
		a = a / 8;
		a /= 8;
		a = a >> 3; //bitwise shift right
		a>>=3; 
	}

The % operator in Java is the remainder function. (note in most languages this is the modulus operator which is only for positive input values). The % operator is defined for integer types only. Note the return type in the following functions (see the change from void to int). The following functions return a value which can be assigned to a variable or used in an expression. (e.g. int x = remainder (10, remainder2 (15, 12));)

	static public int remainder(int a, int b){
		return a % b;
	}
	static public int remainder2(int a, int b){
		int divisor = a / b;
		int remainder = a - (divisor * b);
		return remainder;
	}
Write a function to compares the result f these two functions. If any difference exists, changes function2 so that the functions return the same value for all inputs. Use the equality operator to tests. e.g.:
int val1 = 8;
int val2 = 5;
int r1 = remainder (val1, val2);
int r2 = remainder2(val1, val2);
boolean test = (r1==r2); //true or false
System.out.println("The functions are the same: " + test);
Make sure to test the result several times (see if you can streamlined the above snippit) using a variety of test values.


Lab 2 - Primitives and Strings

Java allows two types of variables. Objects and primitives. Primitives are NOT objects. This can be confusing. The distinction is a little tricky, but in the end, it refers to the way that the elemets are stored in memory. One can think of primitives as the building bricks. Virtually all objects will boil down to primitives if you drill deeper and deeper into the objects. For example the bycycle class that we examined in the previous lab, was an object composed of three primitives: gear, cadence and speed.

The eight primitive data types are: byte, short, int, long, float, double, boolean, and char. The http://java.sun.com/javase/6/docs/api/java/lang/String.html class represents character strings. Strings are objects.

The eight primitives and the class String represent java's "built-in" types (also arrays but we'll come back to this later). Everything else is composition.

Java is a "strongly typed" language. This is a feature of most compiled (vs translated) languages while a feature of scripting languages is that they are softly typed. In a softly typed language one does not have to specify the type of a variable. One may store any value and the system will do the right thing.

In a strongly typed system we are required to declare variables and then use them strickly as declared. One cannot store a string (e.g "Mr Smith") in an variable declared to be an integer. Stronglt typed languages tend to execute faster than softly typed languages and they tend to have fewer bugs in the program code. Soft typed languages often have a faster development time (no planning is required) and are the tool of choice for, what I like to call, "quick and dirty" programming. Scientific applications and other "heavy duty" or mission critical application development is well suited for compiled languages.

From the Java Tutorial pages read these pages:

For now you can skip the discussion of arrays. That's an advanced topic we'll revisit later in the semester.

Also visit this page (it may not make complete sense for you today): String API

Revisit the classes that we ceated in lab1. Let's make a few changes.

Add the following methods:

public String toString(){
	return "Hello World";
}
public void print(){
	System.out.println("Hello world " + this);
}

Your instructor will give you instructions to customize the the above methods. You will need to modify or create a class with a main that will test (call) these methods.

Examine the code below:

import java.util.StringTokenizer; 

public class StringTokenizerTester 
{ 
    public static void main(String[] args) 
    { 
       String sentence = "Mary had a little lamb."; 
       StringTokenizer mystery = new StringTokenizer(sentence); 
       System.out.println(mystery.countTokens()); 
       System.out.println(mystery.nextToken()); 
       System.out.println(mystery.nextToken());    
    } 
} 

Go to http://java.sun.com/javase/6/docs/api/index.html and find out what the methods countTokens and nextToken of the StringTokenizer class do. Can you predict the output of the above program? Compile and run the above program and see if the result matches your prediction.

You will submit your modified classes to dyessick@gmail.com. In the subject line put csci140lab02. In your message include a brief description of the objects you defined and you name. CC to your coastal account.

Make sure you can answer the questions here: http://java.sun.com/docs/books/tutorial/java/nutsandbolts/QandE/questions_variables.html

Next time we'll look at operators. For Tuesday read:


Lab 1 - Object-Oriented Programming Concepts

Step 1: Read this page. Identify 2-3 objects and describe the state/attributes and "behaviors" associated with these objects.

Step 2: At the bottom of the page use the "http://java.sun.com/docs/books/tutorial/java/concepts/class.html">next link to find an example bicycle implementation and demonstration of use. Using the Bicycle and BicycleDemo as a guide, create simple classes for the objects you defined in step 1.

Step 3: Compare the objects you created with one or more students surrounding you. Suggest an improvement and implement an improvement.

Step 4: Save your work. You will use the classes you created today in our future labs.

Step 5: Email a copy of your source files to dyessick@gmail.com. In the subject line put csci140lab01. In your message include a brief description of the objects you defined and you name. CC to your coastal account.

For Thursday read the rest of section Object-Oriented Programming Concepts from Trail: Learning the Java Language You should endeavor to be able to answer these questions about object-oriented programming concepts.


Lab 0 - Getting Started

Install JCreator and create and run a "Hello World" java program. The following may be helpful in answering questions that may arise. You should make sure you can find these resources outside of the lab. It will save you countless hours.

The Java Tutorials are practical guides for programmers who want to use the Java programming language to create applications. They include hundreds of complete, working examples, and dozens of lessons. Groups of related lessons are organized into "trails". Some links into the getting stated trail:

Read A Closer Look at the "Hello World!" Application We will revisit many of these points.

Make sure you can answer these questions.


Contact Me


The views and opinions expressed in this page are strictly those of the page author. The
contents of this page have not been reviewed or approved by Coastal Carolina University.

© 2008 Donald Yessick.