Thursday, December 16, 2010

FINAL EXAM CS36O

FINAL EXAM CS36O
December 16, 2010




import java.awt.Point;

import java.awt.Graphics;

import java.awt.event.MouseEvent;

import java.awt.event.MouseMotionAdapter;

import javax.swing.JPanel;

public class PaintPanel extends JPanel
{
private int pointCount = 0; //count number of points

//array of 10000 java.awt.Point references
private Point[] points = new Point[10000];

//set up GUI and register mouse event handler
public PaintPanel()
{
//handle frame mouse motion event
addMouseMotionListener(

new MouseMotionAdapter() //anonymous inner class
{
//store drag coordinates and repaint
public void mouseDragged( MouseEvent event )
{
if( pointCount < points.length )
{
points[ pointCount ] = event.getPoint(); //find point
pointCount++; //increment number of points in array
repaint(); //repaint JFrame
} //end if
} //end method mouseDragged
} //end anonymous inner class
); //end call to addMouseMotionListener
} //end PaintPanel constructor

//draw ovals in a 4-by-4 bounding box at expecified locations on window
public void paintComponent( Graphics g )
{
super.paintComponent( g ); //clears drawing area

//draw all points in array

for( int i = 0; i < pointCount; i++ )
g.fillOval( points[ i ].x, points[i].y, 4, 4 );
} //end method paintComponent
} //end class PaintPanel







import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Painter
{
public static void main( String[] args )
{
//create JFrame
JFrame application = new JFrame( "A simple paint program." );

PaintPanel paintPanel = new PaintPanel(); //create paint panel
application.add( paintPanel, BorderLayout.CENTER); //in center

//create a label and place it in SOUTH of BorderLayout
application.add( new JLabel( "Drag the mouse to draw" ),
BorderLayout.SOUTH );

application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
application.setSize(400, 200); //set frame size
application.setVisible( true ); //display frame
} //end main
} //end class Painter

Thursday, December 2, 2010

Assignment #20 CS360

Assignment #20
"Wildcard Test"
12-02-10




//WildcardTest.java

//Wildcard test program.

import java.util.ArrayList;

public class WildcardTest

{
public static void main( String[] args )

{
//create, initialize and output ArrayList of integers, then
//display total of the elements

Integer[] integers = { 1, 2, 3, 4, 5 };

ArrayList integerList = new ArrayList ();

//insert elements in intergerList
for( Integer element : integers )
integerList.add( element );

System.out.printf( "integerList contains: %s\n", integerList );
System.out.printf( "Total of the elements in integerList: %.0f\n\n",
sum( integerList ) );

//create, initialize and output ArrayList of Doubles, then
//display total of the elements
Double[] doubles = {1.1, 3.3, 5.5 };
ArrayList< Double > doubleList = new ArrayList< Double >();

//Insert Elements in doubleList
for( Double element : doubles )
doubleList.add( element );

System.out.printf( "doubleList contains:%s\n", doubleList );
System.out.printf( "Total of the elements in doubleList: %.1f\n\n",
sum( doubleList ));

//create, initialize and output ArrayList of Numbers containing
//both Integers and Doubles, then display total of the elements
Number[] numbers = {1, 2.4, 3, 4.1 }; //Integers and Doubles
ArrayList< Number > numberList = new ArrayList< Number >();

//Insert elements in numberList
for( Number element : numbers )
numberList.add( element );

System.out.printf( "numberList contains: %s\n", numberList );
System.out.printf( "Total of the elements in numberList: %.1f\n",
sum( numberList));

}//end main

//total the elements; using a wildcard in the ArrayList parameter
public static double sum( ArrayList< ? extends Number > list )
{
double total = 0; //initialize total

//calculate sum
for( Number element : list )
total += element.doubleValue();

return total;

}//end method sum
}//end class WildcardTest

Thursday, November 11, 2010

Assignment #18 CS360

Assignment #18
"MenuFrame & MenuTest"
11-11-10







// Fig. 22.5: Menu Frame.java
// Demostrating menus.

import java.awt.Color;
import java.awt.Font;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import javax.swing.JFrame;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.ButtonGroup;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JMenuBar;

public class MenuFrame extends JFrame
{
private final Color colorValues[] =
{ Color.BLACK, Color.BLUE, Color.RED, Color.GREEN };
private JRadioButtonMenuItem colorItems[]; //color menu items
private JRadioButtonMenuItem fonts[]; //font menu items
private JCheckBoxMenuItem styleItems[]; //font style menu items
private JLabel displayJLabel; //displays sample text
private ButtonGroup fontButtonGroup; //manages font menu items
private ButtonGroup colorButtonGroup; //manages color menu items
private int style; //used to create style for font

//no-argument constructor set up GUI
public MenuFrame()
{
super(" Usiing JMenus" );

JMenu fileMenu = new JMenu( "File" ); //create file menu
fileMenu.setMnemonic( 'F' ); //set mnemonic to F

// Create About... menu item
JMenuItem aboutItem = new JMenuItem( "About..." );
aboutItem.setMnemonic( 'A' ); //set mnemonic to A
fileMenu.add( aboutItem ); //add about item to file menu
aboutItem.addActionListener(

new ActionListener() //anonymous inner class
{
//display message dialog when user selects About...
public void actionPerformed( ActionEvent event )
{
JOptionPane.showMessageDialog( MenuFrame.this,
"This is an example\not using menus",
"About", JOptionPane.PLAIN_MESSAGE );
} //End method actionPerformed
} //End anonimous inner class
); //end call to addActionListener

JMenuItem exitItem = new JMenuItem( "Exit" ); //create exit item
exitItem.setMnemonic( 'x' ); //set mnemonic to x
fileMenu.add( exitItem ); // add exit item to file menu
exitItem.addActionListener(

new ActionListener() // anonymous inner class
{
//terminate application when user clicks exitItem
public void actionPerformed( ActionEvent event )
{
System.exit( 0 ); //exit application
} // end method actionPerformed
} //end anonymous inner class
); //end call to addActionListener

JMenuBar bar = new JMenuBar(); //create menu bar
setJMenuBar( bar ); //add menu bar to application
bar.add( fileMenu ); //add file menu to menu bar

JMenu formatMenu = new JMenu( "Format" ); //create format menu
formatMenu.setMnemonic( 'r' ); //set mnemonic to r

//array listing string colors
String colors[] = { "Black", "Blue", "Red", "Green" };

JMenu colorMenu = new JMenu( "Color" ); //create color menu
formatMenu.setMnemonic( 'C' ); //set mnemonic to C

//create radio button menu items for colors
colorItems = new JRadioButtonMenuItem[ colors.length ];
colorButtonGroup = new ButtonGroup(); //manages colors
ItemHandler itemHandler = new ItemHandler(); // handler for colors

//create color radio button menu items
for( int count = 0; count < colors.length; count++ )
{
colorItems[ count ] =
new JRadioButtonMenuItem( colors[ count ] );//create item
colorMenu.add( colorItems[ count ]); //add item to color menu
colorButtonGroup.add( colorItems[ count ] ); // add to group
colorItems[ count ].addActionListener( itemHandler );
} //end for

colorItems[ 0 ].setSelected( true ); //select first Color Item

formatMenu.add( colorMenu ); //add color menu to format menu
formatMenu.addSeparator(); //add separator in menu

//array listing font names
String fontNames[] = { "Serif", "Monospace", "SansSerif" };
JMenu fontMenu = new JMenu( "Font" ); //create font menu
fontMenu.setMnemonic( 'n' ); //set mnemonic to n

//create radio button menu items for font names
fonts = new JRadioButtonMenuItem[ fontNames.length ];
fontButtonGroup = new ButtonGroup(); //manages font names

//create Font radio button menu items
for( int count = 0; count < fonts.length; count++ )
{
fonts[ count ] = new JRadioButtonMenuItem( fontNames[ count ] );
fontMenu.add( fonts[ count ] ); //add font to menu font
fontButtonGroup.add( fonts[ count ] ); //add to button groupt
fonts[ count ].addActionListener( itemHandler ); //add handler
} //end for

fonts[ 0 ].setSelected( true ); //select first Font menu item
fontMenu.addSeparator(); //add separator bar to font menu

String styleNames[] = {"Bold", "Italic" }; // names of styles
styleItems = new JCheckBoxMenuItem[styleNames.length ];
StyleHandler styleHandler = new StyleHandler(); //style handler

//create style checkbox menu items
for( int count = 0; count < styleNames.length; count++ )
{
styleItems[ count ]=
new JCheckBoxMenuItem( styleNames[ count ] ); //for style
fontMenu.add( styleItems[ count ] ); //add to font menu
styleItems[ count ].addItemListener( styleHandler ); //handler
} //end for

formatMenu.add( fontMenu ); //add Font menu to Format menu
bar.add( formatMenu ); // add Format menu to menu bar

// set up label to display text
displayJLabel = new JLabel( "Sample Text", SwingConstants.CENTER );
displayJLabel.setForeground( colorValues[ 0 ] );
displayJLabel.setFont( new Font( "Serif", Font.PLAIN, 72) );

getContentPane().setBackground( Color.CYAN ); // set background
add( displayJLabel, BorderLayout.CENTER ); // add displayLabel
} //end MenuFrame constructor

//inner class to handle action events from menu items
private class ItemHandler implements ActionListener
{
//process color and font selections
public void actionPerformed( ActionEvent event )
{
//process color selection
for( int count = 0; count < colorItems.length; count++ )
{
if( colorItems[ count ].isSelected() )
{
displayJLabel.setForeground( colorValues[ count ] );
break;
} //end if
} //end for

//process font selection
for( int count = 0; count < fonts.length; count++ )
{
if( event.getSource() == fonts[ count ] )
{
displayJLabel.setFont(
new Font( fonts[ count ].getText(), style, 72 ));
} // end if
} //end for

repaint(); //redray application
} //end method ActionPerformed
} //end class ItemHandler

//inner class to handle item events for check box menu items
private class StyleHandler implements ItemListener
{
//process font style selections
public void itemStateChanged( ItemEvent e )
{
style = 0; //initialize style

//check for bold selection
if( styleItems[ 0 ].isSelected() )
style += Font.BOLD; //add bold to style

//check for italic selection
if( styleItems[ 1 ].isSelected() )
style += Font.ITALIC; //add italic to style

displayJLabel.setFont(
new Font( displayJLabel.getFont().getName(), style, 72 ));
repaint(); //redraw application
} //end method itemStateChanged
} //end class StyleHandler
} //end class MenuFrame


_____________________________________________________________

// Fig. 22.6: MenuTest.java
// Testing MenuFrame.

import javax.swing.JFrame;

public class MenuTest
{
public static void main( String args[] )
{
MenuFrame menuFrame = new MenuFrame(); // create MenuFrame
menuFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
menuFrame.setSize( 500, 200 ); //set frame size
menuFrame.setVisible( true ); //display frame
} //end main
} //end class MenuTest

Thursday, November 4, 2010

Assignment #17 CS360

Assignment #17
"OvalPanel, SliderFrame & SliderTest"
11-04-10






/*
//Graphics problem
*/
import java.awt.Graphics;
import java.awt.Dimension;
import javax.swing.JPanel;

public class OvalPanel extends JPanel
{
private int diameter = 10;//default diameter of 10

//draw an oval of the specified diameter
public void paintComponent( Graphics g )
{
super.paintComponent( g );

g.fillOval( 10, 10, diameter, diameter ); //draw circle
}

//validate and set diameter
public void setDiameter( int newDiameter )
{
//if diameter invalid, default to 10
diameter = ( newDiameter >= 0 ? newDiameter : 10 );
repaint(); //repaint panel
}

//use by layout manager to determine preffered size
public Dimension getPreferredSize()
{
return new Dimension( 200, 200 );
}

//used by layout manager to determine minimum size
public Dimension getMinimumSize()
{
return getPreferredSize();
}
}

__________________________________________________________________________


/*
//SliderFrame
*/
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JSlider;
import javax.swing.SwingConstants;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;

public class SliderFrame extends JFrame
{
private JSlider diameterJSlider; // slider to select diameter
private OvalPanel myPanel; // panel to draw circle

//no argument constructor
public SliderFrame()
{
super( "Slider Demo" );

myPanel = new OvalPanel(); //create panel to draw circle
myPanel.setBackground( Color.YELLOW ); //set bacground to yellow

//set up JSlider to control diameter value
diameterJSlider = new JSlider( SwingConstants.HORIZONTAL, 0 , 200, 10 );
diameterJSlider.setMajorTickSpacing(10); //create tick every 10
diameterJSlider.setPaintTicks( true ); //paint ticks on slider

//register JSlider event listener
diameterJSlider.addChangeListener(

new ChangeListener() //anonymous inner circle
{
//handle change in slider value
public void stateChanged( ChangeEvent e )
{
myPanel.setDiameter( diameterJSlider.getValue() );
}
}
);

add( diameterJSlider, BorderLayout.SOUTH ); //add slider to frame
add( myPanel, BorderLayout.CENTER ); //add panel to frame
}
}

__________________________________________________________________________

/*
//main method
*/

import javax.swing.JFrame;

public class SliderDemo
{
public static void main( String args[] )
{
SliderFrame sliderFrame = new SliderFrame();
sliderFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
sliderFrame.setSize( 220, 270 ); //set frame size
sliderFrame.setVisible( true ); //display frame
}
}

Thursday, October 21, 2010

Assignment #14 CS360

Assignment #1
"Merge Sort & Merge Sort Test"
10-21-10









/*

//Merge Sort

*/

import java.util.Random;

public class MergeSort
{
private int[] data; //array of values
private static Random generator = new Random();

//create array of given size and fill with random integers
public MergeSort( int size )
{
data = new int[size]; //create space for array

//fill array with random ints range 10-99
for( int i = 0; i < size; i++ )
data[i] = 10 + generator.nextInt( 90 );
}

//calls recursive split method to begin merge sorting
public void sort()
{
sortArray( 0, data.length - 1); //split entire array
}

//splits array, sort subarrays and merges subarrays into sorted array
private void sortArray( int low, int high )
{
//test case: size of array equals 1
if( ( high - low ) >= 1 ) //if not base case
{
int middle1 = (low + high )/2; //calculate middle of array
int middle2 = middle1 + 1; //calculate next element over

//output split step
System.out.println( "split: " + subarray( low, high ) );
System.out.println( " " + subarray( low, middle1 ) );
System.out.println( " " + subarray( middle2, high ) );

//split array in half; sort each half of array
sortArray( low, middle1 ); //first half of array
sortArray( middle2, high ); //second half of array

//merge 2 sorted arrays after split calls return
merge( low, middle1, middle2, high );
}
}

//merge 2 sorted subarrays into one sorted sub array
private void merge( int left, int middle1, int middle2, int right )
{
int leftIndex = left; //index into left subarray
int rightIndex = middle2; //index into right subarray
int combinedIndex = left; //index into temp. work array
int[] combined = new int[data.length]; //working array

//output 2 subarrays before merging
System.out.println( "merge: " + subarray( left, middle1 ) );
System.out.println( " " + subarray( middle2, right ) );

//merge arrays until reaching end of either
while( leftIndex <= middle1 && rightIndex <= right )
{
//place smaller of 2 current elements into result
//and move to next space in arrays
if( data[leftIndex] <= data[rightIndex] )
combined[combinedIndex++] = data[leftIndex++];
else
combined[combinedIndex++] = data[rightIndex++];
}

//if array is empty
if( leftIndex == middle2 )
//copy in rest of right array
while( rightIndex <= right )
combined[combinedIndex++] = data[rightIndex++];
else
//copy in rest of left array
while( leftIndex <= middle1 )
combined[combinedIndex++] = data[leftIndex++];

//copy values back into original array
for( int i = left; i <= right; i++ )
data[i] = combined[i];

//output merged array
System.out.println(" " + subarray( left, right ) );
System.out.println();

}

//method to output certain values in array
public String subarray( int low, int high )
{
StringBuilder temporary = new StringBuilder();

//output spaces for alignment
for( int i = 0; i < low; i++ )
temporary.append( "" );

//output elements left in array
for( int i = low; i <= high; i++ )
temporary.append( "" + data[i] );

return temporary.toString();
}

//method to output values in array
public String toString()
{
return subarray( 0, data.length - 1 );
}
}






/*

//main function

*/

public class MergeSortTest
{
public static void main( String[] args )
{
//create object to perform merge sort
MergeSort sortArray = new MergeSort(10);

//print unsorted array
System.out.println( "Unsorted: " + sortArray + "\n" );

sortArray.sort(); //sort array

//print sorted array
System.out.println( "Sorted: " + sortArray );
}
}

Assignment #13 CS360

Assignment #13
"Insertion Sort & Insertion Sort Test"
10-21-10






/*

//Insertion Sort
*/

import java.util.Random;

public class InsertionSort
{
private int[] data; //array of values
private static Random generator = new Random();

//create array of given size to fill
public InsertionSort( int size)
{
data = new int[size]; //create space for arrays

//fill arrays with random numbers 10-99
for( int i = 0; i < size; i++ )
data[i] = 10 + generator.nextInt(90);
}

//sort array using insertion sort
public void sort()
{
int insert; //temp; variable to hold element to insert

//loop over data.length - elements
for( int next = 1; next < data.length; next++ )
{
//sort value in current element
insert = data[next];

//initialize location to place element
int moveItem = next;

//search for place to put current element
while( moveItem > 0 && data[moveItem - 1] > insert )
{
//shift element right one slot
data[moveItem] = data[moveItem - 1];
moveItem--;
}

data[moveItem] = insert; //place inserted element
printPass( next, moveItem ); //output pass of algorithm
}
}

//print a pass of the algorithm
public void printPass( int pass, int index )
{
System.out.print( String.format( "after pass %2d:", pass ) );

//output elements till swapped item
for(int i = index + 1; i < data.length; i++ )
System.out.print( data[i] + "");

System.out.print( "\n "); //for allignment

//indicate amount of array that is sorted
for( int i = 0; i <= pass; i++ )
System.out.print( "--" );
System.out.println( "\n" ); //add endline
}

//method to output values in array
public String toString()
{
StringBuilder temporary = new StringBuilder();

//iterate through array
for( int element : data )
temporary.append( element + "" );

temporary.append( "\n" ); //add endline character
return temporary.toString();
}
}





/*

//main function

*/

public class InsertionSortTest
{
public static void main( String[] args )
{
//create object to perform insertion sort
InsertionSort sortArray = new InsertionSort( 10 );

System.out.println( "Unsorted array:" );
System.out.println( sortArray ); //print unsorted array

sortArray.sort();

System.out.println( "Sorted array: ");
System.out.println( sortArray ); //print sorted array
}
}

Thursday, October 14, 2010

Assignment #12 CS360

Assignment #12
"Selection Sort & Selection Sort Test"
10-14-10





/*

//Selection Sort Algorithm
*/

import java.util.Random;

public class SelectionSort
{
private int[] data; //array of value
private static Random generator = new Random();

//create array if given size and fill w/ random int
public SelectionSort( int size )
{
data = new int[size]; //create space for array

//fill array with random int 10-99
for(int i = 0; i < size; i++ )
data[i] = 10 + generator.nextInt( 90 );
}

//sort array using slection sort
public void sort()
{
int smallest; //index of smallest element

//loop over data length -1
for(int i = 0; i < data.length - 1; i++)
{
smallest = i; //first index of remaining array

//loops to find index of smallest element
for( int index = i + 1; index < data.length; index++)
if(data[index] < data[smallest])
smallest = index;

swap( i, smallest); //swap smallest elements into position
printPass( i + 1, smallest );
}
}

//helper method to swap values in two elements
public void swap( int first, int second )
{
int temporary = data[first]; //store first in temporary
data[first] = data[second]; //replace first with second
data[second] = temporary; //put temporary in second
}

//print a pass of algorigthm
public void printPass( int pass, int index )
{
System.out.print( String.format( "after pass %2d; ", pass) );

//output elements till selectem item
for (int i = 0; i < index; i++)
System.out.print( data[i] + "");

System.out.print( "\n "); //for alignment

//indicate amount of array that is sorted
for( int j = 0; j < pass; j++ )
System.out.println("\n"); //add endline
}

//method to output balues in array
public String toString()
{
StringBuilder temporary = new StringBuilder();

//iterate through array
for( int element : data)
temporary.append( element + " " );

temporary.append("\n");
return temporary.toString();
}
}

~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|

/*

//main function
*/

public class SelectionSortTest
{
public static void main( String[] args )
{
//create object to perform selection sort
SelectionSort sortArray = new SelectionSort(10);

System.out.println( "Unsorted array:" );
System.out.println( sortArray ); //print unsorted array

sortArray.sort(); //sort array

System.out.println( "Sorted Array:" );
System.out.println( sortArray ); //print sorted array
}
}

Thursday, October 7, 2010

Assignment #11 CS360

Assignment #11
"Towers of Hanoi & Towers of Hanoi Test"
10-07-10





/*
Towers of Hanoi
*/


public class TowersOfHanoi
{
private int numDisks; //number of disks to move

public TowersOfHanoi( int disks )
{
numDisks = disks;
}

//recursively more disks between towers
public void solveTowers( int disks, int sourcePeg, int destinationPeg, int tempPeg)
{
//base case -- only one disk to move
if( disks == 1)
{
System.out.printf( "\n%d --> %d", sourcePeg, destinationPeg);
return;
}

//recursion step -- move (disk 1) disks from sourcePeg
//to tempPeg using destinationPeg
solveTowers( disks - 1, sourcePeg, tempPeg, destinationPeg );

//move last disk from sourcePeg to destinationPeg
System.out.printf( "\n%d --> %d", sourcePeg, destinationPeg );

//move (disks - 1) disks from tempPeg to destinationPeg
solveTowers( disks - 1, tempPeg, destinationPeg, sourcePeg );
}
}




~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|



/*
main function to be run
*/

public class TowersOfHanoiTest
{
public static void main( String args[])
{
int startPeg = 1; //value 1 used to indicate startPeg in output
int endPeg = 3; //value 3 used to indicate endPeg in output
int tempPeg = 2; //value 2 used to indicate tempPeg output
int totalDisks = 3; //number of disks
TowersOfHanoi towersOfHanoi = new TowersOfHanoi( totalDisks );

//initial nonrecursive call: move all disks
towersOfHanoi.solveTowers( totalDisks, startPeg, endPeg, tempPeg );
}
}

Thursday, September 30, 2010

Assignment #10 CS360

Assignment #10
"Fibonacci Calculator & Fibonacci Test"
09-30-10





/*

Fig 15.5
9/18/07
*/

public class FibonacciCalculator
{
//recursive declaration of method Fibonacci
public long fibonacci( long number )
{
if (( number == 0 ) || (number == 1 )) //base cases
return number;
else //recursion step
return fibonacci( number - 1) + fibonacci( number - 2 );
}

public void displayFibonacci()
{
for (int counter = 0; counter <= 10; counter++)
System.out.printf( "Fibonacci of %d is %d\n", counter, fibonacci( counter ) );
}
}


~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|


/*
Fig 15.6
9/18/07
*/

public class FibonacciTest
{
public static void main( String args[] )
{
FibonacciCalculator fibonacciCalculator = new FibonacciCalculator();
fibonacciCalculator.displayFibonacci();
}
}

Assignment #9 CS360

Assignment #9
"Factorial Calculator & Factorial Test"
09-30-10




/*

*/

public class FactorialCalculator
{
//recursive declaration on method factorial
public long factorial( long number )
{
if (number <= 1 ) //test for base case
return 1; //base cases: 0!=1 and 1!=1

else //recursion step
return number * factorial(number - 1);
}

//output factoriasl for values 0-10
public void displayFactorials()
{
//calculate factorials of 0 through 10
for (int counter = 0; counter <= 10; counter++)
System.out.printf( "%d! = %d\n", counter, factorial(counter ));
}
}



~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|



/* Fig 15.4
9/18/07
*/

public class FactorialTest
{
//calculate factorials of 0-10
public static void main( String args[] )
{
FactorialCalculator factorialCalculator = new FactorialCalculator();
factorialCalculator.displayFactorials();
}
}

Thursday, September 23, 2010

Assignment #8 CS360

Assignment #8
"Binary Array & Binary Search Test"
09-23-10






/*
Assignment #8
*/

import java.util.Random;
import java.util.Arrays;

public class BinaryArray
{
private int[] data; //array of any value
private static Random generator = new Random();

//create array of any size and fill with random int
public BinaryArray( int size)
{
data = new int[ size ]; //crate space for array

//fill array with int 10-99
for(int i=0; i data [i] = 10 + generator.nextInt( 90 );

Arrays.sort( data );
}

//perform binary search in data
public int binarySearch( int searchElement )
{
int low = 0; //low end of search area
int high = data.length - 1; //high end of search area
int middle = (low + high + 1)/2; //middle element
int location = -1; //return value; -1 if not found

do //loop to search element
{
//print remaining elements of array
System.out.print( remainingElements( low, high ) );

//output spaces for alignment
for(int i=0; i System.out.print( "" );
System.out.println( "*" ); //indicate current middle

//if the element is found at the middle
if(searchElement == data[ middle ])
location = middle; //location is the current middle

//middle element is too high
else if(searchElement high = middle - 1; // eliminate the higher half
else //middle element too low
low = middle + 1; //eliminate the lower half

middle = (low + high + 1)/2; //recalculate the middle
}

while( ( low <= high ) && (location == -1) );

return location; //return location of search key

}

//method to output certain values in array
public String remainingElements( int low, int high )

{

StringBuilder temporary = new StringBuilder();

//output spaces for alignment
for(int i=0; i<=high; i++)
temporary.append("");

//output element left in array
for(int i=low; i<=high; i++)
temporary.append( data[ i ] + "");

temporary.append( "\n");
return temporary.toString();
}

//method to output values in array
public String toString()
{
return remainingElements( 0,data.length - 1);
}
}




~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|




import java.util.Scanner;

public class BinarySearchTest
{
public static void main(String args[] )
{
//create Scanner object to imput data
Scanner input = new Scanner( System.in );

int searchInt; //Search key
int position; //location of search key in array

//create array and output it
BinaryArray searchArray = new BinaryArray( 15 );
System.out.println( searchArray );

//get input from user
System.out.print( "Please enter an integer value (-1 to quit): ");
searchInt = input.nextInt(); //read an int from user
System.out.println();

//repeadtedly ubput an integer; -1 terminates the program
while(searchInt != -1)
{
//use binary search to try to find integer
position = searchArray.binarySearch( searchInt );

//return value of -1 indicates integer was not found
if(position == -1)
System.out.println( "The integer" + searchInt + "was not found.\n");

else
System.out.println( "The integer" + searchInt + "was found in position"
+ position + ".\n" );

//get input from user
System.out.print( "Please enter an integer value (-1 to quit): ");
searchInt = input.nextInt(); //read an int from user
System.out.println();
}
}
}

Thursday, September 16, 2010

Assignment #7 CS360

Assignment #7
"Linear Array & Linear Search Test"
09-16-10







/*

LinearArray
*/

import java.util.Random;

public class LinearArray
{
private int[] data; //array of values
private static Random generator = new Random();

//Create array of any size and fill with random int
public LinearArray( int size)
{
data = new int[ size ]; //creates spaces for array

//fills array with ints 10-99
for (int i=0; i data[i] = 10 + generator.nextInt(90);
}

//perform a linear search on the data
public int linearSearch( int searchKey )
{
//loop thourgh array sequentionaly
for (int index=0; index if( data[ index ] == searchKey)
return index; //return inex int
return -1; //integer not found
}

//method to output values in array
public String toString()
{
StringBuilder temporary = new StringBuilder();

//iterate through array
for (int element : data)
temporary.append( element+"");

temporary.append("\n"); //add endline
return temporary.toString();
}
}



~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|



/*
LinearSearchTest
*/

import java.util.Scanner;

public class LinearSearchTest
{
public static void main( String args[] )
{
//create scanner object to put data
Scanner input = new Scanner( System.in );

int searchInt; //search key
int position; //location of search key in array

//create array and output it
LinearArray searchArray = new LinearArray( 10 );
System.out.println( searchArray ); //print array

//get input form user
System.out.print( "Please enter an integer value (-1 to quit):");
searchInt = input.nextInt(); //read first int from user

//repeatedly input an integer: -1 terminates the program
while (searchInt != -1 )
{
//perform linear search
position = searchArray.linearSearch( searchInt);

if(position == -1) //integer was not found
System.out.println( "The Integer " + searchInt +" is not found.\n");

//get input from user
System.out.print( "Please enter an integer value (-1 to quit):");
searchInt = input.nextInt(); //read next int from user
}
}
}

Thursday, September 9, 2010

Assignment #6 CS360

Assignment #6
"Label Test"
09-02-10




/*
Assignment 6
*/

import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.Icon;
import javax.swing.ImageIcon;

public class LabelFrame extends JFrame
{
private JLabel label1; //Just for text
private JLabel label2; //Constructed with text and icon
private JLabel label3; // with added text and icon

public LabelFrame()
{
super( "Testing JLabel" );
setLayout (new FlowLayout() );

//JLabel constructor with string argument
label1 = new JLabel( "Label with text" );
label1.setToolTipText( "This is label1" );
add( label1);

//JLabel constructor with string, Icon and alignment arguments
Icon bug = new ImageIcon( getClass().getResource( "bug1.jpg" ) );
label2 = new JLabel( "Label with text and icon", bug,
SwingConstants.LEFT);
label2.setToolTipText( "This is label2" );
add( label2 );

//JLabel constructor with no arguments
label3 = new JLabel();
label3.setText( "Label with icon and text at bottom" );
label3.setIcon( bug );
label3.setHorizontalTextPosition( SwingConstants.CENTER);
label3.setVerticalTextPosition( SwingConstants.BOTTOM);
label3.setToolTipText( "This is label3" );
add( label3 );
}
}





/*
Assignment 6 Main Function
*/

import javax.swing.JFrame;

public class LabelTest
{
public static void main( String args[] )
{
LabelFrame labelFrame = new LabelFrame() ; //creates LabelFrame
labelFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);
labelFrame.setSize( 275, 180 );
labelFrame.setVisible( true );
}
}

Assignment #5 CS360

Assignment #5
"Average Car Fuel"
09-02-10




/*
Assignment 5
*/

import javax.swing.JOptionPane;

public class AverageCarFuel
{
public static void main( String args[] )
{
String milesTravled =
JOptionPane.showInputDialog( "Enter number of miles traveled" );
String gallonsUsed =
JOptionPane.showInputDialog( "Enter gallons used" );

double miles = Integer.parseInt( milesTravled );
double gallons = Integer.parseInt( gallonsUsed);

//gac = gas average for car
double gac = miles / gallons;

JOptionPane.showMessageDialog( null, "Your gas average is " + gac,
"Your Gas Average", JOptionPane.PLAIN_MESSAGE);
}
}

Thursday, September 2, 2010

Assignment #4.1 CS360

Assignment #4.1
"Average"
09-02-10



//Assignment 5


import javax.swing.JOptionPane;

public class Average
{
public static void main(String args[] )
{
//obtain user input from JOptionPaneinput dialogs
String firstNumber =
JOptionPane.showInputDialog( "Enter first interger" ) ;
String secondNumber =
JOptionPane.showInputDialog( "Enter second integer" ) ;
String thirdNumber =
JOptionPane.showInputDialog( "Enter third integer" ) ;

//convert string into int values
int number1 = Integer.parseInt( firstNumber ) ;
int number2 = Integer.parseInt( secondNumber ) ;
int number3 = Integer.parseInt( thirdNumber ) ;

int ave = (number1 + number2 + number3) / 3 ;

//display results in JOptionPane mssg dialog
JOptionPane.showMessageDialog( null, "The average is " + ave,
"Average of Three Integers", JOptionPane.PLAIN_MESSAGE) ;
}
}

Assignment #4 CS360

Assignment #4 CS360
"Addition"
09-02-10




//Assignment 4


import javax.swing.JOptionPane;

public class Addition
{
public static void main(String args[] )
{
//obtain user input from JOptionPaneinput dialogs
String firstNumber =
JOptionPane.showInputDialog( "Enter first interger" ) ;
String secondNumber =
JOptionPane.showInputDialog( "Enter second integer" ) ;

//convert string into int values
int number1 = Integer.parseInt( firstNumber ) ;
int number2 = Integer.parseInt( secondNumber ) ;

int sum = number1 + number2;

//display results in JOptionPane mssg dialog
JOptionPane.showMessageDialog( null, "The sum is " + sum,
"Sum of Two Integers", JOptionPane.PLAIN_MESSAGE) ;
}
}

Tuesday, August 31, 2010

Assignment #3 Part II CS360

Assignment #3 Part II CS360
"Shapes"
08-31-10




//Shapes.java
//Demostrates drawing different shapes.
import java.awt.Graphics;
import javax.swing.JPanel;

public class Shapes extends JPanel
{
private int choice; //user's choice of which shape to draw

//constructor sets the user's choice
public Shapes(int userChoice)
{
choice = userChoice;
} //end Shapes constructor

// draws a cascade of shapes starting from the top-left corner
public void paintComponent(Graphics g)
{
super.paintComponent(g);
for ( int i = 0; i < 10; i++)
{
//pick the shape based on the user's choice
switch (choice)
{
case 1://draw rectangles
g.drawRect(100 - i * 5, 100 - i * 5 , 10 + i * 10, 10 + i * 10 );
break;
case 2://draw ovals
g.drawOval(100 - i * 5, 100 - i * 5 , 10 + i * 10, 10 + i * 10 );
break;
} // end switch
} // end for
} // end method paintCompnent
} //end class Shapes





/*

Test for Shapes

*/

import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class ShapesTest
{
public static void main ( String args[])
{
//obtain user's choice

String input = JOptionPane.showInputDialog(
"Enter 1 to draw rectangles\n"+
"Enter 2 to draw ovals");

int choice=Integer.parseInt( input );//converts input to int

//create the panel with the user's input
Shapes panel = new Shapes(choice);

JFrame application = new JFrame();// creates new JFrame

application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
application.add(panel);
application.setSize(300,300);
application.setVisible(true);
}
}

Thursday, August 26, 2010

Assignment #3 CS360

Assignment #3 CS360
"Shapes"
08-26-10



//Shapes.java
//Demostrates drawing different shapes.
import java.awt.Graphics;
import javax.swing.JPanel;

public class Shapes extends JPanel
{
private int choice; //user's choice of which shape to draw

//constructor sets the user's choice
public Shapes(int userChoice)
{
choice = userChoice;
} //end Shapes constructor

// draws a cascade of shapes starting from the top-left corner
public void paintComponent(Graphics g)
{
super.paintComponent(g);
for ( int i = 0; i < 10; i++)
{
//pick the shape based on the user's choice
switch (choice)
{
case 1://draw rectangles
g.drawRect(10 + i * 10, 10 + i * 10, 50 + i * 10, 50 + i * 10 );
break;
case 2://draw ovals
g.drawOval(10 + i * 10, 10 + i * 10, 50 + i * 10, 50 + i * 10 );
break;
} // end switch
} // end for
} // end method paintCompnent
} //end class Shapes

/*

Test for Shapes

*/

import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class ShapesTest
{
public static void main ( String args[])
{
//obtain user's choice

String input = JOptionPane.showInputDialog(
"Enter 1 to draw rectangles\n"+
"Enter 2 to draw ovals");

int choice=Integer.parseInt( input );//converts input to int

//create the panel with the user's input
Shapes panel = new Shapes(choice);

JFrame application = new JFrame();// creates new JFrame

application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
application.add(panel);
application.setSize(300,300);
application.setVisible(true);
}
}

Assignment #2 CS360

Assignment #2 CS360
"Array On Frame"
08-26-10



/*
Assignment 2
*/

import javax.swing.*;

public class ArrayOnFrame
{

private static void createAndShowGUI()
{
int[]anArray;

anArray = new int[10];

anArray[0] = 100;
anArray[1] = 200;
anArray[2] = 300;
anArray[3] = 400;
anArray[4] = 500;
anArray[5] = 600;
anArray[6] = 700;
anArray[7] = 800;
anArray[8] = 900;
anArray[9] = 1000;

JFrame frame = new JFrame("ArrayOnFrame");
frame.setDefaultCloseOperation(JFrame.EXIT_ONra_CLOSE);

JLabel label = new JLabel("element at index0:" + anArray[0] );
frame.getContentPane().add(label);

frame.pack();
frame.setVisible(true);
}

public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}

Assignment #1 CS360

Assignment #1 CS360
"Hello World Swing"
08-24-10



/*
Assignment 1 HelloWorldSwing

*/

/*
*HelloWorldSwing.java required no other files.
*/
import javax.swing.*;

public class HelloWorldSwing {
/**
* Create the GUI and show it.
*/
private static void createAndShowGUI () {
//Create and set up the window.
JFrame frame = new JFrame ("HelloWorldSwing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Add the ubiquitous "Hello World" label.
JLabel label = new JLabel(" Beatriz Martinez :) ");
frame.getContentPane().add(label);

//Display the window.
frame.pack();
frame.setVisible(true);
}

public static void main (String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI ();
}
});
}
}