12.1 引言
程序清单 12-1 Quotient.java
import java.util.Scanner;
public class Quotient {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Prompt the user to enter two integers
System.out.print("Enter two integers: ");
int number1 = input.nextInt();
int number2 = input.nextInt();
System.out.println(number1 + " / " + number2 + " is " +
(number1 / number2));
}
}
程序清单 12-2 QuotientWithIf.java
import java.util.Scanner;
public class {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Prompt the user to enter two integers
int number1 = input.nextInt();
int number2 = input.nextInt();
if (number2 != 0){
System.out.println(number1 + " / " + number2
+ " is " + (number1 / number2));
}else {
System.out.println("Divisor cannot be zero ");
}
}
}
程序清单 12-3 QuotientWithMethod.java
import java.util.Scanner;
public class QuotientWithMethod {
public static int quotient(int number1, int number2) {
if (number2 == 0) {
System.out.println("Divisor cannot be zero");
System.exit(1);
}
return number1 / number2;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Prompt the user to enter two integers
System.out.print("Enter two integers: ");
int number1 = input.nextInt();
int number2 = input.nextInt();
int result = quotient(number1, number2);
System.out.println(number1 + " / " + number2 + " is "
+ result);
}
}
程序清单 12-4 QuotientWithException.java
import java.util.Scanner;
public class QuotientWithException {
public static int quotient(int number1, int number2) {
if (number2 == 0) {
throw new ArithmeticException("Divisor cannot be zero");
}
return number1 / number2;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Prompt the user to enter two integers
System.out.print("Enter two integers: ");
int number1 = input.nextInt();
int number2 = input.nextInt();
try {
int result = quotient(number1, number2);
System.out.println(number1 + " / " + number1 + " is " +
result);
} catch (ArithmeticException ex) {
System.out.println("Exception: an integer " + " cannot bo divided by zero");
}
System.out.println("Execution continues ...");
}
}
程序清单 12-5 InputMismatchExceptionDemo.java
import java.util.InputMismatchException;
import java.util.Scanner;
public class InputMismatchExceptionDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean continueInput = true;
do {
try {
System.out.print("Enetr an integer: ");
int number = input.nextInt();
//Display the result
System.out.println("The number entered is " + number);
continueInput = false;
} catch (InputMismatchException ex) {
System.out.println("Tru again. (" + "Incorrect input: an integer is required)");
//Discard input
input.nextLine();
}
} while (continueInput);
}
}
程序清单 12-6 TestException.java
public class TestException {
public static void main(String[] args) {
try {
System.out.println(sum(new int[]{1, 2, 3, 4, 5}));
} catch (Exception ex) {
ex.printStackTrace();
System.out.println("\n" + ex.getMessage());
System.out.println("\n" + ex.toString());
System.out.println("\nTrace Info Obtained from getStackTrace");
StackTraceElement[] traceElements = ex.getStackTrace();
for (int i = 0; i < traceElements.length; i++) {
System.out.print("method " + traceElements[i].getMethodName());
System.out.print("(" + traceElements[i].getClassName() + ":");
System.out.print(traceElements[i].getLineNumber() + ")");
}
}
}
private static int sum(int[] list) {
int result = 0;
for (int i = 0; i <= list.length; i++) {
result += list[i];
}
return result;
}
}
程序清单 12-7 CircleWithException.java
public class CircleWithException {
/**
* The radius of the circle
*/
private double radius;
/**
* The number of the objects created
*/
private static int numberOfObjects = 0;
/**
* Construct a circle with radius 1
*/
public CircleWithException() {
this(1.0);
}
/**
* Construct a circle with a specified radius
*/
public CircleWithException(double newRadius) {
setRadius(newRadius);
numberOfObjects++;
}
/**
* Return radius
*/
public double getRadius() {
return radius;
}
/**
* Set a new radius
*/
public void setRadius(double newRadius) throws IllegalArgumentException {
if (newRadius >= 0) {
radius = newRadius;
} else {
throw new IllegalArgumentException("Radius cannot be negative");
}
}
/**
* Return numberOfObjects
*/
public static int getNumberOfObjects() {
return numberOfObjects;
}
/**
* Return the area of this circle
*/
public double findArea() {
return radius * radius * 3.14159;
}
}
程序清单 12-8 TestCircleWithException.java
public class TestCircleWithException {
public static void main(String[] args) {
try {
CircleWithException c1 = new CircleWithException(5);
CircleWithException c2 = new CircleWithException(-5);
CircleWithException c3 = new CircleWithException(0);
} catch (IllegalArgumentException ex) {
System.out.println(ex);
}
System.out.println("Number of objects created: " + CircleWithException.getNumberOfObjects());
}
}
程序清单 12-9 ChainedExceptionDemo.java
public class ChainedExceptionDemo {
public static void main(String[] args) {
try {
method1();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void method1() throws Exception {
try {
method2();
} catch (Exception ex) {
throw new Exception("New info from method1", ex);
}
}
public static void method2() throws Exception {
throw new Exception("New info from method2");
}
}
程序清单 12-10 InvalidRadiusException.java
public class InvalidRadiusException extends Exception {
private double radius;
/**
* Construct an exception
*/
public InvalidRadiusException(double radius) {
super("Invalid radius " + radius);
this.radius = radius;
}
/**
* Return the radius
*/
public double getRadius() {
return radius;
}
}
程序清单 12-11 TestCircleWithCustomException.java
public class TestCircleWithCustomException {
public static void main(String[] args) {
try {
new CircleWithCustomException(5);
new CircleWithCustomException(-5);
new CircleWithCustomException(0);
} catch (InvalidRadiusException ex) {
System.out.println(ex);
}
System.out.println("Number of objects created: " +
CircleWithCustomException.getNumberOfObjects());
}
}
class CircleWithCustomException {
/**
* The radius of the circle
*/
private double radius;
/**
* The number of objects created
*/
private static int numberOfObjects = 0;
/**
* Construct a circle with radius 1
*/
public CircleWithCustomException() throws InvalidRadiusException {
this(1.0);
}
/**
* Construct a circle with a specified radius
*/
public CircleWithCustomException(double newRadius) throws InvalidRadiusException {
setRadius(newRadius);
numberOfObjects++;
}
/**
* Return radius
*/
public double getRadius() {
return radius;
}
/**
* Set a new radius
*/
public void setRadius(double newRadius) throws InvalidRadiusException {
if (newRadius >= 0) {
radius = newRadius;
} else {
throw new InvalidRadiusException(newRadius);
}
}
/**
* Return numberOfObjects
*/
public static int getNumberOfObjects() {
return numberOfObjects;
}
/**
* Return the area of this circle
*/
public double findArea() {
return radius * radius * 3.14159;
}
}
程序清单 12-12 TestFileClass.java
public class TestFileClass {
public static void main(String[] args) {
java.io.File file = new java.io.File("image/us.gif");
System.out.println("Does it exist? " + file.exists());
System.out.println("The file has " + file.length() + " bytes");
System.out.println("Can it be read? " + file.canRead());
System.out.println("Can it be written? " + file.canWrite());
System.out.println("Is it a directory? " + file.isDirectory());
System.out.println("Is it a file? " + file.isFile());
System.out.println("Is it absolute? " + file.isAbsolute());
System.out.println("Is it hidden? " + file.isHidden());
System.out.println("Absolute path is " + file.getAbsolutePath());
System.out.println("Last modified on " + new java.util.Date(file.lastModified()));
}
}
程序清单 12-13 WriteData.java
public class WriteData {
public static void main(String[] args) throws java.io.IOException {
java.io.File file = new java.io.File("scores.txt");
if (file.exists()) {
System.out.println("File already exists");
System.exit(1);
}
//Create a file
java.io.PrintWriter output = new java.io.PrintWriter(file);
//Write formatted output to the file
output.print("John T Smith ");
output.print(90);
output.print("Eric K Jones ");
output.println(85);
//Close the file
output.close();
}
}
程序清单 12-14 WriteDataWithAutoClose.java
public class WriteDataWithAutoClose {
public static void main(String[] args) throws Exception {
java.io.File file = new java.io.File("scores.txt");
if (file.exists()) {
System.out.println("File already exists");
System.exit(0);
}
try (
//Create a file
java.io.PrintWriter output = new java.io.PrintWriter(file);
) {
//Write formatted output to the file
output.print("John T Smith ");
output.println(90);
output.print("Eric K Jones ");
output.print(85);
}
}
}
程序清单 12-15 ReadData.java
import java.util.Scanner;
public class ReadData {
public static void main(String[] args) throws Exception {
//Create a File instance
java.io.File file = new java.io.File("scores.txt");
//Create a Scanner for the file
Scanner input = new Scanner(System.in);
//Read data from a file
while (input.hasNext()) {
String firstName = input.next();
String mi = input.next();
String lastName = input.next();
int score = input.nextInt();
System.out.println(firstName + " " + mi + " " + lastName + " " + score);
}
//Close the file
input.close();
}
}
程序清单 12-16 ReplaceText.java
import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;
public class ReplaceText {
public static void main(String[] args) throws Exception {
//Check command line parameter usage
if (args.length != 4) {
System.out.println("Usage: java ReplaceText sourceFile targetFile oldStr newStr");
System.exit(1);
}
//Check if source file exists
File sourceFile = new File(args[0]);
if (!sourceFile.exists()) {
System.out.println("Source file " + args[0] + " does not exist");
System.exit(2);
}
//Check if target file exists
File targetFile = new File(args[1]);
if (targetFile.exists()) {
System.out.println("Target file " + args[1] + " already exists");
System.exit(3);
}
try (
//Create input and ouput files
Scanner input = new Scanner(System.in);
PrintWriter output = new PrintWriter(targetFile);
) {
while (input.hasNext()) {
String s1 = input.nextLine();
String s2 = s1.replaceAll(args[2], args[3]);
output.println(s2);
}
}
}
}
程序清单 12-17 ReadFileFromURL.java
import java.util.Scanner;
public class ReadFileFromURL {
public static void main(String[] args) {
System.out.print("Enter a URL: ");
String URLString = new Scanner(System.in).next();
try {
java.net.URL url = new java.net.URL(URLString);
int count = 0;
Scanner input = new Scanner(url.openStream());
while (input.hasNext()) {
String line = input.nextLine();
count += line.length();
}
System.out.println("The file size is " + count + " characters");
} catch (java.net.MalformedURLException ex) {
System.out.println("Invalid URL");
} catch (java.io.IOException ex) {
System.out.println("I/O Errors: no such file");
}
}
}
程序清单 12-18 WebCrawler.java
import java.util.ArrayList;
import java.util.Scanner;
public class WebCrawler {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a URL: ");
String url = input.nextLine();
//Traverse the Web from a starting url
crawler(url);
}
public static void crawler(String startingURL) {
ArrayList<String> listOfPendingURLs = new ArrayList<>();
ArrayList<String> listOfTraversedURLs = new ArrayList<>();
listOfPendingURLs.add(startingURL);
while (!listOfPendingURLs.isEmpty() && listOfTraversedURLs.size() <= 100) {
String urlString = listOfPendingURLs.remove(0);
if (!listOfTraversedURLs.contains(urlString)) {
listOfTraversedURLs.add(urlString);
System.out.println("Crawl " + urlString);
for (String s : getSubURLs(urlString)) {
if (!listOfTraversedURLs.contains(s)) {
listOfPendingURLs.add(s);
}
}
}
}
}
public static ArrayList<String> getSubURLs(String urlString) {
ArrayList<String> list = new ArrayList<>();
try {
java.net.URL url = new java.net.URL(urlString);
Scanner input = new Scanner(System.in);
int current = 0;
while (input.hasNext()) {
String line = input.nextLine();
current = line.indexOf("https:", current);
while (current > 0) {
int endIndex = line.indexOf("\"", current);
if (endIndex > 0) {
//Ensure that a correct URL is found
list.add(line.substring(current, endIndex));
current = line.indexOf("https:", endIndex);
} else {
current = -1;
}
}
}
} catch (Exception ex) {
System.out.println("Error: " + ex.getMessage());
}
return list;
}
}