12.1 引言

程序清单 12-1 Quotient.java

  1. import java.util.Scanner;
  2. public class Quotient {
  3. public static void main(String[] args) {
  4. Scanner input = new Scanner(System.in);
  5. //Prompt the user to enter two integers
  6. System.out.print("Enter two integers: ");
  7. int number1 = input.nextInt();
  8. int number2 = input.nextInt();
  9. System.out.println(number1 + " / " + number2 + " is " +
  10. (number1 / number2));
  11. }
  12. }

程序清单 12-2 QuotientWithIf.java

  1. import java.util.Scanner;
  2. public class {
  3. public static void main(String[] args) {
  4. Scanner input = new Scanner(System.in);
  5. //Prompt the user to enter two integers
  6. int number1 = input.nextInt();
  7. int number2 = input.nextInt();
  8. if (number2 != 0){
  9. System.out.println(number1 + " / " + number2
  10. + " is " + (number1 / number2));
  11. }else {
  12. System.out.println("Divisor cannot be zero ");
  13. }
  14. }
  15. }

程序清单 12-3 QuotientWithMethod.java

  1. import java.util.Scanner;
  2. public class QuotientWithMethod {
  3. public static int quotient(int number1, int number2) {
  4. if (number2 == 0) {
  5. System.out.println("Divisor cannot be zero");
  6. System.exit(1);
  7. }
  8. return number1 / number2;
  9. }
  10. public static void main(String[] args) {
  11. Scanner input = new Scanner(System.in);
  12. //Prompt the user to enter two integers
  13. System.out.print("Enter two integers: ");
  14. int number1 = input.nextInt();
  15. int number2 = input.nextInt();
  16. int result = quotient(number1, number2);
  17. System.out.println(number1 + " / " + number2 + " is "
  18. + result);
  19. }
  20. }

程序清单 12-4 QuotientWithException.java

  1. import java.util.Scanner;
  2. public class QuotientWithException {
  3. public static int quotient(int number1, int number2) {
  4. if (number2 == 0) {
  5. throw new ArithmeticException("Divisor cannot be zero");
  6. }
  7. return number1 / number2;
  8. }
  9. public static void main(String[] args) {
  10. Scanner input = new Scanner(System.in);
  11. //Prompt the user to enter two integers
  12. System.out.print("Enter two integers: ");
  13. int number1 = input.nextInt();
  14. int number2 = input.nextInt();
  15. try {
  16. int result = quotient(number1, number2);
  17. System.out.println(number1 + " / " + number1 + " is " +
  18. result);
  19. } catch (ArithmeticException ex) {
  20. System.out.println("Exception: an integer " + " cannot bo divided by zero");
  21. }
  22. System.out.println("Execution continues ...");
  23. }
  24. }

程序清单 12-5 InputMismatchExceptionDemo.java

  1. import java.util.InputMismatchException;
  2. import java.util.Scanner;
  3. public class InputMismatchExceptionDemo {
  4. public static void main(String[] args) {
  5. Scanner input = new Scanner(System.in);
  6. boolean continueInput = true;
  7. do {
  8. try {
  9. System.out.print("Enetr an integer: ");
  10. int number = input.nextInt();
  11. //Display the result
  12. System.out.println("The number entered is " + number);
  13. continueInput = false;
  14. } catch (InputMismatchException ex) {
  15. System.out.println("Tru again. (" + "Incorrect input: an integer is required)");
  16. //Discard input
  17. input.nextLine();
  18. }
  19. } while (continueInput);
  20. }
  21. }

程序清单 12-6 TestException.java

  1. public class TestException {
  2. public static void main(String[] args) {
  3. try {
  4. System.out.println(sum(new int[]{1, 2, 3, 4, 5}));
  5. } catch (Exception ex) {
  6. ex.printStackTrace();
  7. System.out.println("\n" + ex.getMessage());
  8. System.out.println("\n" + ex.toString());
  9. System.out.println("\nTrace Info Obtained from getStackTrace");
  10. StackTraceElement[] traceElements = ex.getStackTrace();
  11. for (int i = 0; i < traceElements.length; i++) {
  12. System.out.print("method " + traceElements[i].getMethodName());
  13. System.out.print("(" + traceElements[i].getClassName() + ":");
  14. System.out.print(traceElements[i].getLineNumber() + ")");
  15. }
  16. }
  17. }
  18. private static int sum(int[] list) {
  19. int result = 0;
  20. for (int i = 0; i <= list.length; i++) {
  21. result += list[i];
  22. }
  23. return result;
  24. }
  25. }

程序清单 12-7 CircleWithException.java

  1. public class CircleWithException {
  2. /**
  3. * The radius of the circle
  4. */
  5. private double radius;
  6. /**
  7. * The number of the objects created
  8. */
  9. private static int numberOfObjects = 0;
  10. /**
  11. * Construct a circle with radius 1
  12. */
  13. public CircleWithException() {
  14. this(1.0);
  15. }
  16. /**
  17. * Construct a circle with a specified radius
  18. */
  19. public CircleWithException(double newRadius) {
  20. setRadius(newRadius);
  21. numberOfObjects++;
  22. }
  23. /**
  24. * Return radius
  25. */
  26. public double getRadius() {
  27. return radius;
  28. }
  29. /**
  30. * Set a new radius
  31. */
  32. public void setRadius(double newRadius) throws IllegalArgumentException {
  33. if (newRadius >= 0) {
  34. radius = newRadius;
  35. } else {
  36. throw new IllegalArgumentException("Radius cannot be negative");
  37. }
  38. }
  39. /**
  40. * Return numberOfObjects
  41. */
  42. public static int getNumberOfObjects() {
  43. return numberOfObjects;
  44. }
  45. /**
  46. * Return the area of this circle
  47. */
  48. public double findArea() {
  49. return radius * radius * 3.14159;
  50. }
  51. }

程序清单 12-8 TestCircleWithException.java

  1. public class TestCircleWithException {
  2. public static void main(String[] args) {
  3. try {
  4. CircleWithException c1 = new CircleWithException(5);
  5. CircleWithException c2 = new CircleWithException(-5);
  6. CircleWithException c3 = new CircleWithException(0);
  7. } catch (IllegalArgumentException ex) {
  8. System.out.println(ex);
  9. }
  10. System.out.println("Number of objects created: " + CircleWithException.getNumberOfObjects());
  11. }
  12. }

程序清单 12-9 ChainedExceptionDemo.java

  1. public class ChainedExceptionDemo {
  2. public static void main(String[] args) {
  3. try {
  4. method1();
  5. } catch (Exception ex) {
  6. ex.printStackTrace();
  7. }
  8. }
  9. public static void method1() throws Exception {
  10. try {
  11. method2();
  12. } catch (Exception ex) {
  13. throw new Exception("New info from method1", ex);
  14. }
  15. }
  16. public static void method2() throws Exception {
  17. throw new Exception("New info from method2");
  18. }
  19. }

程序清单 12-10 InvalidRadiusException.java

  1. public class InvalidRadiusException extends Exception {
  2. private double radius;
  3. /**
  4. * Construct an exception
  5. */
  6. public InvalidRadiusException(double radius) {
  7. super("Invalid radius " + radius);
  8. this.radius = radius;
  9. }
  10. /**
  11. * Return the radius
  12. */
  13. public double getRadius() {
  14. return radius;
  15. }
  16. }

程序清单 12-11 TestCircleWithCustomException.java

  1. public class TestCircleWithCustomException {
  2. public static void main(String[] args) {
  3. try {
  4. new CircleWithCustomException(5);
  5. new CircleWithCustomException(-5);
  6. new CircleWithCustomException(0);
  7. } catch (InvalidRadiusException ex) {
  8. System.out.println(ex);
  9. }
  10. System.out.println("Number of objects created: " +
  11. CircleWithCustomException.getNumberOfObjects());
  12. }
  13. }
  14. class CircleWithCustomException {
  15. /**
  16. * The radius of the circle
  17. */
  18. private double radius;
  19. /**
  20. * The number of objects created
  21. */
  22. private static int numberOfObjects = 0;
  23. /**
  24. * Construct a circle with radius 1
  25. */
  26. public CircleWithCustomException() throws InvalidRadiusException {
  27. this(1.0);
  28. }
  29. /**
  30. * Construct a circle with a specified radius
  31. */
  32. public CircleWithCustomException(double newRadius) throws InvalidRadiusException {
  33. setRadius(newRadius);
  34. numberOfObjects++;
  35. }
  36. /**
  37. * Return radius
  38. */
  39. public double getRadius() {
  40. return radius;
  41. }
  42. /**
  43. * Set a new radius
  44. */
  45. public void setRadius(double newRadius) throws InvalidRadiusException {
  46. if (newRadius >= 0) {
  47. radius = newRadius;
  48. } else {
  49. throw new InvalidRadiusException(newRadius);
  50. }
  51. }
  52. /**
  53. * Return numberOfObjects
  54. */
  55. public static int getNumberOfObjects() {
  56. return numberOfObjects;
  57. }
  58. /**
  59. * Return the area of this circle
  60. */
  61. public double findArea() {
  62. return radius * radius * 3.14159;
  63. }
  64. }

程序清单 12-12 TestFileClass.java

  1. public class TestFileClass {
  2. public static void main(String[] args) {
  3. java.io.File file = new java.io.File("image/us.gif");
  4. System.out.println("Does it exist? " + file.exists());
  5. System.out.println("The file has " + file.length() + " bytes");
  6. System.out.println("Can it be read? " + file.canRead());
  7. System.out.println("Can it be written? " + file.canWrite());
  8. System.out.println("Is it a directory? " + file.isDirectory());
  9. System.out.println("Is it a file? " + file.isFile());
  10. System.out.println("Is it absolute? " + file.isAbsolute());
  11. System.out.println("Is it hidden? " + file.isHidden());
  12. System.out.println("Absolute path is " + file.getAbsolutePath());
  13. System.out.println("Last modified on " + new java.util.Date(file.lastModified()));
  14. }
  15. }

程序清单 12-13 WriteData.java

  1. public class WriteData {
  2. public static void main(String[] args) throws java.io.IOException {
  3. java.io.File file = new java.io.File("scores.txt");
  4. if (file.exists()) {
  5. System.out.println("File already exists");
  6. System.exit(1);
  7. }
  8. //Create a file
  9. java.io.PrintWriter output = new java.io.PrintWriter(file);
  10. //Write formatted output to the file
  11. output.print("John T Smith ");
  12. output.print(90);
  13. output.print("Eric K Jones ");
  14. output.println(85);
  15. //Close the file
  16. output.close();
  17. }
  18. }

程序清单 12-14 WriteDataWithAutoClose.java

  1. public class WriteDataWithAutoClose {
  2. public static void main(String[] args) throws Exception {
  3. java.io.File file = new java.io.File("scores.txt");
  4. if (file.exists()) {
  5. System.out.println("File already exists");
  6. System.exit(0);
  7. }
  8. try (
  9. //Create a file
  10. java.io.PrintWriter output = new java.io.PrintWriter(file);
  11. ) {
  12. //Write formatted output to the file
  13. output.print("John T Smith ");
  14. output.println(90);
  15. output.print("Eric K Jones ");
  16. output.print(85);
  17. }
  18. }
  19. }

程序清单 12-15 ReadData.java

  1. import java.util.Scanner;
  2. public class ReadData {
  3. public static void main(String[] args) throws Exception {
  4. //Create a File instance
  5. java.io.File file = new java.io.File("scores.txt");
  6. //Create a Scanner for the file
  7. Scanner input = new Scanner(System.in);
  8. //Read data from a file
  9. while (input.hasNext()) {
  10. String firstName = input.next();
  11. String mi = input.next();
  12. String lastName = input.next();
  13. int score = input.nextInt();
  14. System.out.println(firstName + " " + mi + " " + lastName + " " + score);
  15. }
  16. //Close the file
  17. input.close();
  18. }
  19. }

程序清单 12-16 ReplaceText.java

  1. import java.io.File;
  2. import java.io.PrintWriter;
  3. import java.util.Scanner;
  4. public class ReplaceText {
  5. public static void main(String[] args) throws Exception {
  6. //Check command line parameter usage
  7. if (args.length != 4) {
  8. System.out.println("Usage: java ReplaceText sourceFile targetFile oldStr newStr");
  9. System.exit(1);
  10. }
  11. //Check if source file exists
  12. File sourceFile = new File(args[0]);
  13. if (!sourceFile.exists()) {
  14. System.out.println("Source file " + args[0] + " does not exist");
  15. System.exit(2);
  16. }
  17. //Check if target file exists
  18. File targetFile = new File(args[1]);
  19. if (targetFile.exists()) {
  20. System.out.println("Target file " + args[1] + " already exists");
  21. System.exit(3);
  22. }
  23. try (
  24. //Create input and ouput files
  25. Scanner input = new Scanner(System.in);
  26. PrintWriter output = new PrintWriter(targetFile);
  27. ) {
  28. while (input.hasNext()) {
  29. String s1 = input.nextLine();
  30. String s2 = s1.replaceAll(args[2], args[3]);
  31. output.println(s2);
  32. }
  33. }
  34. }
  35. }

程序清单 12-17 ReadFileFromURL.java

  1. import java.util.Scanner;
  2. public class ReadFileFromURL {
  3. public static void main(String[] args) {
  4. System.out.print("Enter a URL: ");
  5. String URLString = new Scanner(System.in).next();
  6. try {
  7. java.net.URL url = new java.net.URL(URLString);
  8. int count = 0;
  9. Scanner input = new Scanner(url.openStream());
  10. while (input.hasNext()) {
  11. String line = input.nextLine();
  12. count += line.length();
  13. }
  14. System.out.println("The file size is " + count + " characters");
  15. } catch (java.net.MalformedURLException ex) {
  16. System.out.println("Invalid URL");
  17. } catch (java.io.IOException ex) {
  18. System.out.println("I/O Errors: no such file");
  19. }
  20. }
  21. }

程序清单 12-18 WebCrawler.java

  1. import java.util.ArrayList;
  2. import java.util.Scanner;
  3. public class WebCrawler {
  4. public static void main(String[] args) {
  5. Scanner input = new Scanner(System.in);
  6. System.out.print("Enter a URL: ");
  7. String url = input.nextLine();
  8. //Traverse the Web from a starting url
  9. crawler(url);
  10. }
  11. public static void crawler(String startingURL) {
  12. ArrayList<String> listOfPendingURLs = new ArrayList<>();
  13. ArrayList<String> listOfTraversedURLs = new ArrayList<>();
  14. listOfPendingURLs.add(startingURL);
  15. while (!listOfPendingURLs.isEmpty() && listOfTraversedURLs.size() <= 100) {
  16. String urlString = listOfPendingURLs.remove(0);
  17. if (!listOfTraversedURLs.contains(urlString)) {
  18. listOfTraversedURLs.add(urlString);
  19. System.out.println("Crawl " + urlString);
  20. for (String s : getSubURLs(urlString)) {
  21. if (!listOfTraversedURLs.contains(s)) {
  22. listOfPendingURLs.add(s);
  23. }
  24. }
  25. }
  26. }
  27. }
  28. public static ArrayList<String> getSubURLs(String urlString) {
  29. ArrayList<String> list = new ArrayList<>();
  30. try {
  31. java.net.URL url = new java.net.URL(urlString);
  32. Scanner input = new Scanner(System.in);
  33. int current = 0;
  34. while (input.hasNext()) {
  35. String line = input.nextLine();
  36. current = line.indexOf("https:", current);
  37. while (current > 0) {
  38. int endIndex = line.indexOf("\"", current);
  39. if (endIndex > 0) {
  40. //Ensure that a correct URL is found
  41. list.add(line.substring(current, endIndex));
  42. current = line.indexOf("https:", endIndex);
  43. } else {
  44. current = -1;
  45. }
  46. }
  47. }
  48. } catch (Exception ex) {
  49. System.out.println("Error: " + ex.getMessage());
  50. }
  51. return list;
  52. }
  53. }