Select a Chapter: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Back to the Main Page
Chapter Twelve listings: 9 classes
import java.io.*; // for FileReader, IOException, and others public class TextFileOp { /** Find the first line that begins with a digit. */ public static String findDigit (String fileName) throws IOException { BufferedReader fi = new BufferedReader (new FileReader (fileName)); String si = fi.readLine(); while (si != null) { if (si.length() > 0 && si.charAt (0) >= '0' && si.charAt (0) <= '9') return si; si = fi.readLine(); } return ""; } //====================== /** Tell whether the two files have the same contents. */ public static boolean compareFiles (String one, String two) throws IOException { BufferedReader inOne = new BufferedReader (new FileReader (one)); BufferedReader inTwo = new BufferedReader (new FileReader (two)); String s1 = inOne.readLine(); String s2 = inTwo.readLine(); while (s1 != null && s2 != null) { if ( ! s1.equals (s2)) return false; s1 = inOne.readLine(); s2 = inTwo.readLine(); } return s1 == s2; // true only when both are null } //====================== /** Print the specified number of lines of random 4-digit * non-negative integers, 5 integers per line. */ public static void createRandoms (String name, int numLines) throws IOException { PrintWriter file = new PrintWriter (new FileWriter (name)); java.util.Random randy = new java.util.Random(); for (int k = 0; k < numLines; k++) { for (int i = 0; i < 4; i++) file.print (randy.nextInt (10000) + " \t"); file.println (randy.nextInt (10000)); } file.close(); } //====================== /** Read from two BufferedReaders known to have their lines in * ascending order. Write all lines to a file named outName * so that the file has its lines in ascending order. */ public static void mergeTwo (BufferedReader inOne, BufferedReader inTwo, String outName) throws IOException { PrintWriter merged = new PrintWriter (new FileWriter (outName)); String s1 = inOne.readLine(); String s2 = inTwo.readLine(); while (s1 != null || s2 != null) { if (s2 == null || s1 != null && s1.compareTo (s2) < 0) { merged.println (s1); s1 = inOne.readLine(); } else // the line from inTwo is next in order { merged.println (s2); s2 = inTwo.readLine(); } } merged.close(); } //====================== // From the exercises /** Print all lines in the file that begin with a capital letter. */ public static void findCaps (String name) throws IOException { BufferedReader fi = new BufferedReader (new FileReader (name)); for (String si = fi.readLine(); si != null; si = fi.readLine()) { if (si.length() > 0 && si.charAt (0) >= 'A' && si.charAt (0) <= 'Z') System.out.println (si); } } //====================== /** Calculate average number of characters per line in the file. */ public static double averageCharsPerLine (String name) throws IOException { BufferedReader file = new BufferedReader (new FileReader (name)); int lines = 0; int count = 0; for (String si = file.readLine(); si != null; si = file.readLine()) { lines++; count += si.length(); } return lines == 0 ? 0 : 1.0 * count / lines; } //====================== /** Tell whether each line in the file is less than or equal to the * one before. */ public static boolean descending (String name) throws IOException { BufferedReader file = new BufferedReader (new FileReader (name)); String previous = file.readLine(); if (previous != null) { for (String si = file.readLine(); si != null; si = file.readLine()) { if (previous.compareTo (si) < 0) return false; previous = si; } } return true; } //====================== /** Copy the infile to the file with the name outName. */ public static void copy (BufferedReader infile, String outName) throws IOException { PrintWriter outfile = new PrintWriter (new FileWriter (outName)); for (String si = infile.readLine(); si != null; si = infile.readLine()) outfile.println (si); outfile.close(); } //====================== }


import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.IOException;

public class Message
{
     private String itsReceiver = null;
     private String itsSubject = null;
     private String itsSender = null;


     /** Create a Message object from the next two lines of the
      *  source file.  Set sender to null at end-of-file. */

     public Message (BufferedReader source) throws IOException
     {    String s = source.readLine();
          if (s != null)
          {    StringTokenizer line = new StringTokenizer (s);
               if (line.hasMoreTokens())
               {    itsSender = line.nextToken();
                    if (line.hasMoreTokens())
                    {    itsReceiver = line.nextToken();
                         itsSubject  = source.readLine();
                    }
               }
          }
     }    //======================


     public String getSender()
     {    return itsSender;
     }    //======================


     public String getReceiver()
     {    return itsReceiver;
     }    //======================


     public String getSubject()
     {    return itsSubject;
     }    //======================
}     


public class EmailSet
{
     public static final int MAX = 50;
     /////////////////////////////////
     private int[][] itsItem = new int[MAX][MAX];  
                    // all components of the array are initially zero
     private int itsSize = 0;     
                    // non-zero entries are indexed 0..itsSize-1
     private int itsNumEmails = 0; // total of all non-zero entries


     /** Return the total number of emails sent. */

     public int getNumEmails()
     {    return itsNumEmails;
     }    //======================


     /** Return the total number of employees sending email. */

     public int getNumEmployees()
     {    return itsSize;
     }    //======================


     /** Return the number of emails sent from from to to. */

     public int numSent (int from, int to)
     {    return itsItem[from][to];
     }    //======================


     /** Return the number of emails sent to code. */

     public int numSentTo (int code)   // in EmailSet
     {    int count = 0;
          for (int from = 0;  from < itsSize;  from++)
               count += itsItem[from][code];
          return count;
     }    //======================


     /** Return the smallest number of emails that code sent anyone. */

     public int minSentFrom (int code)  // version 1; in EmailSet
     {    int min = itsItem[code][0];
          for (int to = 1;  to < itsSize;  to++)
          {    if (min > itsItem[code][to])
                    min =  itsItem[code][to];
          }
          return min;
     }    //======================


     /** Return the smallest number of emails that code sent anyone. */

     public int minSentFromV2 (int code)  // version 2; in EmailSet
     {    int[] oneRow = itsItem[code];  // name the row, for clarity
          int min = oneRow[0]; 
          for (int to = 1;  to < itsSize;  to++)
          {    if (min > oneRow[to])
                    min = oneRow[to];
          }
          return min;
     }    //======================


     public int codeOfMaxSelfSent()  // in EmailSet
     {    int code = 0;
          for (int k = 1;  k < itsSize;  k++)
          {    if (itsItem[code][code] < itsItem[k][k])
                    code = k;
          }
          return code;
     }    //======================


     public boolean anyMoreThan (int cutoff)  // in EmailSet
     {    for (int from = 0;  from < itsSize;  from++)
          {    for (int to = 0;  to < itsSize;  to++)
               {    if (itsItem[from][to] > cutoff)
                         return true;
               }
          }
          return false;
     }    //======================


     // public class EmailSet continued

     private String[] itsName = new String[MAX];

     /** Add the given message to the set of stored emails. */

     public void add (Message given)
     {    int from = findCode (given.getSender());
          int to = findCode (given.getReceiver());
          itsItem[from][to]++;
          itsNumEmails++;
     }    //======================


     /** Precondition:  0 <= code < getNumEmployees() */

     public String findEmployee (int code)
     {    return itsName[code];
     }    //======================


     /** Return the code for the given employee. */

     private int findCode (String employee)
     {    for (int k = 0;  k < itsSize;  k++)
          {    if (employee.equals (itsName[k]))
                    return k;
          }
          itsName[itsSize] = employee;
          itsSize++;
          return itsSize - 1;
     }    //======================


     /** Return the number of emails that code sent. */

     public int numSentFrom (int code)
     {    int count = 0;
          for (int k = 0;  k < itsSize;  k++)
               count += itsItem[code][k];
          return count;
     }    //======================


     /** Return the largest total number of emails sent by anyone. */

     public int mostSent()
     {    int max = numSentFrom (0);
          for (int k = 1;  k < itsSize;  k++)
          {    if (max < numSentFrom (k))
                    max = numSentFrom (k);
          }
          return max;
     }    //======================


     /** Return the number of people to whom code sent email. */

     public int numPeopleSentBy (int code)  // in EmailSet
     {    int count = 0;
          for (int to = 0;  to < itsSize;  to++)
          {    if (itsItem[code][to] > 0)
                    count++;
          }
          return count;
     }    //======================


     /** Return the largest number of emails sent to code. */

     public int maxSentTo (int code)  // in EmailSet
     {    int max = itsItem[0][code];
          for (int from = 1;  from < itsSize;  from++)
          {    if (max < itsItem[from][code])
                    max =  itsItem[from][code];
          }
          return max;
     }    //======================
}     


import java.io.*;

public class EmailStats 
{
     /** Read one day's email file and print several usage
      *  statistics about it. */

     public static void main (String[] args) throws IOException
     {    
          if (args.length < 2)
               System.out.println ("Specify the two file names");
          else
          {
               // CONSTRUCT THE EMAIL FILE AND THE DATABASE
               BufferedReader inputFile = new BufferedReader
                                         (new FileReader (args[0]));
               EmailSet database = new EmailSet();

               // READ THE EMAIL FILE AND STORE IT IN THE DATABASE
               Message data = new Message (inputFile);
               while (data.getSender() != null)
               {    database.add (data);
                    data = new Message (inputFile);
               }

               // PRINT THE RESULTS TO THE OUTPUT FILE
               if (database.getNumEmployees() > 0)
                    EmailOp.printStatistics (database, new PrintWriter 
                                            (new FileWriter (args[1])));
          }
     }    //======================
}     


class EmailOp   // helper class for Email
{
     /** Print the statistics about email usage. Precondition:
      *  db and out are non-null, and db is not empty. */

     public static void printStatistics (EmailSet db, 
                                         PrintWriter out)
     {    // PRINT OVERALL AVERAGE
          int size = db.getNumEmployees();  // for speed of execution
          out.println (db.getNumEmails() + " email sent by "
                        + size + " people; average sent per person = "
                        + (1.0 * db.getNumEmails()) / size);

          // PRINT THOSE WITH HEAVY IMBALANCE IN SENT VS RECEIVED
          for (int k = 0;  k < size;  k++)
          {    String name = db.findEmployee (k);
               if (db.numSentFrom (k) == 0)
                    out.println (name + " did not send any email.");
               else
               {    double ratio = 1.0 * db.numSentTo (k) 
                                       / db.numSentFrom (k);
                    if (ratio >= 2.0)
                         out.println (name + " received twice the sent.");
                    else if (ratio <= 0.5)
                         out.println (name + " sent twice the received.");
                    if (db.numSent (k, k) > 0)
                         out.println (name + " sent himself email.");
               }
          }

          // PRINT THOSE WHO SENT THE MOST AMOUNT OF EMAIL
          int largest = db.mostSent();
          for (int k = 0;  k < size;  k++)
          {    if (db.numSentFrom (k) == largest)
                    out.println (db.findEmployee (k) + " sent most.");
          }
          out.close();
     }    //======================
}


public class Flight
{
     public final String aircraftType;
     public final double ticketPrice;
     public final int    numSeats; // available unreserved
     public final int    numReservations;
     public final long   filePosition;


     public Flight (String type, double price, int seats, 
                    int reservations, long position)
     {    aircraftType = type;
          ticketPrice = price;
          numSeats = seats;
          numReservations = reservations;
          filePosition = position;
     }    //======================
}


public class FlightSet
{
     public static final int MAX = 20;
     /////////////////////////////////
     private Flight[][] plane = new Flight[MAX][MAX];


     /** Return the fare for the flight with the lowest fare.
      *  However, return any value if there are no flights. */

     public double cheapestFare()
     {    double smallestSoFar = 1000000.0;     // a million dollars
          for (int dep = 0;  dep < MAX;  dep++)
          {    for (int arr = 0;  arr < MAX;  arr++)
               {    if (plane[dep][arr] != null
                           && plane[dep][arr].ticketPrice < smallestSoFar)
                         smallestSoFar = plane[dep][arr].ticketPrice;
               }
          }
          return smallestSoFar;
     }    //======================


     /** Write the information to the appropriate disk-file record. */

     public void writeRecord (Flight flit) throws IOException
     {    raf.seek (flit.filePosition);
          raf.writeChars (flit.aircraftType + "\n");
          raf.writeDouble (flit.ticketPrice);
          raf.writeInt (flit.numSeats);
          raf.writeInt (flit.numReservations);
     }    //======================
}


import java.io.Reader;
import java.io.IOException;

public class Buffy
{
     public static final int MAX = 8192;
     /////////////////////////////////
     private Reader itsInput;        // the file or keyboard input
     private char[] itsBuf;          // chars read but not used
     private int itsSize;            // number of chars stored
     private int itsNextChar;        // position of next char 
     private boolean itsAtEndOfFile; // true when no more to read


     public Buffy (Reader given) throws IOException
     {    itsInput = given;
          itsBuf = new char[MAX];
          fillBufferStartingAt (0); // get the first characters
     }    //======================


     private void fillBufferStartingAt (int loc) throws IOException
     {    itsSize = loc + itsInput.read (itsBuf, loc, MAX - loc);
          itsAtEndOfFile = itsSize < MAX;
          if (itsAtEndOfFile)
               itsInput.close();
          itsNextChar = 0;
     }    //======================


     public String readLine() throws IOException
     {    if (itsNextChar >= itsSize - 2000 && ! itsAtEndOfFile)
               downShiftAndFill();
          if (itsNextChar >= itsSize)         // no more characters
               return null;
          int start = itsNextChar;
          int count = 0;
          while (itsBuf[start + count] != '\n')
               count++;
          itsNextChar = start + count + 1;   // prepare for next call
          return new String (itsBuf, start, count);
     }    //======================


     private void downShiftAndFill() throws IOException
     {    for (int k = itsNextChar;  k < itsSize;  k++)
               itsBuf[k - itsNextChar] = itsBuf[k];
          itsSize -= itsNextChar;
          fillBufferStartingAt (itsSize);
     }    //======================
}     


import java.net.*;
import java.io.*;

public class Telnetting
{
     public static void main (String[] args)
     {    try
          {    Handler birthNames = new Handler();
               ServerSocket server = new ServerSocket (12345, 20);
               for (;;)
               {    Socket client = server.accept();  // blocks
                    BufferedReader input = new BufferedReader 
                      (new InputStreamReader(client.getInputStream()));
                    PrintWriter output = new PrintWriter
                                        (client.getOutputStream());
                    birthNames.getMore (input, output);
                    client.close();
               }
          }catch (IOException e)
          {    System.out.println ("could not open server or socket");
          }
     }    //=======================
}
//############################################################



import java.io.*;

public class Handler
{
     private String itsInfo = "";

     public void getMore (BufferedReader input, PrintWriter output)
     {    try 
          {    if (itsInfo.length() > 0)
                    output.println ("Suggestions so far:" + itsInfo);
               output.println ("What do you suggest for a baby name?");
               output.flush();
               String data = input.readLine();
               while (data != null && data.length() > 0)
               {    itsInfo += " " + data;
                    output.println ("Another suggestion? ENTER to quit");
                    output.flush();
                    data = input.readLine();
               }
               output.close();
          }catch (IOException e)
          {    // no need for any statements here
          }
     }    //=======================
}

All information Copyright (c)1999 - Dr. William C. Jones, Jr.
Layout and Design Copyright © Psumonix, LLC. All Rights Reserved.