home *** CD-ROM | disk | FTP | other *** search
/ Java 1.2 How-To / JavaHowTo.iso / code / ch02.txt next >
Text File  |  1998-12-14  |  20KB  |  783 lines

  1. Convert.java:
  2.  
  3.  
  4. /*
  5. Convert.class prints a short table of common conversion factors.
  6. */
  7.  
  8. class Convert {
  9.  
  10. /*
  11.  * Note that the main method must be defined as
  12. * public static void main (String []) to be called from
  13.  * the Java interpreter.
  14.  */
  15.  
  16. public static void main (String args[]) {
  17.    
  18.    double mi_to_km = 1.609;
  19.    double gals_to_l = 3.79;
  20.    double kg_to_lbs = 2.2;
  21.  
  22.    System.out.print ("1 Mile equals\t");   
  23. System.out.print (mi_to_km);
  24.    System.out.println ("\tKilometers");    
  25.  
  26.    System.out.print ("1 Gallon equals\t");
  27.    System.out.print (gals_to_l);
  28.    System.out.print ("\tLiters\n");        
  29.  
  30.    System.out.print ("1 Kilogram equals\t");
  31.    System.out.print (kg_to_lbs);
  32.    System.out.println ("\tPounds");
  33. }
  34. }
  35.  
  36.  
  37.  
  38.  
  39.  
  40.  
  41.  
  42.  
  43. Input.java:
  44.  
  45. import java.io.*;
  46.  
  47. /*
  48.  * Input.class reads a line of text from standard input,
  49.  * determines the length of the line, and prints it.
  50.  */
  51.  
  52. class Input {
  53. public static void main (String args[]) {
  54.        String input = "";
  55.        boolean error;
  56.  
  57. /*
  58.  * BufferedReader contains the readLine method.
  59.  * Create a new instance for standard input System.in
  60.  */
  61. BufferedReader in = new BufferedReader (new InputStreamReader(System.in));
  62. /*
  63.  * This loop is used to catch I/O exceptions that may occur
  64.  */
  65.       do {
  66.              error = false;
  67.              System.out.print ("Enter the string > ");
  68.  
  69. /*
  70.  * We need to flush the output - no newline at the end
  71. */
  72.              System.out.flush ();
  73.  
  74.              try {
  75.                   input = in.readLine ();       
  76. } catch (IOException e) {
  77.                   System.out.println (e);       
  78. System.out.println ("An input error was caught");
  79. error = true;
  80.              }
  81.       } while (error);
  82.        
  83.       System.out.print ("You entered \"");
  84.       System.out.print (input);      /
  85. System.out.println ("\"");
  86.       System.out.print ("The length is ");
  87.       System.out.println (input.length ());     
  88. } // end of main ()
  89.  
  90.  
  91.  
  92.  
  93.  
  94.  
  95. Tip.java:
  96.  
  97. import java.io.*;
  98.  
  99. /*
  100.  * Tip.class calculates the tip, given the bill and tip percentage
  101.  */
  102.  
  103. class Tip {
  104. public static void main (String args[]) {
  105.        String input = "";
  106.        int tip_percent=0;
  107.        double bill=0, tip=0;
  108.        boolean error;
  109.  
  110.       BufferedReader in = new BufferedReader (new InputStreamReader(System.in));
  111.  
  112.        do {
  113.                error = false;
  114.                System.out.print ("Enter the bill total > ");
  115.                System.out.flush ();
  116.                try {
  117.                       input = in.readLine ();
  118.                } catch (IOException e) {
  119.                       System.out.println (e);
  120.                       System.exit (1);
  121.                }
  122.  
  123. /*
  124.  * Convert input string to double, 
  125. */
  126.                try {
  127.                       bill = Double.valueOf (input).doubleValue();
  128. } catch (NumberFormatException e) {
  129.                       System.out.println (e);
  130.                       System.out.println ("Please try again");
  131.                       error = true;
  132.                }
  133.        } while (error);
  134.  
  135.         do {
  136.                error = false;
  137.                System.out.print ("Enter the tip amount in percent > ");
  138. System.out.flush ();
  139.                try {
  140.                        input = in.readLine ();
  141.                } catch (IOException e) {
  142.                        System.out.println (e);
  143.                        System.exit (1); 
  144.                }
  145.  
  146. /*
  147.  * This time convert to Integer
  148.  */
  149.                try {
  150.                       tip_percent = Integer.valueOf (input).intValue();
  151. } catch (NumberFormatException e) {
  152.                       System.out.println (e);
  153.                       System.out.println ("Please try again");
  154.                       error = true;
  155.                }
  156.        } while (error);
  157.  
  158.        System.out.print ("The total is ");
  159.         tip = bill * ((double) tip_percent)/100.0;
  160.         System.out.println (bill + tip);
  161. } // end of main ()
  162. }
  163.  
  164.  
  165.  
  166.  
  167. BigNum.java:
  168.  
  169. /*
  170.  * BigNum.class converts a very large number to a string
  171.  * and then prints it out
  172.  */
  173. class BigNum {
  174.  
  175. public static void main (String args[]) {
  176.  
  177. /*
  178.  * Good thing longs are 64 bits! 
  179.  */
  180.     long debt = 3965170506502L; 
  181.     long pop = 250410000;
  182.  
  183.     print ("The 1992 national debt was $", debt);
  184.     print ("The  1992 population was ", pop);
  185.     print ("Each person owed $", debt/pop);
  186. }
  187.  
  188. /*
  189.  * print method converts a long to a string with commas
  190. * for easy reading.  We need it with these big numbers!
  191.  *    String str        preceding label
  192.  *     long n        the long to format and print
  193.  */
  194. public static void print (String str,long n) {
  195.     System.out.print (str);        // print the label
  196.     String buf = String.valueOf (n);    // Integer to String
  197.  
  198.     int start, end, ncommas, i;
  199.     int buflen = buf.length ();
  200.  
  201. /*
  202.  * It's a crazy algorithm, It works from left to right
  203. */
  204.     ncommas = buflen/3;
  205.     if (ncommas * 3 == buflen) ncommas -= 1; 
  206.     start = 0;
  207.     end = buflen-(3*ncommas);
  208.     System.out.print (buf.substring (start, end));
  209.     for (i=0; i<ncommas; i+=1) {
  210.         start = end;
  211.         end = start+3;
  212.         System.out.print (",");
  213.         System.out.print (buf.substring (start, end));
  214.     }
  215.     System.out.println ("");    // The final newline
  216. }
  217. }
  218.  
  219.  
  220.  
  221.  
  222.  
  223.  
  224.  
  225. Parms.java:
  226.  
  227. /* Parms.class prints the month and year, which are passed in
  228.  * as command-line arguments
  229.  */
  230. class Parms {
  231.  
  232. public static void main (String args[]) {
  233.  
  234. /*
  235.  * Java, unlike C/C++, does not need argument count (argc)
  236.  */
  237.         if (args.length < 2) {
  238.                System.out.println ("usage: java Parms <month> <year>");
  239. System.exit (1);
  240.         }
  241.  
  242. /*
  243.  * Unlike in C/C++, args[0] is the FIRST argument.  
  244. * The application name is not available as an argument
  245.  */
  246.         int month = Integer.valueOf (args[0]).intValue();
  247.         int year = Integer.valueOf (args[1]).intValue();
  248.         if (month < 1 || month > 12) {
  249.                System.out.println ("Month must be between 1 and 12");
  250. System.exit (1);
  251.         }
  252.         if (year < 1970) {
  253.                System.out.println ("Year must be greater than 1969");
  254. System.exit (1);
  255.         }
  256.  
  257.         System.out.print ("The month that you entered is  ");
  258.         System.out.println (month);
  259.         System.out.print ("The year that you entered is  ");
  260.         System.out.println (year);
  261. }
  262. }
  263.  
  264.  
  265.  
  266.  
  267.  
  268. More.java:
  269.  
  270. import java.io.*;
  271.  
  272. /*
  273.  * More.class similar to UNIX more utility
  274.  */
  275. class More {
  276.  
  277. public static void main (String args[])
  278. {
  279.        String buf;
  280.        FileInputStream fs=null;
  281.        int nlines;
  282.  
  283.        if (args.length != 1) {
  284.                System.out.println ("usage: java More <file>");
  285.                System.exit (1);
  286.         }
  287.  
  288. /*
  289.  * Try to open the filename specified by args[0]
  290.  */
  291.        try {
  292.                fs = new FileInputStream (args[0]);
  293.        } catch (Exception e) {
  294.                System.out.println (e);
  295.                System.exit (1);
  296.         }
  297.         
  298. /*
  299.  * Create a BufferedReader associated with FileInputStream fs
  300. *
  301. */
  302.       BufferedReader ds = new BufferedReader(new InputStreamReader(fs));
  303. BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
  304.  
  305.  
  306.         nlines = 0;
  307.         while (true) {
  308.                try {
  309.                       buf = ds.readLine ();        // read 1 line
  310.                       if (buf == null) break;
  311.                } catch (IOException e) {
  312.                       System.out.println (e);      
  313.                       break;
  314.                }
  315.                System.out.println (buf); 
  316. nlines += 1;
  317.                if (nlines % 23 == 0) {  // 23 lines/pages vt100
  318. System.out.print ("-More-");
  319.                       System.out.flush ();
  320.                       try {
  321.                               keyboard.readLine ();
  322.                       } catch (IOException e) {
  323.                       }
  324.                }
  325.         }
  326. /*
  327.  * close can throw an exception also, 
  328.  * and catch it for completeness
  329. */
  330.          try {
  331.                fs.close ();
  332.        } catch (IOException e) {
  333.                System.out.println (e);
  334.         }
  335. }
  336. }
  337.  
  338.  
  339.  
  340.  
  341.  
  342.  
  343.  
  344. Format.java:
  345.  
  346. import java.io.*;
  347.  
  348. /*
  349. Format.class translates a text file 
  350. * to either DOS, Mac, or UNIX
  351. * format.  The differences are in line termination.
  352.  */
  353. class Format {
  354.  
  355. static final int TO_DOS = 1;
  356. static final int TO_MAC = 2;
  357. static final int TO_UNIX = 3;
  358. static final int TO_UNKNOWN = 0;
  359.  
  360. static void usage () {
  361.         System.out.print ("usage: java Format -dmu <in-file> ");
  362.         System.out.println ("<out-file>");
  363.         System.out.println ("\t-d converts <in-file> to DOS");
  364.         System.out.println ("\t-m converts <in-file> to MAC");
  365.         System.out.println ("\t-u converts <in-file> to UNIX");
  366. }
  367.  
  368. public static void main (String args[])
  369. {
  370.         int format=TO_UNKNOWN;
  371.         String buf;
  372.         FileInputStream fsIn = null;
  373.         FileOutputStream fsOut = null;
  374.  
  375.        if (args.length != 3) { // you must specify format, in, out
  376. usage ();
  377.                System.exit (1);
  378.         }
  379.  
  380. /*
  381. args[0] is a String, so we can use 
  382.  * the equals (String) method for
  383. * comparisons
  384.  */
  385.         if (args[0].equals ("-d")) format = TO_DOS; else
  386.         if (args[0].equals ("-m")) format = TO_MAC; else
  387.         if (args[0].equals ("-u")) format = TO_UNIX; else {
  388.                usage ();
  389.                System.exit (1);
  390.         }
  391.         
  392.         try {
  393.               fsIn = new FileInputStream (args[1]);
  394.         } catch (Exception e) {
  395.                System.out.println (e);
  396.                System.exit (1);
  397.         }
  398.  
  399. /*
  400.  * FileOutputStream is the complement of FileInputStream
  401.  */
  402.         try {
  403.                fsOut = new FileOutputStream (args[2]);
  404.         } catch (Exception e) {
  405.                System.out.println (e);
  406.                System.exit (1); 
  407.         }
  408.       BufferedReader dsIn = new BufferedReader(new InputStreamReader(fsIn));
  409.  
  410.         PrintStream psOut = new PrintStream (fsOut);
  411.         while (true) {
  412.               try {
  413.                       buf = dsIn.readLine ();
  414.                       if (buf == null) break;        // break on EOF
  415.               } catch (IOException e) {
  416.                       System.out.println (e);
  417.                       break;
  418.                }
  419.                psOut.print (buf);
  420.                switch (format) {
  421.                       case TO_DOS:
  422.                       psOut.print ("\r\n");
  423.                       break;
  424.                       
  425.                       case TO_MAC:
  426.                       psOut.print ("\r");
  427.                       break;
  428.                       
  429.                       case TO_UNIX:
  430.                       psOut.print ("\n");
  431.                       break;               
  432.               }
  433.         }
  434.         
  435. /*
  436. */
  437.        try {
  438.                fsIn.close ();
  439.                fsOut.close ();
  440.         } catch (IOException e) {
  441.                System.out.println (e);
  442.         }
  443. }
  444. }
  445.  
  446.  
  447.  
  448.  
  449.  
  450.  
  451.  
  452.  
  453. Stringcat.java:
  454.  
  455. import java.io.*;
  456.                                                     
  457. /*
  458.  * Stringcat.class prints integers and strings together.
  459.  */
  460. class Stringcat {
  461.  
  462. public static void main (String args[]) {
  463.         String today = "";
  464.         int monthday = 15;
  465.  
  466. /* The string "Today is " and date are concatenated together and
  467.  * assigned to the String today.
  468.  */
  469.         today = "Today is the " + monthday + "th";
  470.  
  471. /* The String today is printed with println
  472.  */
  473.         System.out.println (today);
  474.  
  475. /* Here two text strings are concatenated with the integer
  476.    monthday within the println method.
  477.  */
  478.         System.out.println ("Today is the " + monthday +
  479.         " day of the month");
  480.  
  481. } // end of main ()
  482. }
  483.  
  484.  
  485.  
  486.  
  487.  
  488.  
  489.  
  490.  
  491. Sort.java:
  492.  
  493. import java.io.*;
  494.  
  495. /*
  496.  * Sort.class reads a text file specified by args[0] and
  497.  * sorts each line for display
  498.  */
  499. class Sort {
  500.  
  501. static final int NMaxLines = 128;    // an arbitrary limit
  502.  
  503. public static void main (String args[]) {
  504. /*
  505.  * Allocate new array of strings; this is where the file
  506.  * is read and sorted in place
  507.  */
  508.        String sortArray[] = new String [NMaxLines];
  509.        FileInputStream fs=null;
  510.        int nlines;
  511.  
  512.        if (args.length != 1) {
  513.                System.out.println ("usage: java Sort <file>");
  514.                System.exit (1);
  515.         }
  516.         try {
  517.                fs = new FileInputStream (args[0]);
  518.         } catch (Exception e) {
  519.                System.out.println ("Unable to open "+args[0]);
  520.                System.exit (1);
  521.         }
  522.       
  523.        BufferedReader ds = new BufferedReader(new InputStreamReader(fs));
  524.  
  525.         for (nlines=0; nlines<NMaxLines; nlines += 1) {
  526.                try {
  527.                       sortArray[nlines] = ds.readLine ();
  528.                       if (sortArray[nlines] == null) break;
  529.                } catch (IOException e) {
  530.                       System.out.println("Exception caught during read."); 
  531. break;
  532.                }
  533.         }
  534.         try {
  535.                fs.close ();
  536.         } catch (IOException e) {
  537.                System.out.println ("Exception caught closing file."); 
  538. }
  539.  
  540. /*
  541.  * Sort in place and print
  542.  */     
  543.         QSort qsort = new QSort ();
  544.         qsort.sort (sortArray, nlines);
  545.         print (sortArray, nlines);
  546. }
  547.  
  548. /*
  549.  * print method prints an array of strings of n elements
  550.  *      String a[]    array of strings to print
  551.  *      int n         number of elements
  552.  */
  553. private static void print (String a[], int n) {
  554.         int i;
  555.         
  556.         for (i=0; i<n; i+=1) System.out.println (a[i]);
  557.         System.out.println ("");
  558. }
  559. }
  560.  
  561. /*
  562.  * QSort.class uses the standard quicksort algorithm
  563.  * Detailed explanation of the techniques are found in online help
  564. */
  565. class QSort {
  566.  
  567. /*
  568.  * This is used internally, so make it private
  569.  */
  570. private void sort (String a[], int lo0, int hi0) {
  571.         int lo = lo0;
  572.         int hi = hi0;
  573.  
  574.         if (lo >= hi) return;
  575.         String mid = a[(lo + hi) / 2];
  576.         while (lo < hi) {
  577.                while (lo<hi && a[lo].compareTo (mid) < 0) lo += 1;
  578. while (lo<hi && a[hi].compareTo (mid) > 0) hi -= 1;
  579. if (lo < hi) {
  580.                       String T = a[lo];
  581.                       a[lo] = a[hi];
  582.                       a[hi] = T; 
  583.                }
  584.         }
  585.         if (hi < lo) {
  586.                int T = hi;
  587.                hi = lo;
  588.                lo = T;
  589.         }
  590.         sort(a, lo0, lo);    // Yes, it is recursive
  591.         sort(a, lo == lo0 ? lo+1 : lo, hi0); 
  592. }
  593.  
  594. /*
  595.  * The method called to start the sort
  596.  *    String a[]    an array of strings to be sorted in place
  597.  *    int n        the number of elements in the array
  598.  */
  599. public void sort (String a[], int n) {
  600.        sort (a, 0, n-1);
  601. }
  602. }
  603.  
  604.  
  605.  
  606.  
  607.  
  608. Phone.java:
  609.  
  610. import java.io.*;
  611. import java.util.StringTokenizer;
  612.  
  613. /*
  614.  * Phone.class implements a simple phone book with fuzzy
  615.  * name lookup.  The phone book file could be created with a
  616.  * text editor or a spreadsheet saved as tab-delimited text.
  617.  */
  618. class Phone {
  619.  
  620. public static void main (String args[])
  621. {
  622.         String buf;
  623.         FileInputStream fs=null;
  624.  
  625.         if (args.length != 1) {
  626.                System.out.println ("usage: java Phone <name>");
  627.                System.exit (1);
  628.         }
  629.  
  630. /*
  631.  * PhoneBook.txt is the name of the phone book file.
  632.  */
  633.        try {
  634.               fs = new FileInputStream ("PhoneBook.txt");
  635.        } catch (Exception e) {
  636.                System.out.println ("Unable to open PhoneBook.txt");
  637. System.exit (1);
  638.        }
  639.       BufferedReader ds = new BufferedReader(new InputStreamReader(fs));
  640. while (true) {
  641.                try {
  642.                       buf = ds.readLine ();
  643.                       if (buf == null) break;
  644.                } catch (IOException e) {
  645.                       System.out.println ("Exception caught reading file."); 
  646. break;
  647.                }
  648.  
  649. /*
  650.  * Create a new StringTokenizer for each line read
  651.  * Explicitly specify the delimiters as both colons and tabs
  652.  */
  653.                StringTokenizer st = new StringTokenizer(buf, ":\t");
  654.  
  655.                String name = st.nextToken ();
  656.                if (contains (name, args[0])) {
  657.                       System.out.println (name);
  658.                       System.out.println (st.nextToken ());
  659.                       System.out.println (st.nextToken () + "\n");
  660. }
  661.         }
  662.         try {
  663.               fs.close ();
  664.         } catch (IOException e) {
  665.               System.out.println ("Exception caught closing file.");
  666. }
  667. }
  668.  
  669. /*
  670.  * contains method is a fuzzy string compare that returns true
  671.  * if either string is completely contained in the other one
  672.  *      String s1, s2  two strings to compare
  673.  */
  674. static boolean contains (String s1, String s2) {
  675.  
  676.         int i;
  677.         int l1 = s1.length ();
  678.         int l2 = s2.length ();
  679.  
  680.         if (l1 < l2) {
  681.                for (i=0; i<=l2-l1; i+=1)
  682.                       if (s1.regionMatches (true, 0, s2, i, l1))
  683.                              return true;
  684.         }
  685.         for (i=0; i<=l1-l2; i+=1)
  686.                if (s2.regionMatches (true, 0, s1, i, l2))
  687.                       return true;
  688.  
  689.         return false;
  690. }
  691. }
  692.  
  693.  
  694.  
  695.  
  696.  
  697.  
  698.  
  699. Ammortize.java:
  700.  
  701. import java.io.*;
  702.  
  703. /*
  704.  * Ammortize.class calculates monthly payment given
  705.  * loan amount, interest, and the number of years of the loan
  706.  */
  707. class Ammortize {
  708. public static void main (String args[]) {
  709.        double loanAmount=0, interest=0, years=0;
  710.  
  711.       BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
  712.  
  713.         loanAmount = inputDouble ("Enter the loan amount in dollars > ", in);
  714.  
  715.         interest = inputDouble ("Enter the interest rate in percent > ", in);
  716.  
  717.         years = inputDouble ("Enter the number of years > ", in);
  718.  
  719.         System.out.print ("The payment is $");
  720.         System.out.println (payment (loanAmount, interest, years));
  721. } // end of main ()
  722.  
  723. /*
  724.  * inputDouble method prints a prompt and reads a double
  725.  * BufferedReader 
  726. */
  727. static double inputDouble (String prompt, BufferedReader in) {
  728.         boolean error;
  729.         String input="";
  730.         double value=0;
  731.  
  732.         do {
  733.                error = false;
  734.                System.out.print (prompt);
  735.                System.out.flush ();
  736.                try {
  737.                       input = in.readLine ();
  738.                } catch (IOException e) {
  739.                       System.out.println ("An input error was caught");
  740. System.exit (1);
  741.                }
  742.                try {
  743.                      value = Double.valueOf (input).doubleValue();
  744. } catch (NumberFormatException e) {
  745.                       System.out.println ("Please try again");
  746.                       error = true;
  747.                }
  748.         } while (error);
  749.         return value;
  750. } // end of inputDouble ()
  751.  
  752. /*
  753.  * payment method does the magic calculation
  754.  *      double A      loan amount
  755.  *      double I      interest rate, as a percentage
  756.  *      double Y      number of years
  757.  */
  758. static double payment (double A, double I, double Y) {
  759.  
  760. /*
  761.  * call the exponentiation and natural log functions as
  762.  * static methods in the Math class
  763.  */
  764.         double top = A * I / 1200;
  765.         double bot = 1 - Math.exp (Y*(-12) * Math.log (1 + I/1200));
  766.  
  767.         return top / bot;
  768. } // end of payment ()
  769. }
  770.  
  771.  
  772.  
  773.  
  774.  
  775.  
  776.  
  777.  
  778.  
  779.  
  780.  
  781.  
  782.  
  783.