楼主: Lisrelchen
3243 15

[读者文库]Java Examples in a Nutshell, 3rd Edition [推广有奖]

  • 0关注
  • 62粉丝

VIP

已卖:4194份资源

院士

67%

还不是VIP/贵宾

-

TA的文库  其他...

Bayesian NewOccidental

Spatial Data Analysis

东西方数据挖掘

威望
0
论坛币
50288 个
通用积分
83.6306
学术水平
253 点
热心指数
300 点
信用等级
208 点
经验
41518 点
帖子
3256
精华
14
在线时间
766 小时
注册时间
2006-5-4
最后登录
2022-11-6

楼主
Lisrelchen 发表于 2015-6-5 10:35:11 |AI写论文

+2 论坛币
k人 参与回答

经管之家送您一份

应届毕业生专属福利!

求职就业群
赵安豆老师微信:zhaoandou666

经管之家联合CDA

送您一个全额奖学金名额~ !

感谢您参与论坛问题回答

经管之家送您两个论坛币!

+2 论坛币

  • Java Examples in a Nutshell, 3rd Edition
  • By: David Flanagan

  • Publisher: O'Reilly Media, Inc.

  • Pub. Date: January 21, 2004

  • Print ISBN-13: 978-0-596-00620-4

  • Pages in Print Edition: 722

  • Subscriber Rating: [0 Ratings]



二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

关键词:Examples nutshell example Edition editio Media Java 读者

本帖被以下文库推荐

沙发
Lisrelchen 发表于 2015-6-5 10:35:48

Computing Factorials

  1. Example 1-7. Factorial.java
  2. package je3.basics;
  3. /**
  4. * This class doesn't define a main( ) method, so it isn't a program by itself.
  5. * It does define a useful method that we can use in other programs, though.
  6. **/
  7. public class Factorial {
  8.     /** Compute and return x!, the factorial of x */
  9.     public static int factorial(int x) {
  10.         if (x < 0) throw new IllegalArgumentException("x must be >= 0");
  11.         int fact = 1;
  12.         for(int i = 2; i <= x; i++)    // loop
  13.             fact *= i;                 // shorthand for: fact = fact * i;
  14.         return fact;
  15.     }
  16. }
复制代码

藤椅
Lisrelchen 发表于 2015-6-5 10:37:58
Recursive Factorials

Example 1-8 shows another way to compute factorials. This example uses a programming technique called recursion. Recursion happens when a method calls itself, or in other words, invokes itself recursively. The recursive algorithm for computing factorials relies on the fact that n! is equal to n*(n-1)!. Computing factorials in this fashion is a classic example of recursion. It is not a particularly efficient technique in this case, but there are many important uses for recursion, and this example demonstrates that it is perfectly legal in Java. This example also switches from the int data type, which is a 32-bit integer, to the long data type, which is a 64-bit integer. Factorials become very large, very quickly, so the extra capacity of a long makes the factorial( ) method more useful.
  1. Example 1-8. Factorial2.java
  2. package je3.basics;
  3. /**
  4. * This class shows a recursive method to compute factorials.  This method
  5. * calls itself repeatedly based on the formula: n! = n * (n-1)!
  6. **/
  7. public class Factorial2 {
  8.     public static long factorial(long x) {
  9.         if (x < 0) throw new IllegalArgumentException("x must be >= 0");
  10.         if (x <= 1) return 1;              // Stop recursing here
  11.         else return x * factorial(x-1);    // Recurse by calling ourselves
  12.     }
  13. }
复制代码


板凳
Lisrelchen 发表于 2015-6-5 10:40:16
Caching Factorials

Example 1-9 shows a refinement to our previous factorial examples. Factorials are ideal candidates for caching because they are slightly time consuming to compute, and more importantly, there are few factorials you actually can compute, due to the limitations of the long data type. So, in this example, once a factorial is computed, its value is stored for future use.

Besides introducing the technique of caching, this example demonstrates several new things. First, it declares static fields within the Factorial3 class:

static long[  ] table = new long[21];
static int last = 0;
A static field is kind of like a variable, but it retains its value between invocations of the factorial( ) method. This means that static fields can cache values computed in one invocation for use by the next invocation.

Second, this example shows how to create an array:

static long[  ] table = new long[21];
The first half of this line (before the = sign) declares the static field table to be an array of long values. The second half of the line actually creates an array of 21 long values using the new operator.

Finally, this example demonstrates how to throw an exception:

throw new IllegalArgumentException("Overflow; x is too large.");
An exception is a kind of Java object; it is created with the new keyword, just as the array was. When a program throws an exception object with the throw statement, it indicates that some sort of unexpected circumstance or error has arisen. When an exception is thrown, program control transfers to the nearest containing catch clause of a try/catch statement. This clause should contain code to handle the exceptional condition. If an exception is never caught, the program terminates with an error.

Example 1-9 throws an exception to notify the calling procedure that the argument it passed is too big or too small. The argument is too big if it is greater than 20, since we can’t compute factorials beyond 20!. The argument is too small if it is less than 0, as factorial is only defined for nonnegative integers. Examples later in the chapter demonstrate how to catch and handle exceptions.
  1. Example 1-9. Factorial3.java
  2. package je3.basics;

  3. /**
  4. * This class computes factorials and caches the results in a table for reuse.
  5. * 20! is as high as we can go using the long data type, so check the argument
  6. * passed and "throw an exception" if it is too big or too small.
  7. **/
  8. public class Factorial3 {
  9.     // Create an array to cache values 0! through 20!.
  10.     static long[  ] table = new long[21];
  11.     // A "static initializer": initialize the first value in the array
  12.     static { table[0] = 1; }  // factorial of 0 is 1.
  13.     // Remember the highest initialized value in the array
  14.     static int last = 0;

  15.     public static long factorial(int x) throws IllegalArgumentException {
  16.         // Check if x is too big or too small.  Throw an exception if so.
  17.         if (x >= table.length)   // ".length" returns length of any array
  18.             throw new IllegalArgumentException("Overflow; x is too large.");
  19.         if (x<0) throw new IllegalArgumentException("x must be non-negative.");

  20.         // Compute and cache any values that are not yet cached.
  21.         while(last < x) {
  22.             table[last + 1] = table[last] * (last + 1);
  23.             last++;
  24.         }
  25.         // Now return the cached factorial of x.
  26.         return table[x];
  27.     }
  28. }
复制代码


报纸
Lisrelchen 发表于 2015-6-5 10:41:59
Computing Big Factorials

In the previous section, we learned that 20! is the largest factorial that can fit in a 64-bit integer. But what if you want to compute 50! or100!? The java.math.BigInteger class represents arbitrarily large integer values and provides methods to perform arithmetic operations on these very large numbers. Example 1-10 uses the BigInteger class to compute factorials of any size. It also includes a simple main( )method that defines a standalone test program for our factorial( ) method. This test program says, for example, that 50! is the following 65-digit number:

30414093201713378043612608166064768844377641568960512000000000000

Example 1-10 introduces the import statement. This statement must appear at the top of a Java file, before any class is defined (but after thepackage declaration). It provides a way to tell the compiler what classes you are using in a program. Once a class like java.math.BigIntegerhas been imported, you no longer have to type its full name; instead you can refer to it simply as BigInteger. You can also import an entire package of classes, as with the line:

import java.util.*

Note that the classes in the java.lang package are automatically imported, as are the classes of the current package, which, in this case, isje3.basics.

Example 1-10 uses the same caching technique Example 1-9 did. However, because there is no upper bound on the number of factorials that can be computed with this class, you can’t use a fixed-sized array for the cache. Instead, use the java.util.ArrayList class, which is a utility class that implements an array-like data structure that can grow to be as large as you need it to be. Because an ArrayList is an object rather than an array, you use such methods as size( ), add( ), and get( ) to work with it. By the same token, a BigInteger is an object rather than a primitive value, so you can’t simply use the * operator to multiply BigInteger objects. Use the multiply( ) method instead.

  1. Example 1-10. Factorial4.java
  2. package je3.basics;

  3. // Import some other classes we'll use in this example.
  4. // Once we import a class, we don't have to type its full name.
  5. import java.math.BigInteger;  // Import BigInteger from java.math package
  6. import java.util.*;  // Import all classes (including ArrayList) from java.util

  7. /**
  8. * This version of the program uses arbitrary precision integers, so it does
  9. * not have an upper-bound on the values it can compute.  It uses an ArrayList
  10. * object to cache computed values instead of a fixed-size array.  An ArrayList
  11. * is like an array, but can grow to any size.  The factorial( ) method is
  12. * declared "synchronized" so that it can be safely used in multi-threaded
  13. * programs.  Look up java.math.BigInteger and java.util.ArrayList while
  14. * studying this class.  Prior to Java 1.2, use Vector instead of ArrayList
  15. **/
  16. public class Factorial4 {
  17.     protected static ArrayList table = new ArrayList( ); // create cache
  18.     static { // Initialize the first element of the cache with !0 = 1.
  19.         table.add(BigInteger.valueOf(1));
  20.     }

  21.     /** The factorial( ) method, using BigIntegers cached in a ArrayList */
  22.     public static synchronized BigInteger factorial(int x) {
  23.         if (x<0) throw new IllegalArgumentException("x must be non-negative.");
  24.         for(int size = table.size( ); size <= x; size++) {
  25.             BigInteger lastfact = (BigInteger)table.get(size-1);
  26.             BigInteger nextfact = lastfact.multiply(BigInteger.valueOf(size));
  27.             table.add(nextfact);
  28.         }
  29.         return (BigInteger) table.get(x);
  30.     }

  31.     /**
  32.      * A simple main( ) method that we can use as a standalone test program
  33.      * for our factorial( ) method.  
  34.      **/
  35.     public static void main(String[  ] args) {
  36.         for(int i = 0; i <= 50; i++)
  37.             System.out.println(i + "! = " + factorial(i));
  38.     }
  39. }
复制代码


地板
Lisrelchen 发表于 2015-6-5 10:46:08
Sorting Numbers

Example 1-14 implements a simple (but inefficient) algorithm for sorting an array of numbers. This example doesn’t introduce any new elements of Java syntax, but it is interesting because it reaches a real-world level of complexity. The sorting algorithm manipulates array entries using an if statement within a for loop that is itself within another for loop. You should take the time to study this short program carefully. Make sure that you understand exactly how it goes about sorting its array of numbers.

  1. Example 1-14. SortNumbers.java
  2. package je3.basics;

  3. /**
  4. * This class demonstrates how to sort numbers using a simple algorithm
  5. **/
  6. public class SortNumbers {
  7.     /**
  8.      * This is a very simple sorting algorithm that is not very efficient
  9.      * when sorting large numbers of things
  10.      **/
  11.     public static void sort(double[  ] nums) {
  12.         // Loop through each element of the array, sorting as we go.
  13.         // Each time through, find the smallest remaining element, and move it
  14.         // to the first unsorted position in the array.
  15.         for(int i = 0; i < nums.length; i++) {
  16.             int min = i;  // holds the index of the smallest element
  17.             // find the smallest one between i and the end of the array
  18.             for(int j = i; j < nums.length; j++) {
  19.                 if (nums[j] < nums[min]) min = j;
  20.             }
  21.             // Now swap the smallest one with element i.  
  22.             // This leaves all elements between 0 and i sorted.
  23.             double tmp;
  24.             tmp = nums[i];
  25.             nums[i] = nums[min];
  26.             nums[min] = tmp;
  27.         }
  28.     }

  29.     /** This is a simple test program for the algorithm above */
  30.     public static void main(String[  ] args) {
  31.         double[  ] nums = new double[10];      // Create an array to hold numbers
  32.         for(int i = 0; i < nums.length; i++) // Generate random numbers
  33.             nums[i] = Math.random( ) * 100;
  34.         sort(nums);                          // Sort them
  35.         for(int i = 0; i < nums.length; i++) // Print them out
  36.             System.out.println(nums[i]);
  37.     }
  38. }
复制代码


7
Lisrelchen 发表于 2015-6-5 10:48:36
Computing Primes

Example 1-15 computes the largest prime number less than a specified value, using the Sieve of Eratosthenes algorithm. The algorithm finds primes by eliminating multiples of all lower prime numbers. Like Example 1-14, this example introduces no new Java syntax, but is a nice, nontrivial program with which to end this chapter. The program may seem deceptively simple, but there’s actually a fair bit going on, so be sure you understand how it is ruling out prime numbers.

  1. Example 1-15. Sieve.java
  2. package je3.basics;

  3. /**
  4. * This program computes prime numbers using the Sieve of Eratosthenes
  5. * algorithm: rule out multiples of all lower prime numbers, and anything
  6. * remaining is a prime.  It prints out the largest prime number less than
  7. * or equal to the supplied command-line argument.
  8. **/
  9. public class Sieve {
  10.     public static void main(String[  ] args) {
  11.         // We will compute all primes less than the value specified on the
  12.         // command line, or, if no argument, all primes less than 100.
  13.         int max = 100;                           // Assign a default value
  14.         try { max = Integer.parseInt(args[0]); } // Parse user-supplied arg
  15.         catch (Exception e) {  }                   // Silently ignore exceptions.

  16.         // Create an array that specifies whether each number is prime or not.
  17.         boolean[  ] isprime = new boolean[max+1];

  18.         // Assume that all numbers are primes, until proven otherwise.
  19.         for(int i = 0; i <= max; i++) isprime[i] = true;

  20.         // However, we know that 0 and 1 are not primes.  Make a note of it.
  21.         isprime[0] = isprime[1] = false;

  22.         // To compute all primes less than max, we need to rule out
  23.         // multiples of all integers less than the square root of max.
  24.         int n = (int) Math.ceil(Math.sqrt(max));  // See java.lang.Math class

  25.         // Now, for each integer i from 0 to n:
  26.         //   If i is a prime, then none of its multiples are primes,
  27.         //   so indicate this in the array.  If i is not a prime, then
  28.         //   its multiples have already been ruled out by one of the
  29.         //   prime factors of i, so we can skip this case.
  30.         for(int i = 0; i <= n; i++) {
  31.             if (isprime[i])                          // If i is a prime,
  32.                 for(int j = 2*i; j <= max; j = j + i) // loop through multiples
  33.                     isprime[j] = false;               // they are not prime.
  34.         }

  35.         // Now go look for the largest prime:
  36.         int largest;
  37.         for(largest = max; !isprime[largest]; largest--) ;  // empty loop body
  38.         
  39.         // Output the result
  40.         System.out.println("The largest prime less than or equal to " + max +
  41.                            " is " + largest);
  42.     }
  43. }
复制代码


8
Lisrelchen 发表于 2015-6-5 10:50:23
Working with Files

Example 3-1 is a relatively short program that deletes a file or directory specified on the command line. Before it does the actual deletion, it performs several checks to ensure that the specified file exists, that it is writable, and, if it is a directory, that it is empty. If any of the tests fail, the program throws an exception explaining why the file cannot be deleted. These tests demonstrate some of the important features of the File class, and are necessary because the File.delete( ) method does not have useful failure diagnostics: instead of throwing an informative IOException on failure, it simply returns false. Thus, if we want to know why a file could not be deleted, we must test its deleteability before calling File.delete( ). Other useful File methods (worth looking up) include getParent( ), length( ), mkdir( ), andrenameTo( ).

  1. Example 3-1. Delete.java
  2. package je3.io;
  3. import java.io.*;

  4. /**
  5. * This class is a static method delete( ) and a standalone program that
  6. * deletes a specified file or directory.
  7. **/
  8. public class Delete {
  9.     /**
  10.      * This is the main( ) method of the standalone program.  After checking
  11.      * it arguments, it invokes the Delete.delete( ) method to do the deletion
  12.      **/
  13.     public static void main(String[  ] args) {
  14.         if (args.length != 1) {    // Check command-line arguments
  15.             System.err.println("Usage: java Delete <file or directory>");
  16.             System.exit(0);
  17.         }
  18.         // Call delete( ) and display any error messages it throws.
  19.         try { delete(args[0]); }
  20.         catch (IllegalArgumentException e) {
  21.             System.err.println(e.getMessage( ));
  22.         }
  23.     }     
  24.    
  25.     /**
  26.      * The static method that does the deletion.  Invoked by main( ), and
  27.      * designed for use by other programs as well.  It first makes sure that
  28.      * the specified file or directory is deleteable before attempting to
  29.      * delete it.  If there is a problem, it throws an
  30.      * IllegalArgumentException.
  31.      **/
  32.     public static void delete(String filename) {
  33.         // Create a File object to represent the filename
  34.         File f = new File(filename);

  35.         // Make sure the file or directory exists and isn't write protected
  36.         if (!f.exists( )) fail("Delete: no such file or directory: " +filename);
  37.         if (!f.canWrite( )) fail("Delete: write protected: " + filename);

  38.         // If it is a directory, make sure it is empty
  39.         if (f.isDirectory( )) {
  40.             String[  ] files = f.list( );
  41.             if (files.length > 0)
  42.                 fail("Delete: directory not empty: " + filename);
  43.         }

  44.         // If we passed all the tests, then attempt to delete it
  45.         boolean success = f.delete( );
  46.         
  47.         // And throw an exception if it didn't work for some (unknown) reason.
  48.         // For example, because of a bug with Java 1.1.1 on Linux,
  49.         // directory deletion always fails
  50.         if (!success) fail("Delete: deletion failed");
  51.     }

  52.     /** A convenience method to throw an exception */
  53.     protected static void fail(String msg) throws IllegalArgumentException {
  54.         throw new IllegalArgumentException(msg);
  55.     }
  56. }
复制代码


9
auirzxp 学生认证  发表于 2015-6-5 10:58:19
提示: 作者被禁止或删除 内容自动屏蔽

10
Lisrelchen 发表于 2015-9-27 00:27:16
  1. Example 2-1. Rect.java
  2. package je3.classes;
  3. /**
  4. * This class represents a rectangle.  Its fields represent the coordinates
  5. * of the corners of the rectangle.  Its methods define operations that can
  6. * be performed on Rect objects.
  7. **/
  8. public class Rect {
  9.     // These are the data fields of the class
  10.     public int x1, y1, x2, y2;

  11.     /**
  12.      * The is the main constructor for the class.  It simply uses its arguments
  13.      * to initialize each of the fields of the new object.  Note that it has
  14.      * the same name as the class, and that it has no return value declared in
  15.      * its signature.
  16.      **/
  17.     public Rect(int x1, int y1, int x2, int y2) {
  18.         this.x1 = x1;
  19.         this.y1 = y1;
  20.         this.x2 = x2;
  21.         this.y2 = y2;
  22.     }

  23.     /**
  24.      * This is another constructor.  It defines itself in terms of the above
  25.      **/
  26.     public Rect(int width, int height) { this(0, 0, width, height); }
  27.    
  28.     /** This is yet another constructor. */
  29.     public Rect( ) { this(0, 0, 0, 0); }

  30.     /** Move the rectangle by the specified amounts */
  31.     public void move(int deltax, int deltay) {
  32.         x1 += deltax; x2 += deltax;
  33.         y1 += deltay; y2 += deltay;
  34.     }

  35.     /** Test whether the specified point is inside the rectangle */
  36.     public boolean isInside(int x, int y) {
  37.         return ((x >= x1)&& (x <= x2)&& (y >= y1)&& (y <= y2));
  38.     }

  39.     /**
  40.      * Return the union of this rectangle with another.  I.e. return the
  41.      * smallest rectangle that includes them both.
  42.      **/
  43.     public Rect union(Rect r) {
  44.         return new Rect((this.x1 < r.x1) ? this.x1 : r.x1,
  45.                         (this.y1 < r.y1) ? this.y1 : r.y1,
  46.                         (this.x2 > r.x2) ? this.x2 : r.x2,
  47.                         (this.y2 > r.y2) ? this.y2 : r.y2);
  48.     }
  49.    
  50.     /**
  51.      * Return the intersection of this rectangle with another.
  52.      * I.e. return their overlap.
  53.      **/
  54.     public Rect intersection(Rect r) {
  55.         Rect result =  new Rect((this.x1 > r.x1) ? this.x1 : r.x1,
  56.                                 (this.y1 > r.y1) ? this.y1 : r.y1,
  57.                                 (this.x2 < r.x2) ? this.x2 : r.x2,
  58.                                 (this.y2 < r.y2) ? this.y2 : r.y2);
  59.         if (result.x1 > result.x2) { result.x1 = result.x2 = 0; }
  60.         if (result.y1 > result.y2) { result.y1 = result.y2 = 0; }
  61.         return result;
  62.     }

  63.     /**
  64.      * This is a method of our superclass, Object.  We override it so that
  65.      * Rect objects can be meaningfully converted to strings, can be
  66.      * concatenated to strings with the + operator, and can be passed to
  67.      * methods like System.out.println( )
  68.      **/
  69.     public String toString( ) {
  70.         return "[" + x1 + "," + y1 + "; " + x2 + "," + y2 + "]";
  71.     }
  72. }
复制代码

您需要登录后才可以回帖 登录 | 我要注册

本版微信群
jg-xs1
拉您进交流群
GMT+8, 2025-12-30 13:29