Download sample solutions

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Laboratory 11
Lesson 11-2
Exercise 1
Exercise 2
Exercise 3
Exercise 4
Exercise 5
Exercise 6
Lesson 11-3
Exercise 1
Exercise 2
Exercise 3
Exercise 4
Exercise 5
Exercise 6
Exercise 7
Lesson 11-4
Exercise 1
Exercise 2
Exercise 3
Exercise 4
Exercise 5
Exercise 6
Solutions
Lesson 11-2
Exercise 1:
The following is a sample of the class.
public class IntList
{
// Methods
public void store(int item)
// Pre: The list is not full
// Post: item is in the list
{
values[numItems] = item;
numItems++;
}
public void printList()
// Post: If the list is not empty, the elements are
//
printed on the screen; otherwise "The list
//
is empty" is printed on the screen
{
if (numItems > 0)
for (int i = 0; i < numItems; i++)
System.out.println(values[i]);
else
System.out.println("The list is empty");
}
public int getLength()
// Post: return value is the number of items in the list
{
return numItems;
}
public boolean isEmpty()
// Post: returns true if list is empty; false otherwise
{
return (numItems == 0);
}
public boolean isFull()
// Post: returns true if there is no more room in the
//
list; false otherwise
{
return (values.length == numItems);
}
public IntList(int maxItems)
// Constructor
// Post: Empty list is created with maxItems cells
{
values = new int[maxItems];
numItems = 0;
}
// Data fields
private int numItems;
private int[] values;
}
Exercise 2:
The following is a sample of the driver.
//**********************************************************
// Class UseIntList is a driver for class IntList. The list
// is instantiated, values are read in and printed.
//**********************************************************
import java.io.*;
// Access file classes
import java.util.Scanner;
// Access Scanner
public class UseIntList
{
public static void main(String[] args) throws IOException
{
// Data file for this test is on "real.dat"
Scanner inFile = new Scanner(new FileReader("int.dat"));
// Instantiate list with 15 cells
IntList list = new IntList(15);
while( inFile.hasNextInt() && !list.isFull() )
{
list.store(inFile.nextInt());
}
// Print values on System.out
list.printList();
// Close the input file
inFile.close();
}
}
The last four values are
70
80
90
100
Exercise 3:
public boolean contains(int item)
// Post: returns true if item is in the list; false otherwise
// adapted from page 595 of main text
{
int index = 0;
while ((index < numItems) && (values[index] != item))
index++;
return (index < numItems);
}
Exercise 4:
public void removeItem(int item)
// Pre: value is in the list
// Post: value removed from the list and remaining items shifted up
// adapted from page 596 of main text
{
int index = 0;
boolean found = false;
while ( (index < numItems) && !found )
{
if (values[index] == item)
found = true;
else
index++;
}
if (found)
{
for (int count = index; count < numItems - 1; count++)
values[count] = values[count+1];
numItems--;
}
}
Exercise 5:
Note: Add ‘import java.io.*;” to the class IntList.
public void writeList(String file) throws IOException
// Post: values in the list are written to the file
{
PrintWriter outFile = new PrintWriter(new FileWriter(file));
for ( int index = 0; index < numItems; index++)
outFile.println(values[index]);
outFile.close();
}
Exercise 6:
The following is an example of the driver.
import java.io.*;
// Access file classes
import java.util.Scanner;
// Access Scanner
public class UseIntList
{
public static void main(String[] args) throws IOException
{
// Data file for this test is on "real.dat"
Scanner inFile = new Scanner(new FileReader("int.dat"));
// Instantiate list with 15 cells
IntList list = new IntList(15);
while( inFile.hasNextInt() && !list.isFull() )
{
list.store(inFile.nextInt());
}
// Print values on System.out
System.out.println(
"Write the values in the list to file newInt.dat:" );
list.printList();
list.writeList( "newInt.dat" );
System.out.println();
// Search for values and print result
System.out.println("Look for a value that is there (10):
" +
list.contains(10) );
System.out.println("Look for a value that is NOT there (5):" +
list.contains(5) );
System.out.println();
// delete value 10 and print the list
System.out.println(
"Delete a value (10) and print the list with the value removed: ");
list.removeItem(10);
list.printList();
// Close the input file
inFile.close();
}
}
The driver output is
Write the values in the list to file newInt.dat:
10
20
30
40
50
60
70
80
90
100
Look for a value that is there (10):
true
Look for a value that is NOT there (5): false
Delete a value (10) and print the list with the value removed:
20
30
40
50
60
70
80
90
100
Lesson 11-3
Exercise 1:
The following is a sample of the class.
public class SList
{
// Methods
public void insert(int item)
// Pre: The list is not full
//
item is not in the list
// Post: item is in the list; the items are in sorted order
// Modeled on example on page 612 of main text (see method 'add')
{
if (!isFull())
{
int index = numItems - 1; //Loop control variable
while ((index >= 0) && (item < values[index]))
{ // find insertion point
values[index+1] = values[index];
index--;
}
values[index+1] = item; // Insert item
numItems++; // Increment item count
}
}
public void printList()
// Post: If the list is not empty, the elements are
//
printed on the screen; otherwise "The list
//
is empty" is printed on the screen
{
if (numItems > 0)
for (int i = 0; i < numItems; i++)
System.out.println(values[i]);
else
System.out.println("The list is empty");
}
public int getLength()
// Post: return value is the number of items in the list
{
return numItems;
}
public boolean isEmpty()
// Post: returns true if list is empty; false otherwise
{
return (numItems == 0);
}
public boolean isFull()
// Post: returns true if there is no more room in the
//
list; false otherwise
{
return (values.length == numItems);
}
public SList(int maxItems)
// Constructor
// Post: Empty list is created with maxItems cells
{
values = new int[maxItems];
numItems = 0;
}
// Data
private
private
fields
int numItems;
int[] values;
}
Exercise 2:
Note: Reorder the test data sequence so that it is not in ascending order. This is needed to
test the new insert method.
The following is a sample test driver.
//**********************************************************
// Class UseSList is a driver for class SList. The list
// is instantiated, values are read in and printed.
//**********************************************************
import java.io.*;
// Access file classes
import java.util.Scanner;
// Access Scanner
public class UseSList
{
public static void main(String[] args) throws IOException
{
// Data file for this test is on "real.dat"
Scanner inFile = new Scanner(new FileReader("int01.dat"));
// Instantiate list with 15 cells
SList list = new SList(15);
while( inFile.hasNextInt() && !list.isFull() )
{
list.insert(inFile.nextInt());
}
// Print values on System.out
list.printList();
// Close the input file
inFile.close();
}
}
The last four values are
70
80
90
100
Exercise 3:
Yes, all methods were reused except the method ‘store’, which is replaced with a new
method ‘insert’.
Exercise 4:
The following is the method ‘contains’ based on the binary search algorithm.
public boolean contains(int item)
// Post: returns true if item is in the list; false otherwise
// adapted from page 619 of main text
{
int first = 0;
int last = numItems - 1;
int middle;
boolean found = false;
while ((last >= first) && !found )
{
middle = (first + last ) / 2;
if ( item == values[middle] )
found = true;
else if ( item < values[middle] )
last = middle - 1;
else
first = middle + 1;
}
return found;
}
Exercise 5:
The following are the methods ‘resetList’, ‘hasNext’, and ‘next’.
// the next three methods adapted from page 597 of main text
public void resetList()
// Set currentItem to 0
{
currentItem = 0;
}
public int next()
// Returns the item at values[currentItem]
// Increments currentItem
{
int next = values[currentItem];
currentItem++;
return next;
}
public boolean hasNext()
// Returns true if currentItem is not equal to numItems
{
return (currentItem < numItems);
}
Exercise 6:
The following is a sample test driver.
//**********************************************************
// Class UseSList is a driver for class SList. The list
// is instantiated, values are read in and printed.
//**********************************************************
import java.io.*;
// Access file classes
import java.util.Scanner;
// Access Scanner
public class UseSList
{
public static void main(String[] args) throws IOException
{
// Data file for this test is on "real.dat"
Scanner inFile = new Scanner(new FileReader("int01.dat"));
// Instantiate list with 15 cells
SList list = new SList(15);
// Insert values
while( inFile.hasNextInt() && !list.isFull() )
{
list.insert(inFile.nextInt());
}
System.out.println();
//Search for values and print result
System.out.println("Look for a value that is there (10):
" +
list.contains(10) );
System.out.println("Look for a value that is NOT there (5):" +
list.contains(5) );
System.out.println();
// Print values on System.out
System.out.println( "Print the list with 'hasNext' and 'next':" );
while( list.hasNext() )
System.out.print( list.next() + " " );
System.out.println("\n");
list.resetList();
System.out.println( "Reset the list and print again:" );
while( list.hasNext() )
System.out.print( list.next() + " " );
System.out.println();
// Close the input file
inFile.close();
}
}
The driver output is
Look for a value that is there (10):
true
Look for a value that is NOT there (5): false
Print the list with 'hasNext' and 'next':
10 20 30 40 50 60 70 80 90 100
Reset the list and print again:
10 20 30 40 50 60 70 80 90 100
Exercise 7:
The print method always iterates through the entire list.
The three other methods appear to be more flexible; they provide access to individual list
items. We can perform both complete and/or selective list iterations using these three
methods.
Lesson 11-4
Exercise 1:
The following is an example of AbstractList.
import java.io.*;
public abstract class AbstractList
{
public AbstractList(int maxItems)
// Constructor
// Post: Empty list is created with maxItems cells
{
values = new int[maxItems];
numItems = 0;
}
// Abstract Methods
public abstract void store(int item);
// Pre: The list is not full
// Post: item is in the list
public abstract boolean contains(int item);
// Post: returns true if item is in the list; false otherwise
// Implemented Methods
public void printList()
// Post: If the list is not empty, the elements are
//
printed on the screen; otherwise "The list
//
is empty" is printed on the screen
{
if (numItems > 0)
for (int i = 0; i < numItems; i++)
System.out.println(values[i]);
else
System.out.println("The list is empty");
}
public int getLength()
// Post: return value is the number of items in the list
{
return numItems;
}
public boolean isEmpty()
// Post: returns true if list is empty; false otherwise
{
return (numItems == 0);
}
public boolean isFull()
// Post: returns true if there is no more room in the
//
list; false otherwise
{
return (values.length == numItems);
}
public void removeItem(int item)
// Pre: value is in the list
// Post: value removed from the list and remaining items shifted up
// adapted from page 596 of main text
{
int index = 0;
boolean found = false;
while ( (index < numItems) && !found )
{
if (values[index] == item)
found = true;
else
index++;
}
if (found)
{
for (int count = index; count < numItems - 1; count++)
values[count] = values[count+1];
numItems--;
}
}
public void writeList(String file) throws IOException
// Post: values in the list are written to the file
{
PrintWriter outFile = new PrintWriter(new FileWriter(file));
for ( int index = 0; index < numItems; index++)
outFile.println(values[index]);
outFile.close();
}
// Data fields
protected int numItems;
protected int[] values;
}
Exercise 2:
The following is an implementation of IntList derived from AbstractList.
import java.io.*;
public class IntList2 extends AbstractList
{
public IntList2(int maxItems)
// Constructor
// Post: Empty list is created with maxItems cells
{
super( maxItems );
}
// IntList implementation of Abstract Methods
public void store(int item)
// Pre: The list is not full
// Post: item is in the list
{
values[numItems] = item;
numItems++;
}
public boolean contains(int item)
// Post: returns true if item is in the list; false otherwise
// adapted from page 595 of main text
{
int index = 0;
while ((index < numItems) && (values[index] != item))
index++;
return (index < numItems);
}
}
Use the driver from Lesson 11-2: Exercise 6.
Change
IntList list = new IntList(15);
to
IntList2 list = new IntList2(15);
The driver produces the same output shown in Lesson 11-2: Exercise 6.
Exercise 3:
The following is an implementation of SList.
public class SList2 extends AbstractList
{
public SList2(int maxItems)
// Constructor
// Post: Empty list is created with maxItems cells
{
super( maxItems );
currentItem = 0;
}
// SList implementation of Abstract Methods
public void store(int item)
// Pre: The list is not full
//
item is not in the list
// Post: item is in the list; the items are in sorted order
// Modeled on example on page 612 of main text (see method 'add')
{
if (!isFull())
{
int index = numItems - 1; //Loop control variable
while ((index >= 0) && (item < values[index]))
{ // find insertion point
values[index+1] = values[index];
index--;
}
values[index+1] = item; // Insert item
numItems++; // Increment item count
}
}
public boolean contains(int item)
// Post: returns true if item is in the list; false otherwise
// adapted from page 619 of main text
// uses the binary search algorithm
{
int first = 0;
int last = numItems - 1;
int middle;
boolean found = false;
while ((last >= first) && !found )
{
middle = (first + last ) / 2;
if ( item == values[middle] )
found = true;
else if ( item < values[middle] )
last = middle - 1;
else
first = middle + 1;
}
return found;
}
// Methods specific to SList
// the next three methods adapted from page 597 of main text
public void resetList()
// Set currentItem to 0
{
currentItem = 0;
}
public int next()
// Returns the item at values[currentItem]
// Increments currentItem
{
int next = values[currentItem];
currentItem++;
return next;
}
public boolean hasNext()
// Returns true if currentItem is not equal to numItems
{
return (currentItem < numItems);
}
// Data fields
private int currentItem;
}
The following is an example of the test driver.
import java.io.*;
// Access file classes
import java.util.Scanner;
// Access Scanner
public class UseSList2
{
public static void main(String[] args) throws IOException
{
// Data file for this test is on "real.dat"
Scanner inFile = new Scanner(new FileReader("int01.dat"));
// Instantiate list with 15 cells
SList2 list = new SList2(15);
// Insert values
while( inFile.hasNextInt() && !list.isFull() )
{
list.store(inFile.nextInt());
}
System.out.println();
//Search for values and print result
System.out.println("Look for a value that is there (10):
" +
list.contains(10) );
System.out.println("Look for a value that is NOT there (5):" +
list.contains(5) );
System.out.println();
// Print values on System.out
System.out.println( "Print the list with 'hasNext' and 'next':" );
while( list.hasNext() )
System.out.print( list.next() + " " );
System.out.println("\n");
list.resetList();
System.out.println( "Reset the list and print again:" );
while( list.hasNext() )
System.out.print( list.next() + " " );
System.out.println();
// Close the input file
inFile.close();
}
}
The output is the same. See Lesson 11-3: Exercise 6.
Exercise 4:
The methods ‘store’ and ‘contains’ have to be abstract because their implementations for
IntList and SList are different.
Any other method that serves both lists (IntList and SList) without modification could be
concrete.
Exercise 5:
The following is AbstractList using Comparable as the class of items on the list.
import java.io.*;
public abstract class AbstractListComparable
{
public AbstractListComparable(int maxItems)
// Constructor
// Post: Empty list is created with maxItems cells
{
values = new Comparable[maxItems];
numItems = 0;
}
// Abstract Methods
public abstract void store( Comparable item );
// Pre: The list is not full
// Post: item is in the list
public abstract boolean contains( Comparable item );
// Post: returns true if item is in the list; false otherwise
public abstract void removeItem( Comparable item );
// Pre: value is in the list
// Post: value removed from the list and remaining items shifted up
// Implemented Methods
public void printList()
// Post: If the list is not empty, the elements are
//
printed on the screen; otherwise "The list
//
is empty" is printed on the screen
{
if (numItems > 0)
for (int i = 0; i < numItems; i++)
System.out.println(values[i]);
else
System.out.println("The list is empty");
}
public int getLength()
// Post: return value is the number of items in the list
{
return numItems;
}
public boolean isEmpty()
// Post: returns true if list is empty; false otherwise
{
return (numItems == 0);
}
public boolean isFull()
// Post: returns true if there is no more room in the
//
list; false otherwise
{
return (values.length == numItems);
}
public void writeList(String file) throws IOException
// Post: values in the list are written to the file
{
PrintWriter outFile = new PrintWriter(new FileWriter(file));
for ( int index = 0; index < numItems; index++)
outFile.println(values[index]);
outFile.close();
}
// Data fields
protected int numItems;
protected Comparable[] values;
}
Exercise 6:
The following is SList derived from AbstractListComparable, where the items on the list
are of class String.
public class SListComparable extends AbstractListComparable
{
public SListComparable(int maxItems)
// Constructor
// Post: Empty list is created with maxItems cells
{
super( maxItems );
currentItem = 0;
}
// SListComparable implementation of Abstract Methods
public void store( Comparable item )
// Pre: The list is not full
//
item is not in the list
// Post: item is in the list; the items are in sorted order
// Modeled on example on page 612 of main text (see method 'add')
{
if (!isFull())
{
int index = numItems - 1; //Loop control variable
while ((index >= 0) &&
(((String)item).compareTo((String)values[index])< 0))
{ // find insertion point
values[index+1] = values[index];
index--;
}
values[index+1] = item; // Insert item
numItems++; // Increment item count
}
}
public boolean contains( Comparable item )
// Post: returns true if item is in the list; false otherwise
// adapted from page 619 of main text
// uses the binary search algorithm
{
int first = 0;
int last = numItems - 1;
int middle;
boolean found = false;
while ((last >= first) && !found )
{
middle = (first + last ) / 2;
if (((String)item).compareTo((String)values[middle]) == 0)
found = true;
else if (((String)item).compareTo((String)values[middle]) < 0)
last = middle - 1;
else
first = middle + 1;
}
return found;
}
public void removeItem( Comparable item )
// Pre: value is in the list
// Post: value removed from the list and remaining items shifted up
// adapted from page 596 of main text
{
int index = 0;
boolean found = false;
while ( (index < numItems) && !found )
{
if (((String)values[index]).compareTo((String)item) == 0 )
found = true;
else
index++;
}
if (found)
{
for (int count = index; count < numItems - 1; count++)
values[count] = values[count+1];
numItems--;
}
}
// Methods specific to SList
// the next three methods adapted from page 597 of main text
public void resetList()
// Set currentItem to 0
{
currentItem = 0;
}
public String next()
// Returns the item at values[currentItem]
// Increments currentItem
{
String next = (String)values[currentItem];
currentItem++;
return next;
}
public boolean hasNext()
// Returns true if currentItem is not equal to numItems
{
return (currentItem < numItems);
}
// Data fields
private int currentItem;
}
The following is an example of a test driver.
import java.io.*;
// Access file classes
import java.util.Scanner;
// Access Scanner
public class UseSListComparable
{
public static void main(String[] args) throws IOException
{
// Data file for this test is on "real.dat"
Scanner inFile = new Scanner(new FileReader("strings.dat"));
// Instantiate list with 15 cells
SListComparable list = new SListComparable(15);
// Insert values
while( inFile.hasNextLine() && !list.isFull() )
{
list.store(inFile.nextLine());
}
// Print the list
list.printList();
// Close the input file
inFile.close();
}
}
The last two items printed are
white
yellow
Related documents