cmp326: Programming Methods II LAB on Collection Framework

advertisement
cmp326: Programming Methods II
LAB on Collection Framework and Threads Basics
Task 1: We want to write a program that counts the number of occurrences of each word in a string input
from the keyboard. Create map three times by HashMap, LinkedHashMap, and TreeMap.
(1) Complete the program by filling-out the blank lines of the program template.
(2) Debug the program to see the structure of the three different Map objects created. Make the
statement A as a breakpoint for debugging.
//Write specific statements for importing Collections, Map, HashMap, etc
//Do not write import java.util.*
public class WordCount
{
public static void main( String[] args )
{
// create HashMap to store String keys and Integer values
Map_______________ myMap = new HashMap__________________();
createMap( _______ ); // create map based on user input
System.out.println("HashMap Content: " + myMap);
displayMap( _______); // display map content
// create LinkedHashMap to store String keys and Integer values with initial capacity 12, load
//factor 0.75, accessOrder = false.
Map______________ myLinkedMap = new ________________(___________);
createMap( _________);
System.out.println("LinkedHashMap Content: " + myLinkedMap);
displayMap(____________);
// create TreeMap to store String keys and Integer values with a comparator object that
// oders String key objects in reverse of the natural ordering (i.e., lexicographic ordering). Use
//Collections class method.
Map_____________ myTreeMap = new TreeMap_____________________________
createMap( ________________ );
System.out.println("LinkedHashMap Content: " + myTreeMap);
displayMap(_________________);
//Statement A
System.out.println("This is a dummy statement to create a break point for debugging....");
} // end main
1
// create map from user input
private _________ void createMap( _________________ map )
{
Scanner scanner = new Scanner( ___________ ); // create scanner
System.out.println( "Enter a string:" ); // prompt for user input
String input = scanner.nextLine();
// tokenize the input
String[] tokens = input.split( " " );
// processing input text in the array tokens
for ( _______ token : ___________ )
{
String word = token.______________ // get lowercase word of token
// if the map contains the word
if ( map.containsKey( word ) ) // is word in map
{
int count = map.get( word ); // get current count
map.put( word, count + 1 ); // increment count
} // end if
else
map.put( word, 1 ); // add new word with a count of 1 to map
} // end for
} // end method createMap
// display map content
private ____________ void displayMap( __________________ map )
{
Set< String > keys = map.keySet(); // get keys
// sort keys
TreeSet________ sortedKeys = new TreeSet__________( keys );
System.out.println( "\nMap contains:\nKey\t\tValue" );
// generate output for each key in the TreeSet object
for ( String key : _______________ )
System.out.printf( "%-10s%10s\n", key, map.get( key ) );
System.out.printf(
"\nsize: %d\nisEmpty: %b\n", map.size(), map.isEmpty() );
} // end method displayMap
} // end class WordTypeCount
2
Task 2: Write a program that reads an unspecified number of integers and finds the one that has the most
occurrences. Input ends when a user enters a negative integer value (Use TreeMap).
//Write specific statements for importing classe(s) and interface(s)
//Do not write import java.util.*
public class CountingNumbers {
public static void main(String[] args) {
// Create a tree map to hold an integer value as a key and the number of occurrences as value
_______________________ treeMap = new _____________________();
System.out.println("Enter integer values, to end the program enter a negative integer value");
Scanner kb = new Scanner(__________________);
int number = kb._________ //get an integer value from the keyboard
while (_______________________) {
if (treeMap.get(number) != null) {
int value = ((Integer)treeMap.get(number)).intValue();
value++;
treeMap.put(number, value);
}
else {
treeMap.put(number, 1);
}
number = kb.nextInt();
}
Integer max = (Integer)(Collections.max(treeMap.values()));
Set_________ keys = treeMap.keySet(); //get a set of keys from the map and saves it in a set
________________ iterator = keys.iterator(); //get an iterator object to iterate the set
while (iterator.______________) {
Integer key = iterator.next();
Integer value = (Integer)(treeMap.get(key));
if (value.equals(max)) {
System.out.println("Number " + key + " occurred most");
}
}
}
}
3
Task 3: Write PrintChar.java that prints a specified character in specified times to the console.
PrintChar.java implements java.lang.Runnable interface.
_______________________//import statement(s) if necessary
public class PrintChar _________________________ {
private char charToPrint; // The character to print
private int times; // The times to repeat
/** Construct a task with specified character and number of times to print the character
*/
public PrintChar(_______, ___________) {
charToPrint = c;
times = t;
}
/** Override the run() method to tell the system what the task to perform */
public void run() {
for (int i = 0; i < times; i++) {
System.out.print(charToPrint);
}
}
}
Task 4: Write PrintNum.java that prints numbers from 1 to n to the console. PrintNum.java implements
java.lang.Runnable interface.
_______________________//import statement(s) if necessary
class PrintNum ___________________________ {
private int lastNum;
/** Construct a task for printing 1, 2, ... i */
public PrintNum(int n) {
lastNum = n;
}
public void run() {
for (int i = 1; i <= lastNum; i++) {
System.out.print(" " + i);
}
}//of run
}
Task 5: Write TaskThreadDemo.java that creates 3 threads for printing characters and numbers.
4
_______________________//import statement(s) if necessary
public class TaskThreadDemo {
public static void main(String[] args) {
// Create tasks
Runnable printA = new PrintChar('a', 100);
Runnable printB = new PrintChar('b', 100);
Runnable print100 = new PrintNum(100);
// Create threads
Thread thread1 = new Thread(printA);
Thread thread2 = new Thread(printB);
Thread thread3 = new Thread(print100);
// Start threads
thread1.start();
thread2.start();
thread3.start();
}
}
Task 5: Rewrite the run() method of the PrintNum.java as explained below.

Add two statements before the for statement:
Thread thread4 = new Thread(new PrintChar('c', 40));
thread4.start();

Add the try and catch block (shown below) after System.out.print(….); in the for statement
try{


if(i==50) thread4.join();
}
catch (InterruptedException ex) {
}
This run method enforces the current thread (thread3) waits until thread4 finishes its task.
thread4.join is invoked after 50 numbers are printed out to the console.
Execute TaskThreadDemo.java program to see the effect of thread4.join() method invocation.
Task 6: Rewrite the run() method of the PrintNum.java as follows:
public void run() {
for (int i = 1; i <= lastNum; i++) {
System.out.print(" " + i);
try {
5
if (i >= 50) Thread.sleep(1);
}
catch (InterruptedException ex) {
}
}
}

Execute TaskThreadDemo.java program to see the behavior of the program
Task 7: Write a simple Applet/Frame-based application FlasingText.java. This class impelements
java.lang.Runnable interface.
import javax.swing.*;
public class FlashingText extends JApplet _________________________ {
private static final long serialVersionUID = 1L;
private JLabel jlblText = new JLabel("Welcome", JLabel.CENTER);
public FlashingText() {
add(jlblText);
new Thread(this).start();
}
/** Set the text on/off every 200 milliseconds */
public void run() {
try {
while (true) {
if (jlblText.getText() == null)
jlblText.setText("Welcome");
else
jlblText.setText(null);
Thread.sleep(200);
}
}
catch (InterruptedException ex) {
}
}
/** Main method */
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame("FlashingText");
6
frame.add(new FlashingText());
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
}
});
}
}
Task 8: We want to write a thread that calculates sum of integer values from 1 to upper value. This
program is based on the following two Java classes.
public class Sum
{
private int sum;
public int getSum() {
___________
}
public void setSum(int sum) {
_________ = sum;
}
}
//Summation.java implements java.lang.Runnable interface
class Summation ________________________
{
private int upper;
private Sum sumValue;
public Summation(int upper, Sum sumValue) {
if (upper < 0)
throw new IllegalArgumentException();
_______________ = upper;
________________ = sumValue;
}
public void run() {
int sum = 0;
for (int i = 0; i <= upper; i++)
7
sum += i;
sumValue.setSum(sum);
}
}
public class SumDriver
{
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Usage Driver <integer>");
System.exit(0);
}
Sum ___________ = new Sum(); //identify the object variable name
int upper = Integer._________________(args[0]);
Thread worker = new Thread(new Summation(upper, sumObject));
worker.start();
try {
worker.______ //the main thread waits until worker thread finishes its task
} catch (InterruptedException ie) { }
System.out.println("The sum of " + upper + " is " + sumObject.getSum());
}
}
8
Download