Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

/** ArrayListPractice Anderson, Franceschi */ import java.awt.*; import javax.sw

ID: 662766 • Letter: #

Question

/** ArrayListPractice
Anderson, Franceschi
*/

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Iterator;

public class ArrayListPractice extends JFrame
{
// GUI components
private JButton fillValues;
private JButton printAutoList;
private JButton setValues;
private JButton findMaximum;
private JButton countFrequency;

private ButtonHandler bh;

private static ArrayList<Auto> carList;
private static Auto current = null;
private AutoDisplay ad;

private static ArrayListPractice app;
private boolean firstTime = true;

public ArrayListPractice( )
{
super( "Choose your activity" );
Container c = getContentPane( );
c.setLayout( new FlowLayout( ) );

fillValues = new JButton( "Fill Cars" );
c.add( fillValues );
printAutoList = new JButton( "Print Auto List" );
c.add( printAutoList );
setValues = new JButton( "Set Models" );
c.add( setValues );
findMaximum = new JButton( "Find Maximum Miles" );
c.add( findMaximum );
countFrequency = new JButton( "Count Model Frequency" );
c.add( countFrequency );

bh = new ButtonHandler( );
fillValues.addActionListener( bh );
printAutoList.addActionListener( bh );
setValues.addActionListener( bh );
findMaximum.addActionListener( bh );
countFrequency.addActionListener( bh );

setSize( 500,400 );

carList = new ArrayList<Auto>( );

ad = new AutoDisplay( carList );
setVisible( true );
ad.setEraseColor( getBackground( ) );
// fill carList with several cars
fillWithCars( );
}

// ***** 1. This method has been coded as an example
/** Fills the carList with hard-coded Auto objects
* The instance variable carList is the ArrayList
* to be filled with Auto objects
*/
public void fillWithCars()
{
// clear carList before adding cars
carList.clear();
// Reset the number of Autos to 0
// This is needed so that the animation feedback works correctly
Auto.clearNumberAutos();

Auto car1 = new Auto("BMW", 0, 0.0);
Auto car2 = new Auto("Ferrari", 100, 500.0);
Auto car3 = new Auto("Jeep", 1000, 90.0);
Auto car4 = new Auto("Ferrari", 10, 3.0);
Auto car5 = new Auto("BMW", 4000, 200.0);
Auto car6 = new Auto("Ferrari", 1000, 50.0);

carList.add(car1);
carList.add(car2);
carList.add(car3);
carList.add(car4);
carList.add(car5);
carList.add(car6);
animate();
}

// ***** 2. Student writes this method
/** Prints carList to console, elements are separated by a space
* The instance variable carList is the ArrayList to be printed
*/
public void printAutoList()
{
// Note: To animate the algorithm, put this method call as the
// last element in your for loop
// animate(car);
// where car is the variable name for the current Auto object
// as you loop through the ArrayList object
// Part 2 student code starts here:

// Part 2 student code ends here.
}

// ***** 3. Student writes this method
/** Sets the model of all the elements in carList to parameter value
* The instance variable carList is the ArrayList to be modified
* @param model the model to assign to all Auto objects in carList
*/
public void setModelValues(String model)
{
// Note: To animate the algorithm, put this method call as the
// last statement in your for loop
// animate(car);
// where car is the variable name for the current Auto object
// as you loop through the ArrayList object
// Part 3 student code starts here:

// Part 3 student code ends here.
}

// ***** 4. Student writes this method
/** Finds maximum number of miles driven
* Instance variable carList is the ArrayList to search
* @return the maximum miles driven by all the Auto objects
*/
public int findMaximumMilesDriven()
{
// Note: To animate the algorithm, put this method call as the
// last statement in your for loop
// animate(car, maximum);
// where car is the variable name for the current Auto object
// and maximum is the int variable storing the current maximum
// number of miles for all Auto elements you have already tested
// as you loop through the ArrayList object
// Part 4 student code starts here:

return 0; // replace this statement with your return statement

// Part 4 student code ends here.
}


// ***** 5. Student writes this method
/** Finds number of times parameter model is found in the carList
* Instance variable carList is the ArrayList in which we search
* @param model the model to count
* @return the number of times model was found
*/
public int countFound(String model)
{
// Note: To animate the algorithm, put this method call as the
// last statement in your for loop
// animate(car, num);
// where car is the variable name for the current Auto object
// and num is the int variable storing the current number of
// Auto elements whose model is equal to the method's parameter
// as you loop through the ArrayList object
// Part 5 student code starts here:

return 0; // replace this statement with your return statement

// Part 5 student code ends here.
}

public void startActivity( int act )
{
ad.setActivity( act );
boolean goodInput = false;
String answer = "";
String message = "";
switch( act )
{
case 0:
fillWithCars( );
JOptionPane.showMessageDialog( null, "carList filled with new values" );
break;

case 1:
printAutoList( );
JOptionPane.showMessageDialog( null, "carList printed" );
break;

case 2:
answer = JOptionPane.showInputDialog( null, "Enter a car model" );
if (answer != null )
{
ad.setSearchModel( answer );
setModelValues( answer );
if ( ad.getCurrentModelValuesSet( ) )
message = " Your result is correct";
else
message = " Your result is not correct";
JOptionPane.showMessageDialog( null, "car models set to " + answer + message );
}
break;

case 3:
int a = findMaximumMilesDriven( );
if ( a == ad.getCurrentMaximumMilesDriven( ) )
message = " Your result is correct";
else
message = " Your result is not correct";
JOptionPane.showMessageDialog( null, "The maximum number of miles driven is " + a + message );
break;

case 4:
answer = JOptionPane.showInputDialog( null, "Enter a car model" );
if ( answer != null )
{
ad.setSearchModel( answer );
int frequency = countFound( answer );
if ( frequency == ad.getCurrentCountModelFound( ) )
message = " Your result is correct";
else
message = " Your result is not correct";
if ( frequency > 1 )
JOptionPane.showMessageDialog( null, answer + " found " + frequency + " times" + message );
else if ( frequency == 1 )
JOptionPane.showMessageDialog( null, answer + " found " + frequency + " time" + message );
else
JOptionPane.showMessageDialog( null, answer + " not found" + message );
}
break;
}
enableButtons( );
}

public static Auto getCurrent( )
{
return current;
}

public static ArrayList getCarList( )
{
return carList;
}

private void animate( Auto au )
{
if ( ad.getActivity( ) == 1 || ad.getActivity( ) == 2 )
{
try
{
current = au;
ad.setCarList( carList );
ad.setCurrentAuto( au );
ad.setCurrentIndex( au.getIndex( ) );
repaint( );
Thread.sleep( 4000 );
}
catch ( InterruptedException e )
{
System.out.println( "IE Exception " + e.getMessage( ) );
System.out.println( e.toString( ) );
}
}
else
{
// call to animate has wrong number of arguments
JOptionPane.showMessageDialog( null, "Wrong number of arguments to animate method" );
System.exit( 1 );
}
}

private void animate( Auto au, int studentResult )
{
if ( ad.getActivity( ) == 3 || ad.getActivity( ) == 4 )
{
try
{
current = au;
ad.setCarList( carList );
ad.setCurrentAuto( au );
ad.setCurrentIndex( au.getIndex( ) );
ad.setStudentResult( studentResult );
repaint( );
Thread.sleep( 4000 );
}
catch ( InterruptedException e )
{
System.out.println( "IE Exception " + e.getMessage( ) );
System.out.println( e.toString( ) );
}
}
else
{
// call to animate has wrong number of arguments
JOptionPane.showMessageDialog( null, "Wrong number of arguments to animate method" );
System.exit( 1 );
}
}

private void animate( )
{
if ( ad.getActivity( ) == 0 )
{
try
{
ad.setCarList( carList );
repaint( );
Thread.sleep( 4000 );
}
catch ( InterruptedException e )
{
System.out.println( "IE Exception " + e.getMessage( ) );
System.out.println( e.toString( ) );
}
}
else
{
// call to animate has wrong number of arguments
JOptionPane.showMessageDialog( null, "Wrong number of arguments to animate method" );
System.exit( 1 );
}
}

public void paint( Graphics g )
{
if ( ( ( current != null ) || firstTime ) && ( ad.getActivity( ) != 0 ) )
{
super.paint( g );
if ( ad.getCurrentAuto( ) != null )
ad.updateAutoDisplay( current, g );
firstTime = false;
}
else if ( ad.getActivity( ) == 0 )
{
super.paint( g );
ad.updateAutoDisplay( g );
}
}

public static void main( String [] args )
{
app = new ArrayListPractice( );
app.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}

public void disableButtons( )
{
fillValues.setEnabled( false );
printAutoList.setEnabled( false );
setValues.setEnabled( false );
countFrequency.setEnabled( false );
findMaximum.setEnabled( false );
}

public void enableButtons( )
{
fillValues.setEnabled( true );
printAutoList.setEnabled( true );
setValues.setEnabled( true );
countFrequency.setEnabled( true );
findMaximum.setEnabled( true );
}

private class ButtonHandler implements ActionListener
{
private boolean on = true;
public void actionPerformed( ActionEvent e )
{
printAutoListT t = new printAutoListT( app );

if ( e.getSource( ) == fillValues )
{
disableButtons( );
fillValues.requestFocus( );
ad.setActivity( 0 );
t.start( );
}
else if ( e.getSource( ) == printAutoList )
{
disableButtons( );
printAutoList.requestFocus( );
ad.setActivity( 1 );
t.start( );
}
else if ( e.getSource( ) == setValues )
{
disableButtons( );
setValues.requestFocus( );
ad.setActivity( 2 );
t.start( );
}
else if ( e.getSource( ) == findMaximum )
{
disableButtons( );
findMaximum.requestFocus( );
ad.setActivity( 3 );
t.start( );
}
else if ( e.getSource( ) == countFrequency )
{
disableButtons( );
countFrequency.requestFocus( );
ad.setActivity( 4 );
t.start( );
}
}
}

private class printAutoListT extends Thread
{
ArrayList<Auto> arr;
ArrayListPractice s1;
public printAutoListT ( ArrayListPractice s )
{
arr = ArrayListPractice.carList;
s1 = s;
}
public void run( )
{
startActivity( ad.getActivity( ) );
}
}
}

/* AutoDisplay
* Anderson, Franceschi
*/

import java.awt.Graphics;
import javax.swing.JFrame;
import java.awt.Color;
import java.util.ArrayList;

public class AutoDisplay
{
private ArrayList<Auto> data;

private int xStart = 100;
private int xEnd = 300;
private int yStart = 200;
private int activity = 0;
private int count = 0;

private Auto currentAuto;
private int currentIndex;
private String searchModel;
private int studentResult;

private int currentCountModelFound;
private int currentMaximumMilesDriven;
private boolean currentModelValuesSet;

private Color eraseColor;

public AutoDisplay( )
{ }

public AutoDisplay( ArrayList<Auto> al )
{
data = new ArrayList<Auto>( );
data = al;
}

public void setCarList( ArrayList<Auto> al )
{
data = al;
}

public void setActivity( int a )
{
activity = a;
}
public int getActivity( )
{
return activity;
}

public void setCurrentAuto( Auto car )
{
currentAuto = car;
}

public Auto getCurrentAuto( )
{
return currentAuto;
}

public void setCurrentIndex( int newCurrentIndex )
{
currentIndex = newCurrentIndex;
}

public void setSearchModel( String newSearchModel )
{
searchModel = newSearchModel;
}

public void setStudentResult( int sr )
{
studentResult = sr;
}

public void setEraseColor( Color c )
{
eraseColor = c;
}

public int getCurrentCountModelFound( )
{
return currentCountModelFound;
}

public int getCurrentMaximumMilesDriven( )
{
return currentMaximumMilesDriven;
}

public boolean getCurrentModelValuesSet( )
{
return currentModelValuesSet;
}

public void findCurrentMaximumMilesDriven( )
{
currentMaximumMilesDriven = currentAuto.getMilesDriven( );
for(int i = 0; i < currentIndex; i++)
{
if ( data.get( i ).getMilesDriven( ) > currentMaximumMilesDriven )
currentMaximumMilesDriven = data.get( i ).getMilesDriven( );
}
}

public void findCurrentCountFound( )
{
currentCountModelFound = 0;
for(int i = 0; i <= currentIndex; i++)
{
if ( data.get( i ).getModel( ).equals(searchModel) )
currentCountModelFound++;
}
}

public void checkCurrentModelValuesSet( )
{
currentModelValuesSet = true;
for(int i = 0; i <= currentIndex; i++)
{
if (!( data.get( i ).getModel( ).equals(searchModel) ))
currentModelValuesSet = false;
}
}

public void updateAutoDisplay( Graphics g )
{
// called for new ArrayList values
// Displays new data
int i = 0;
for ( Auto car : data )
{
if ( car.getModel( ).equals( "BMW" ) )
g.setColor( Color.blue );
else if ( car.getModel( ).equals( "Jeep" ) )
g.setColor( Color.black );
else if ( car.getModel( ).equals( "Ferrari" ) )
g.setColor( Color.red );
else
g.setColor( Color.green );

g.drawString( car.toString( ) , xStart, yStart + 25* i );
i = i + 1;
try {
Thread.sleep( 100 );
}
catch ( InterruptedException e )
{
e.printStackTrace();
}
}
}

public void updateAutoDisplay( Auto car, Graphics g )
{
draw( g );
switch( activity )
{
case 0: // create new ArrayList values
break;
case 1: // print out the ArrayList
break;
case 2: // set all Auto models
checkCurrentModelValuesSet( );
drawValuesSet( g );
break;
case 3: // find the maximum mumber of miles
findCurrentMaximumMilesDriven( );
drawMaxMiles( g );
break;
case 4: // find the frequency of a model
findCurrentCountFound( );
drawFrequency( g );
break;
}

if ( ( currentAuto.getModel( ) ).equals( "BMW" ) )
drawBMW( g, xStart, xEnd, yStart );
else if ( ( currentAuto.getModel( ) ).equals( "Jeep" ) )
drawJeep( g, xStart, xEnd, yStart );
else if ( ( currentAuto.getModel( ) ).equals( "Ferrari" ) )
drawFerrari( g, xStart, xEnd, yStart );
else
drawOtherCar( g, xStart, xEnd, yStart );
}

public void draw( Graphics g )
{
// Set color first then Draw the miles and gallons of currentAuto
if ( currentAuto != null )
{
if ( currentAuto.getModel( ).equals( "BMW" ) )
g.setColor( Color.BLUE );
else if ( currentAuto.getModel( ).equals( "Jeep" ) )
g.setColor( Color.BLACK );
else if ( currentAuto.getModel( ).equals( "Ferrari" ) )
g.setColor( Color.RED );
else
g.setColor( new Color( 20, 200, 110 ) );
g.drawString( "Miles = " + currentAuto.getMilesDriven( ) , xStart + 100, yStart + 40 );
g.drawString( "Gallons = " + currentAuto.getGallonsOfGas( ) , xStart + 100, yStart + 70 );
}
}

public void drawBMW( Graphics g, int startX, int endX, int y )
{
int wx1 = 0;
int wy1 = 0;
int wx2 = 0;
int wy2 = 0;
for ( int x = startX; x < endX; x += 1 )
{
// draw the BMW
g.setColor( Color.BLUE );
// Bottom
g.drawLine( x, y, x + 100, y );
// Back
g.drawLine( x, y, x, y - 20 );
// trunk
g.drawLine( x, y - 20, x + 20, y - 20 );
// back windshield
g.drawLine( x + 20, y - 20, x + 20, y - 40 );
// Roof
g.drawLine( x + 20, y - 40, x + 60, y - 40 );
// Windshield
g.drawLine( x + 60, y - 40, x + 70, y - 20 );
// Hood
g.drawLine( x + 70, y - 20, x + 100, y - 20 );
// Front
g.drawLine( x + 100, y - 20, x + 100, y );

// Back wheel
g.drawOval( x + 15, y, 14, 14 );
// Make backwheel animate
wx1 = x + 22 - ( (int) ( 3 * Math.cos( 3 * x ) ) );
wy1 = y + 7 - ( (int) ( 3 * Math.sin( -3 * x ) ) );
wx2 = x + 22 + ( (int) ( 3 * Math.cos( 3 * x ) ) );
wy2 = y + 7 + ( (int) ( 3 * Math.sin( -3 * x ) ) );
g.drawLine( wx1, wy1, wx2, wy2 );

// Front wheel
g.drawOval( x + 70, y, 14, 14 );
// Make frontwheel animate
wx1 = x + 77 - ( (int) ( 3 * Math.cos( 3 * x ) ) );
wy1 = y + 7 - ( (int) ( 3 * Math.sin( -3 * x ) ) );
wx2 = x + 77 + ( (int) ( 3 * Math.cos( 3 * x ) ) );
wy2 = y + 7 + ( (int) ( 3 * Math.sin( -3 * x ) ) );
g.drawLine( wx1, wy1, wx2, wy2 );

// draw BMW name
g.drawString("BMW", x + 30, y - 20 );
try {
Thread.sleep( ( int )( 15 ) );
}
catch ( InterruptedException e )
{
e.printStackTrace( );
}
g.setColor( eraseColor );
if ( x != ( endX - 1 ) )
g.fillRect( x, y - 60, 101, 81 ); //erase
}
}

public void drawFerrari( Graphics g, int startX, int endX, int y )
{
int wx1 = 0;
int wy1 = 0;
int wx2 = 0;
int wy2 = 0;
for ( int x = startX; x < endX; x += 1 )
{
// draw the BMW
g.setColor( Color.RED );
// Bottom
g.drawLine( x, y, x + 100, y );
// Back
g.drawLine( x, y, x, y - 10 );
// trunk
g.drawLine( x, y - 10, x + 10, y - 15 );
// back windshield
g.drawLine( x + 10, y - 15, x + 20, y - 30 );
// Roof
g.drawLine( x + 20, y - 30, x + 50, y - 30 );
// Windshield
g.drawLine( x + 50, y - 30, x + 80, y - 15 );
// Hood
g.drawLine( x + 80, y - 15, x + 100, y - 10 );
// Front
g.drawLine( x + 100, y - 10, x + 100, y );

// Back wheel
g.drawOval( x + 15, y, 14, 14 );
// Make backwheel animate
wx1 = x + 22 - ( (int) ( 3 * Math.cos( 3 * x ) ) );
wy1 = y + 7 - ( (int) ( 3 * Math.sin( -3 * x ) ) );
wx2 = x + 22 + ( (int) ( 3 * Math.cos( 3 * x ) ) );
wy2 = y + 7 + ( (int) ( 3 * Math.sin( -3 * x ) ) );
g.drawLine( wx1, wy1, wx2, wy2 );

// Front wheel
g.drawOval( x + 70, y, 14, 14 );
// Make frontwheel animate
wx1 = x + 77 - ( (int) ( 3 * Math.cos( 3 * x ) ) );
wy1 = y + 7 - ( (int) ( 3 * Math.sin( -3 * x ) ) );
wx2 = x + 77 + ( (int) ( 3 * Math.cos( 3 * x ) ) );
wy2 = y + 7 + ( (int) ( 3 * Math.sin( -3 * x ) ) );
g.drawLine( wx1, wy1, wx2, wy2 );

// draw BMW name
g.drawString("Ferrari", x + 25, y - 10 );
try {
Thread.sleep( ( int )( 10 ) );
}
catch ( InterruptedException e )
{
e.printStackTrace( );
}
g.setColor( eraseColor );
if ( x != ( endX - 1 ) )
g.fillRect( x, y - 60, 101, 81 ); //erase
}
}

public void drawJeep( Graphics g, int startX, int endX, int y )
{
int wx1 = 0;
int wy1 = 0;
int wx2 = 0;
int wy2 = 0;
for ( int x = startX; x < endX; x += 1 )
{
// draw the Jeep
g.setColor( Color.BLACK );
// Bottom
g.drawLine( x, y, x + 100, y );
// Back
g.drawLine( x, y, x, y - 60 );
// Roof
g.drawLine( x, y - 60, x + 60, y - 60 );
// Windshield
g.drawLine( x + 60, y - 60, x + 70, y - 20 );
// Hood
g.drawLine( x + 70, y - 20, x + 100, y - 20 );
// Front
g.drawLine( x + 100, y - 20, x + 100, y );
// Back wheel
g.drawOval( x + 15, y, 15, 15 );

// Make backwheel animate
wx1 = x + 22 - ( (int) ( 3 * Math.cos( 3 * x ) ) );
wy1 = y + 7 - ( (int) ( 3 * Math.sin( -3 * x ) ) );
wx2 = x + 22 + ( (int) ( 3 * Math.cos( 3 * x ) ) );
wy2 = y + 7 + ( (int) ( 3 * Math.sin( -3 * x ) ) );
g.drawLine( wx1, wy1, wx2, wy2 );

// Front wheel
g.drawOval( x + 70, y, 15, 15 );
// Make frontwheel animate
wx1 = x + 77 - ( (int) ( 3 * Math.cos( 3 * x ) ) );
wy1 = y + 7 - ( (int) ( 3 * Math.sin( -3 * x ) ) );
wx2 = x + 77 + ( (int) ( 3 * Math.cos( 3 * x ) ) );
wy2 = y + 7 + ( (int) ( 3 * Math.sin( -3 * x ) ) );
g.drawLine( wx1, wy1, wx2, wy2 );

// draw Jeep name
g.drawString("Jeep", x + 20, y - 30 );
try {
Thread.sleep( ( int )( 18 ) );
}
catch ( InterruptedException e )
{
e.printStackTrace( );
}
g.setColor( eraseColor );
if ( x != ( endX - 1 ) )
g.fillRect( x, y - 60, 101, 81 ); //erase
}
}

public void drawOtherCar( Graphics g, int startX, int endX, int y )
{
int wx1 = 0;
int wy1 = 0;
int wx2 = 0;
int wy2 = 0;
for ( int x = startX; x < endX; x += 1 )
{
// draw the other car
g.setColor( new Color( 20, 200, 110 ) );
// Bottom
g.drawLine( x, y, x + 100, y );
// Back
g.drawLine( x, y, x, y - 20 );
// trunk
g.drawLine( x, y - 20, x + 20, y - 20 );
// back windshield
g.drawLine( x + 20, y - 20, x + 20, y - 40 );
// Roof
g.drawLine( x + 20, y - 40, x + 60, y - 40 );
// Windshield
g.drawLine( x + 60, y - 40, x + 70, y - 20 );
// Hood
g.drawLine( x + 70, y - 20, x + 100, y - 20 );
// Front
g.drawLine( x + 100, y - 20, x + 100, y );
// Back wheel
g.drawOval( x + 15, y, 14, 14 );
// Make backwheel animate
wx1 = x + 22 - ( (int) ( 3 * Math.cos( 3 * x ) ) );
wy1 = y + 7 - ( (int) ( 3 * Math.sin( -3 * x ) ) );
wx2 = x + 22 + ( (int) ( 3 * Math.cos( 3 * x ) ) );
wy2 = y + 7 + ( (int) ( 3 * Math.sin( -3 * x ) ) );
g.drawLine( wx1, wy1, wx2, wy2 );

// Front wheel
g.drawOval( x + 70, y, 14, 14 );
// Make frontwheel animate
wx1 = x + 77 - ( (int) ( 3 * Math.cos( 3 * x ) ) );
wy1 = y + 7 - ( (int) ( 3 * Math.sin( -3 * x ) ) );
wx2 = x + 77 + ( (int) ( 3 * Math.cos( 3 * x ) ) );
wy2 = y + 7 + ( (int) ( 3 * Math.sin( -3 * x ) ) );
g.drawLine( wx1, wy1, wx2, wy2 );

// draw Auto name
// g.drawString("???", x + 30, y - 20 );
String autoName = currentAuto.getModel( );
if ( autoName.length( ) > 5 )
autoName = autoName.substring( 0, 3 ) + "..";
g.drawString( autoName, x + 30, y - 20 ); // NEW ADDED
try {
Thread.sleep( ( int )( 18 ) );
}
catch ( InterruptedException e )
{
e.printStackTrace( );
}
g.setColor( eraseColor );
if ( x != ( endX - 1 ) )
g.fillRect( x, y - 60, 101, 81 ); //erase
}
}

public void drawValuesSet( Graphics g )
{
g.setColor( Color.BLACK );
String message = "";
if ( currentModelValuesSet )
message = "correctly";
else
message = "incorrectly";
g.drawString( "To this point, the models have been set " + message, xStart + 100, yStart + 125 );
}

public void drawMaxMiles( Graphics g )
{
g.setColor( Color.BLACK );
g.drawString( "Student's current maximum is " + studentResult, xStart + 100, yStart + 100 );
g.drawString( "Correct current maximum is " + currentMaximumMilesDriven, xStart + 100, yStart + 125 );
}

public void drawFrequency( Graphics g )
{
g.setColor( Color.BLACK );
g.drawString( "Student's current count is " + studentResult, xStart + 100, yStart + 100 );
g.drawString( "Correct current count is " + currentCountModelFound, xStart + 100, yStart + 125 );
}
}

/* Auto class
Anderson, Franceschi
*/
import java.text.DecimalFormat;
import java.awt.Graphics;

public class Auto
{
// Static instance variable - number of Auto objects references created
private static int numberAutos = 0;
// Instance variables
private String model; // model of auto
private int milesDriven; // number of miles driven
private double gallonsOfGas; // number of gallons of gas
private int index; // car number

// Default constructor:
// Initializes model to a blank String
// milesDriven are autoinitialized to 0, gallonsOfGas to 0.0
public Auto( )
{
model = "";
index = numberAutos;
numberAutos++;
}

// Overloaded constructor:
// Allows client to set beginning values for
// model, milesDriven, and gallonsOfGas.
// Calls mutator methods to validate new values.
public Auto( String startModel,
int startMilesDriven,
double startGallonsOfGas )
{
model = startModel;
setMilesDriven( startMilesDriven );
setGallonsOfGas( startGallonsOfGas );
index = numberAutos;
numberAutos++;
}

// Accessor method:
// Returns current value of index
public int getIndex( )
{
return index;
}

// Accessor method:
// Returns current value of model
public String getModel( )
{
return model;
}

// Accessor method:
// Returns current value of milesDriven
public int getMilesDriven( )
{
return milesDriven;
}

// Accessor method:
// Returns current value of gallonsOfGas
public double getGallonsOfGas( )
{
return gallonsOfGas;
}

// Mutator method:
// Allows client to set model
public void setModel( String newModel )
{
model = newModel;
}

// Mutator method:
// Allows client to set value of milesDriven
// prints an error message if new value is less than 0
public void setMilesDriven( int newMilesDriven )
{
if ( newMilesDriven >= 0 )
milesDriven = newMilesDriven;
else
{
System.err.println( "Miles driven must be at least 0." );
System.err.println( "Value not changed." );
}
}

// Mutator method:
// Allows client to set value of gallonsOfGas;
// prints an error message if new value is less than 0.0
public void setGallonsOfGas( double newGallonsOfGas )
{
if ( newGallonsOfGas >= 0.0 )
gallonsOfGas = newGallonsOfGas;
else
{
System.err.println( "Gallons of gas must be at least 0." );
System.err.println( "Value not changed." );
}
}

// Mutator method
// Allows client to add miles driven and gallons of gas used
// to current values;
// prints error messages if new values are less than 0
public void addMileage( int newMilesDriven,
double newGallonsOfGas )
{
if ( newMilesDriven < 0 )
{
System.err.println( "Miles driven must be at least 0." );
System.err.println( "Value not changed" );
return; // do not continue executing method
}

if ( newGallonsOfGas < 0.0 )
{
System.err.println( "Gallons of gas must positive." );
System.err.println( "Value not changed" );
return; // do not continue executing method
}

// ok to change values
milesDriven += newMilesDriven; // add newMilesDriven
gallonsOfGas += newGallonsOfGas; // add newGallonsOfGas
}

// Calculates mileage as miles per gallon.
// If no gallons of gas have been used, returns 0.0;
// Otherwise, returns miles per gallon
// as milesDriven / gallonsOfGas
public double calculateMilesPerGallon( )
{
if ( gallonsOfGas != 0.0 )
return milesDriven / gallonsOfGas;
else
return 0.0;
}

public static void clearNumberAutos( )
{
numberAutos = 0;
}

public String toString( )
{
DecimalFormat gallonsFormat = new DecimalFormat( "##.0" );
return "Model: " + model
+ " Miles driven: " + milesDriven
+ " Gallons of gas: "
+ gallonsFormat.format( gallonsOfGas );
}

public void draw( Graphics g, int startX, int endX, int y)
{}

} // end Auto class definition

Explanation / Answer

import java.awt.Container; import java.awt.FlowLayout; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.ArrayList; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; public abstract class ArrayListPracticeBase extends JFrame { final static String[] CAR_NAMES = {"BMW", "Ferrari", "Jeep"}; final static int MIN_CARS = 2; final static int MAX_CARS = 5; /** Fills the carList with hard-coded Auto objects * The instance variable carList is the ArrayList * to be filled with Auto objects */ abstract void fillWithCars(); /** Prints carList to console, elements are separated by a space * The instance variable carList is the ArrayList to be printed */ abstract void printAutoList(); /** Sets the model of all the elements in carList to parameter value * The instance variable carList is the ArrayList to be modified * @param model the model to assign to all Auto objects in carList */ abstract void setModelValues(String model); /** Finds maximum number of miles driven * Instance variable carList is the ArrayList to search * @return the maximum miles driven by all the Auto objects */ abstract int findMaximumMilesDriven(); /** Finds number of times parameter model is found in the carList * Instance variable carList is the ArrayList in which we search * @param model the model to count * @return the number of times model was found */ abstract int countFound(String model); /** Clears the list * Instance variable carList is the ArrayList to clear */ abstract void clearList(); /** Remove last car from the list * Instance variable carList is the ArrayList to clear * Be sure to handle the case when the list is empty */ abstract void removeLast(); //End of student code ////////////////////////////////////////// ////////////////////////////////////////// // GUI components private JButton fillValues; private JButton printAutoList; private JButton setValues; private JButton findMaximum; private JButton countFrequency; private JButton clearList; private JButton removeLast; private ButtonHandler bh; protected static ArrayList carList; private AutoDisplay ad; private static ArrayListPractice app; public ArrayListPracticeBase() { super("Choose your activity"); this.addWindowListener(new WindowAdapter() { @Override public void windowActivated(WindowEvent we) { repaint(); } @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); Container c = getContentPane(); c.setLayout(new FlowLayout()); fillValues = new JButton("Fill Cars"); c.add(fillValues); printAutoList = new JButton("Print Auto List"); c.add(printAutoList); setValues = new JButton("Set Models"); c.add(setValues); findMaximum = new JButton("Find Maximum Miles"); c.add(findMaximum); countFrequency = new JButton("Count Model Frequency"); c.add(countFrequency); clearList = new JButton("Clear List"); c.add(clearList); removeLast = new JButton("Remove Last"); c.add(removeLast); bh = new ButtonHandler(); fillValues.addActionListener(bh); printAutoList.addActionListener(bh); setValues.addActionListener(bh); findMaximum.addActionListener(bh); countFrequency.addActionListener(bh); clearList.addActionListener(bh); removeLast.addActionListener(bh); setSize(500, 400); carList = new ArrayList(); ad = new AutoDisplay(carList); setVisible(true); ad.setEraseColor(getBackground()); // fill carList with several cars fillWithCars(); } void showDialog(String message) { ad.resetActivity(); JOptionPane.showMessageDialog(null, message); repaint(); } public void startActivity(AutoDisplay.Activity act) { ad.setActivity(act); String answer = ""; String message = ""; switch (act) { case FILL_VALUES: fillWithCars(); ad.setCarList(carList); showDialog("carList filled with new values"); break; case PRINT_LIST: printAutoList(); showDialog("carList printed"); break; case SET_MODELS: answer = JOptionPane.showInputDialog(null, "Enter a car model"); if (answer != null) { ad.resetCurrentModelValuesSet(); ad.setSearchModel(answer); setModelValues(answer); if (ad.getCurrentModelValuesSet()) { message = " Your result is correct"; } else { message = " Your result is not correct"; } showDialog("car models set to " + answer + message); } break; case FIND_MAX: if (carList.isEmpty()) { JOptionPane.showMessageDialog(null, "The list is empty, there is no maximum."); break; } int a = findMaximumMilesDriven(); if (a == ad.getCurrentMaximumMilesDriven()) { message = " Your result is correct"; } else { message = " Your result is not correct"; } showDialog("The maximum number of miles driven is " + a + message); break; case COUNT_MODEL: answer = JOptionPane.showInputDialog(null, "Enter a car model"); if (answer != null) { ad.resetCurrentCountModelFound(); ad.setSearchModel(answer); int frequency = countFound(answer); if (frequency == ad.getCurrentCountModelFound()) { message = " Your result is correct"; } else { message = " Your result is not correct"; } if (frequency > 1) { showDialog(answer + " found " + frequency + " times" + message); } else if (frequency == 1) { showDialog(answer + " found " + frequency + " time" + message); } else { showDialog(answer + " not found" + message); } } break; case CLEAR_LIST: int n = JOptionPane.showConfirmDialog( null, "Erase list?", "Confirm", JOptionPane.YES_NO_OPTION); if (n == JOptionPane.YES_OPTION) { clearList(); ad.setCarList(carList); if (carList.isEmpty()) { showDialog("The list is empty. Your result is correct."); } else { showDialog("The list is not empty. Your result is incorrect."); } } break; case REMOVE_LAST_CAR: int nRemove = JOptionPane.showConfirmDialog( null, "Remove last car from list?", "Confirm", JOptionPane.YES_NO_OPTION); if (nRemove == JOptionPane.YES_OPTION) { Auto lastCar = getLastCar(); removeLast(); ad.setCarList(carList); if (isLastGone(lastCar)) { showDialog("The last car is gone. Your result is correct."); } else { showDialog("The last car is still there. Your result is incorrect."); } } break; } enableButtons(); } public Auto getLastCar() { if (carList.size() > 0) { return carList.get(carList.size() - 1); } return null; } public boolean isLastGone(Auto last) { for (Auto car : carList) { if (car == last) { return false; } } return true; } public static ArrayList getCarList() { return carList; } protected void animate(Auto au) { switch (ad.getActivity()) { case PRINT_LIST: case SET_MODELS: try { ad.setCurrentAuto(au); ad.setCurrentIndex(au.getIndex()); repaint(); Thread.sleep(4000); } catch (InterruptedException e) { System.out.println("IE Exception " + e.getMessage()); System.out.println(e.toString()); } break; default: // call to animate has wrong number of arguments JOptionPane.showMessageDialog(null, "Wrong number of arguments to animate method. " + "The animate method with 1 argument should only be called for PRINT_LIST and SET_MODELS. " + "It was called with " + ad.getActivity() + ". " + "Terminating program."); System.exit(1); break; } } protected void animate(Auto au, int studentResult) { switch (ad.getActivity()) { case FIND_MAX: case COUNT_MODEL: try { ad.setCurrentAuto(au); ad.setCurrentIndex(au.getIndex()); ad.setStudentResult(studentResult); repaint(); Thread.sleep(4000); } catch (InterruptedException e) { System.out.println("IE Exception " + e.getMessage()); System.out.println(e.toString()); } break; default: // call to animate has wrong number of arguments JOptionPane.showMessageDialog(null, "Wrong number of arguments to animate method. " + "The animate method with 2 arguments should only be called for FIND_MAX and COUNT_MODELS. " + "It was called with " + ad.getActivity() + ". " + "Terminating program."); System.exit(1); break; } } protected void animate() { switch (ad.getActivity()) { case FILL_VALUES: case CLEAR_LIST: case REMOVE_LAST_CAR: case NONE: repaint(); break; default: JOptionPane.showMessageDialog(null, "Wrong number of arguments to animate method. " + "The animate method with no arguments should only be called for " + "FILL_VALUES, CLEAR_LIST, REMOVE_LAST_CAR and NONE. " + "It was called with " + ad.getActivity() + ". " + "Terminating program."); System.exit(1); break; } } @Override public void paint(Graphics g) { super.paint(g); if (ad.getActivity() != AutoDisplay.Activity.NONE && ad.getCurrentAuto() != null) { ad.updateAutoDisplay(ad.getCurrentAuto(), g); } else { ad.updateAutoDisplay(g); } } public static void main(String[] args) { app = new ArrayListPractice(); app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void disableButtons() { fillValues.setEnabled(false); printAutoList.setEnabled(false); setValues.setEnabled(false); countFrequency.setEnabled(false); findMaximum.setEnabled(false); clearList.setEnabled(false); removeLast.setEnabled(false); } public void enableButtons() { fillValues.setEnabled(true); printAutoList.setEnabled(true); setValues.setEnabled(true); countFrequency.setEnabled(true); findMaximum.setEnabled(true); clearList.setEnabled(true); removeLast.setEnabled(true); } private class ButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { printAutoListT t = new printAutoListT(app); if (e.getSource() == fillValues) { disableButtons(); fillValues.requestFocus(); ad.setActivity(AutoDisplay.Activity.FILL_VALUES); t.start(); } else if (e.getSource() == printAutoList) { disableButtons(); printAutoList.requestFocus(); ad.setActivity(AutoDisplay.Activity.PRINT_LIST); t.start(); } else if (e.getSource() == setValues) { disableButtons(); setValues.requestFocus(); ad.setActivity(AutoDisplay.Activity.SET_MODELS); t.start(); } else if (e.getSource() == findMaximum) { disableButtons(); findMaximum.requestFocus(); ad.setActivity(AutoDisplay.Activity.FIND_MAX); t.start(); } else if (e.getSource() == countFrequency) { disableButtons(); countFrequency.requestFocus(); ad.setActivity(AutoDisplay.Activity.COUNT_MODEL); t.start(); } else if (e.getSource() == clearList) { disableButtons(); clearList.requestFocus(); ad.setActivity(AutoDisplay.Activity.CLEAR_LIST); t.start(); } else if (e.getSource() == removeLast) { disableButtons(); removeLast.requestFocus(); ad.setActivity(AutoDisplay.Activity.REMOVE_LAST_CAR); t.start(); } } } private class printAutoListT extends Thread { ArrayList arr; ArrayListPractice s1; public printAutoListT(ArrayListPractice s) { arr = ArrayListPracticeBase.carList; s1 = s; } @Override public void run() { startActivity(ad.getActivity()); } } }