Skip to content

Instantly share code, notes, and snippets.

@rjlutz
Last active November 21, 2018 12:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rjlutz/8df0313bedee7b9112b1505a89316d90 to your computer and use it in GitHub Desktop.
Save rjlutz/8df0313bedee7b9112b1505a89316d90 to your computer and use it in GitHub Desktop.
Exceptions and File I/O (Chapter 12) -- examples from Liang Intro to Java Comprehensive 10e
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;
}
}
public class CircleWithRadiusException {
/** 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 CircleWithRadiusException() {
this(1.0);
}
/** Construct a circle with a specified radius */
public CircleWithRadiusException(double newRadius) {
try {
setRadius(newRadius);
numberOfObjects++;
}
catch (InvalidRadiusException ex) {
ex.printStackTrace();
}
}
/** 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;
}
}
import java.util.*;
public class InputMismatchExceptionDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean continueInput = true;
do {
try {
System.out.print("Enter 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("Try again. (" +
"Incorrect input: an integer is required)");
input.nextLine(); // discard input
}
} while (continueInput);
}
}
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;
}
}
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));
}
}
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 + " / " + number2 + " is "
+ result);
}
catch (ArithmeticException ex) {
System.out.println("Exception: an integer " +
"cannot be divided by zero ");
}
System.out.println("Execution continues ...");
}
}
import java.util.Scanner;
public class QuotientWithIf {
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();
if (number2 != 0)
System.out.println(number1 + " / " + number2 + " is " +
(number1 / number2));
else
System.out.println("Divisor cannot be zero ");
}
}
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);
}
}
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(file);
// 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();
}
}
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 + " bytes");
}
catch (java.net.MalformedURLException ex) {
System.out.println("Invalid URL");
}
catch (java.io.IOException ex) {
System.out.println("IO Errors");
}
}
}
import java.io.*;
import java.util.*;
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 output files
Scanner input = new Scanner(sourceFile);
PrintWriter output = new PrintWriter(targetFile);
) {
while (input.hasNext()) {
String s1 = input.nextLine();
String s2 = s1.replaceAll(args[2], args[3]);
output.println(s2);
}
}
}
}
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 the 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;
}
}
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());
}
}
public class TestCircleWithRadiusException {
/** Main method */
public static void main(String[] args) {
try {
CircleWithRadiusException c1 = new CircleWithRadiusException(5);
c1.setRadius(-5);
CircleWithRadiusException c3 = new CircleWithRadiusException(0);
}
catch (InvalidRadiusException ex) {
System.out.println(ex);
}
System.out.println("Number of objects created: " +
CircleWithRadiusException.getNumberOfObjects());
}
}
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()));
}
}
import java.util.Scanner;
import java.util.ArrayList;
public class WebCrawler {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter a URL: ");
String url = input.nextLine();
crawler(url); // Traverse the Web from the a starting 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("Craw " + 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(url.openStream());
int current = 0;
while (input.hasNext()) {
String line = input.nextLine();
current = line.indexOf("http:", 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("http:", endIndex);
}
else
current = -1;
}
}
}
catch (Exception ex) {
System.out.println("Error: " + ex.getMessage());
}
return list;
}
}
public class WriteData {
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);
}
// 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.println(85);
// Close the file
output.close();
}
}
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.println(85);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment