190 Chapter 10: Polymorphism
list[i] = list[minIndex];
list[minIndex] = temp;
}
}
}
// ****************************************************************
// IntegerListTest.java
//
// Provide a menu-driven tester for the IntegerList class.
//
// ****************************************************************
import java.util.Scanner;
public class IntegerListTest
//——————————————————-
// Create a list, then repeatedly print the menu and do what the
// user asks until they quit
//——————————————————-
public static void main(String[] args)
{
printMenu();
int choice = scan.nextInt();
while (choice != 0)
{
}
//——————————————————-
// Do what the menu item calls for
//——————————————————-
public static void dispatch(int choice)
{
break;
case 1:
System.out.println(“How big should the list be?”);
case 2:
case 3:
System.out.print(“Enter the value to look for: “);
loc = list.search(scan.nextInt());
Chapter 10: Polymorphism 191
case 4:
list.print();
break;
default:
System.out.println(“Sorry, invalid choice”);
}
}
//——————————————————
// Print the user’s choices
//——————————————————
public static void printMenu()
}
}
Timing Searching and Sorting Algorithms
Chapter 10 has a brief discussion comparing sorting algorithms and searching algorithms. In this exercise you
will use an IntegerList class (in the file IntegerList.java) and a driver (in the file IntegerListTest.java) to
examine the runtimes of the searching and sorting algorithms. The IntegerListTest class has several options for
creating a list of a given size, filling the list with random integers or with already sorted integers, and searching
or sorting the list. (NOTE: You may have used a version of these classes in a previous lab.) Add the methods
minIndex, swap, linearSearch, and binarySearch to the IntegerList class (see the calls to determine the
parameters). Run IntegerListTest a few times to explore the options.
The runtimes of the sorting and searching algorithms can be examined using the Java method
System.currentTimeMillis(), which returns the current system time in milliseconds. (Note that it returns a long,
not an int.) You will have to import java.util.* to have access to this method. In IntegerListTest, just get the
system time immediately before and immediately after you perform any of the searches or sorts. Then subtract
the first from the second, and you have the time required for the operation in milliseconds. WARNING: Be sure
you are not including any input or output in your timed operations; these are very expensive and will swamp
your algorithm times!
Add appropriate calls to System.currentTimeMillis() to your program, run it and fill out the tables below. Note
that you will use much larger arrays for the search algorithms than for the sort algorithms; do you see why?
Chapter 10: Polymorphism 193
import java.util.Scanner;
public class IntegerList
{
int[] list; //values in the list
//————————————————————
// Constructor — takes an integer and creates a list of that
// size. All elements default to value 0.
//————————————————————
public IntegerList(int size)
public void randomize()
{
int max = list.length;
for (int i=0; i<list.length; i++)
list[i] = (int)(Math.random() * max) + 1;
}
//————————————————————
// fillSorted — fills the array with sorted values
//————————————————————
public void fillSorted()
{
for (int i=0; i<list.length; i++)
list[i] = i + 2;
}
//————————————————————
// linearSearch — takes a target value and returns the index
// of the first occurrence of target in the list. Returns -1
// if target does not appear in the list
//————————————————————
public int linearSearch(int target)
location = i;
return location;
}
//————————————————————
// sortIncreasing — uses selection sort
//————————————————————
}
// ****************************************************************
// FILE: IntegerListTest.java
//
// Purpose: Provide a menu-driven tester for the IntegerList class.
//
// ****************************************************************
import java.util.Scanner;
public class IntegerListTest
{
printMenu();
int choice = scan.nextInt();
while (choice != 0)
{
dispatch(choice);
printMenu();
choice = scan.nextInt();
}
}
int loc;
int val;
long time1, time2;
switch(choice)
{
case 0:
case 1:
case 2:
System.out.println(“How big should the list be?”);
Chapter 10: Polymorphism 195
break;
case 3:
list.randomize();
case 4:
list.fillSorted() ;
case 5:
System.out.print(“Enter the value to look for: “);
val = scan.nextInt();
case 6:
System.out.print(“Enter the value to look for: “);
val = scan.nextInt();
case 7:
case 8:
list.sortDecreasing();
System.out.println(“List has been sorted.”);
break;
default:
System.out.println(“3: Fill the list with random ints in range 1-length”);
System.out.println(“4: Fill the list with already sorted elements“);
System.out.println(“5: Use linear search to find an element”);
System.out.println(“6: Use binary search to find an element ” +
“(list must be sorted in increasing order)”);
Coloring a Movable Circle
File MoveCircle.java contains a program that uses CirclePanel.java to draw a circle and let the user move it by
pressing buttons. Save these files to your directory and compile and run MoveCircle to see how it works. Then
study the code, noting the following:
CirclePanel uses a BorderLayout so that the buttons can go on the bottom. But the buttons are not added
directly to the south of the main panel—if they were they would all be on top of each other, and only the
last one would show. Instead, a new panel buttonPanel is created and the buttons are added to it.
buttonPanel uses a flow layout (the default panel layout), so the buttons will appear next to each other and
centered. This panel is added to the south of the main panel.
1. Modify CirclePanel so that in addition to moving the circle, the user can press a button to change its color.
The color buttons should be on the top of the panel; have four color choices. You will need to do the
following:
3. Add another button to the top that says “Choose Color.” Place the button in the middle of your other color
buttons. When pressed, this button should bring up a JColorChooser, and the circle color should become
the color that the user chooses. You can use the same ColorListener class that you used for the other
buttons; just pass null for the color when the user wants to choose their own, and in the actionPerformed
method bring up a JColorChooser if the color is null. Remember that the easiest way to use a
Chapter 10: Polymorphism 197
// ******************************************************************
// MoveCircle.java
//
// Uses CirclePanel to display a GUI that lets the user move
// a circle by pressing buttons.
// ******************************************************************
import java.awt.*;
import javax.swing.*;
public class MoveCircle
{
//———————————–
// Set up a frame for the GUI.
198 Chapter 10: Polymorphism
// ******************************************************************
// CirclePanel.java
//
// A panel with a circle drawn in the center and buttons on the
// bottom that move the circle.
// ******************************************************************
import java.awt.*;
{
// Set coordinates so circle starts in middle
x = (width/2)-(CIRCLE_SIZE/2);
y = (height/2)-(CIRCLE_SIZE/2);
c = Color.green;
// Need a border layout to get the buttons on the bottom
down.addActionListener(new MoveListener(0,20));
// Need a panel to put the buttons on or they’ll be on
// top of each other.
JPanel buttonPanel = new JPanel();
buttonPanel.add(left);
super.paintComponent(page) ;
page.setColor(c) ;
page.fillOval(x,y,CIRCLE_SIZE,CIRCLE_SIZE) ;
}
//—————————————————————-
// Class to listen for button clicks that move circle.
}
//————————————————————–
// Change x and y coordinates and repaint.
//————————————————————–
public void actionPerformed(ActionEvent e)
{
x += dx;
Speed Control
The files SpeedControl.java and SpeedControlPanel.java contain a program (and its associated panel) with a
circle that moves on the panel and rebounds from the edges. (NOTE: the program is derived from Listing 8.15
and 8.16 in the text. That program uses an image rather than a circle. You may have used it in an earlier lab on
animation.) The Circle class is in the file Circle.java. Save the program to your directory and run it to see how it
1. Set up a JSlider object. You need to
Declare it.
2. Set up the change listener for the slider. A skeleton of a class named SlideListener is already in
SpeedControlPanel.java. You need to
3. Create a label (“Timer Delay”) for the slider and align it to the left.
5. Compile and run the program. Make sure the speed is changing when the slider is moved. (NOTE: Larger
delay means slower!)
6. You should have noticed one problem with the program. The ball (circle) goes down behind the panel the
slider is on. To fix this problem do the following:
In actionPerformed, declare a variable slidePanelHt (type int). Use the getSize() method to get the size
(which is a Dimension object) of the panel you put the slider on. Assign slidePanelHt to be the height
of the Dimension object. For example, if your panel is named slidePanel the following assignment
Chapter 10: Polymorphism 201
// ********************************************************************
// SpeedControl.java
//
// Demonstrates animation — balls bouncing off the sides of a panel –
// with speed controlled by a slider.
// ********************************************************************
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SpeedControl
{
// ————————————
202 Chapter 10: Polymorphism
// ******************************************************************
// SpeedControlPanel.java
//
// The panel for the bouncing ball. Similar to
// ReboundPanel.java in Listing 8.16 in the text, except a circle
// rather than a happy face is rebounding off the edges of the
// window.
private Timer timer;
private int moveX, moveY; // increment to move each time
// ——————————————–
// Sets up the panel, including the timer
// for the animation
}
// ———————
// Draw the ball
// ———————
public void paintComponent (Graphics page)
{
super.paintComponent (page);
Chapter 10: Polymorphism 203
public void actionPerformed(ActionEvent action)
{
bouncingBall.move(moveX, moveY);
// change direction if ball hits a side
int x = bouncingBall.getX();
int y = bouncingBall.getY();
// Called when the state of the slider has changed;
// resets the delay on the timer.
// ————————————————
public void stateChanged (ChangeEvent event)
{
}
}
}
204 Chapter 10: Polymorphism
private Color color; // color of the circle
static Random generator = new Random();
//———————————————————
// Creates a random circle with properties in ranges given:
// — radius 25..74
// Creates a circle of a given size (diameter). Other
// attributes are random (as described above)
//———————————————————
public Circle(int size)
{
radius = Math.abs(size/2);
// Shifts the circle’s position — “over” is the number of
// pixels to move horizontally (positive is to the right;
// negative to the left); “down” is the number of pixels
// to move vertically (positive is down; negative is up)