Section 12.4. Other Useful Classes


[Page 417 (continued)]

12.4. Other Useful Classes

In every programming language, there's a way of extending the basic functionality of the language. In Java, we do this with classes. Java comes with an extensive library of classes that you can use to do a wide range of things, such as accessing the Internet, generating random numbers, and accessing files in a directorya useful thing to do when developing Web pages or working with video. These classes are grouped into packages. We have been working with several classes from the java.io package. But there are many other useful classes and many more packages.

Let's get a list of the contents of a directory as our first example. The class we'll use is the java.io.File class. This is a class that represents a file or directory pathname. There is a list method in the File class that will list all of the files and directories in a directory. It returns an array of String objects.

> import java.io.File; > File dir = new File("C:\\intro-prog-java\\mediasources\\"); > String[] pathArray = dir.list(); > for (int i=0; i < 5; i++) System.out.println(pathArray[i]); swan.jpg MattScotland.jpg twoSwans.jpg kidsTree.jpg redDoor.jpg


We can use the list method to add text to pictures in a directory. We could insert a copyright claim. The method list just returns the base filename and suffix. That's enough to make sure that we have pictures and not sounds or something else. But, it doesn't give us complete paths for creating a new Picture. To get a complete path, we can append the directory to the name we get from the method list.


[Page 418]

Program 110. Add Text to All Pictures in a Directory

import java.io.*; /**  * Class to work with files in a directory  */ public class DirectoryWorker {   /**    * Method to add a string to every picture in directory    * @param dir the name of the directory    * @param text the text of the string to add    */   public void addStringToPictures(String dir, String text)   {     String name = null;     // create the object that represents the directory     File file = new File(dir);     // Get the array of names in the directory     String[] nameArray = file.list();     // loop through the names     for (int i = 0; i < nameArray.length; i++)     {       name = nameArray[i];       // if this is a picture file       if (name.indexOf(".jpg") >= 0)       {         // create the picture object         Picture p = new Picture(dir + name);         // add the text to the picture         p.drawString(text, 5,                      p.getHeight() - 50);         // save the changed picture to a file         p.write(dir + "titled-" + name);       }     }   }   public static void main(String[] args)   {     DirectoryWorker worker = new DirectoryWorker();     worker.addStringToPictures(        "c:\\intro-prog-java\\mediasources\\",        "Copyright 2005");   } }



[Page 419]

How it Works

The method addStringToPictures takes a directory (a path name, as a string) and the text to add as input. It creates a File object using the name of the directory and then it gets a list of file and directory names in that directory using the method list. It loops through the array of names, and if the current name has ".jpg" in it, it will create a Picture object from it and draw a string on the picture. It will then write the changed picture back out adding "titled-" in front of the name. It writes the changed picture to the same directory it read the original picture from.

12.4.1. Another Fun Class: Random

Another fun and useful class is java.util.Random. It is in the java.util package. It has a method nextdouble() that generates random numbers (evenly distributed) between 0 and 1.

> import java.util.Random; > Random randomGen = new Random(); > for (int i = 0; i < 5;  i++)    System.out.println(randomGen.nextDouble()); 0.9534889951932188 0.9713266979695472 0.2678907619250269 0.5310776290468512 0.9586483089727932


It also has a method nextInt(int n) which generates a random number between 0 (inclusive) and n (exclusive). To generate random numbers from 0 to 10 use nextInt(11).

> for (int i = 0; i < 5;  i++)    System.out.println(randomGen.nextInt(11)); 9 1 4 3 8 >


Random numbers can be fun when they're applied to tasks like picking random words from a list. We can generate random sentences by randomly picking nouns, verbs, and phrases from arrays of Strings.

Program 111. Randomly Generate Language
(This item is displayed on pages 419 - 420 in the print version)

import java.util.Random; /**  * Class to generate sentences  * @author Barb Ericson  */ 
[Page 420]
public class SentenceGenerator { /////////// fields ///////////// private String[] nounArray = {"Mark", "Adam", "Angela", "Larry", "Jose", "Matt", "Jim"}; private String[] verbArray = {"runs", "skips", "sings", "leaps", "jumps", "climbs", "argues", "giggles"}; private String[] phraseArray = {"in a tree", "over a log", "very loudly", "around the bush", "while reading the newspaper", "very badly", "while skipping", "instead of grading"}; private Random randGen = new Random(); //////////////// methods /////////////////////////////////// /** * Method to generate a random sentence * @return a random sentence */ public String generateRandomSentence() { String sentence = nounArray[randGen.nextInt(nounArray.length)] + " " + verbArray[randGen.nextInt(verbArray.length)] + " " + phraseArray[randGen.nextInt(phraseArray.length)] + "."; return sentence; } public static void main(String[] args) { SentenceGenerator sentenceGen = new SentenceGenerator(); for (int i = 0; i < 5; i++) System.out.println(sentenceGen.generateRandomSentence()); } }


  > java SentenceGenerator Jose runs around the bush. Mark jumps while reading the newspaper. Matt jumps very badly. Angela skips very loudly. Angela jumps while reading the newspaper.


How it Works

This class has arrays of nouns, verbs, and phrases. The method generateRandom-Sentence uses a random number generator (Random) to randomly pick a noun, verb, and a phrase and it returns the created sentence.

The basic process here is common in simulation programs. What we have here is a structure defined in the program: a definition of what counts as a noun, a verb, and a phrase, and a rule about how to put them together. A sentence is a noun, then a verb, and finally a phrase. The sentence gets filled in with random choices. The interesting question is how much can be simulated with a structure and randomness. Could we simulate intelligence like this? And what's the difference between a simulation of intelligence and a really thinking computer?


[Page 421]

Imagine a program that reads input from the user, then generates a random sentence. Maybe there are a few rules in the program that searches for keywords and responds to those keywords, like:

if (input.indexOf("mother") >= 0)    System.out.println("Tell me more about your mother...");


Joseph Weizenbaum wrote a program like this many years ago, called Doctor (later known as Eliza). His program would act like a Rogerian psychotherapist, echoing back whatever you said, with some randomness in it, but searching for keywords to seem like it was really "listening." It was meant as a joke, not a real effort to create a simulation of intelligence. To Weizenbaum's dismay, people took it seriously! They really started treating it like a therapist. Weizenbaum changed his research direction from artificial intelligence to concern over the ethical use of technology, and how easily people can be fooled by technology.



Introduction to Computing & Programming Algebra in Java(c) A Multimedia Approach
Introduction to Computing & Programming Algebra in Java(c) A Multimedia Approach
ISBN: N/A
EAN: N/A
Year: 2007
Pages: 191

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net