Instantly share code, notes, and snippets.

# rjlutz/ComputeFactorial.java Created Oct 12, 2017

Abstract Classes and Interfaces (Chapter 18) -- examples from Liang Intro to Java Comprehensive 10e
 import java.util.Scanner; public class ComputeFactorial { /** Main method */ public static void main(String[] args) { // Create a Scanner Scanner input = new Scanner(System.in); System.out.print("Enter a non-negative integer: "); int n = input.nextInt(); // Display factorial System.out.println("Factorial of " + n + " is " + factorial(n)); } /** Return the factorial for a specified number */ public static long factorial(int n) { if (n == 0) // Base case return 1; else return n * factorial(n - 1); // Recursive call } }
 public class ComputeFactorialTailRecursion { /** Return the factorial for a specified number */ public static long factorial(int n) { return factorial(n, 1); // Call auxiliary method } /** Auxiliary tail-recursive method for factorial */ private static long factorial(int n, int result) { if (n == 0) return result; else return factorial(n - 1, n * result); // Recursive call } }
 import java.util.Scanner; public class ComputeFibonacci { /** Main method */ public static void main(String[] args) { // Create a Scanner Scanner input = new Scanner(System.in); System.out.print("Enter an index for a Fibonacci number: "); int index = input.nextInt(); // Find and display the Fibonacci number System.out.println("The Fibonacci number at index " + index + " is " + fib(index)); } /** The method for finding the Fibonacci number */ public static long fib(long index) { if (index == 0) // Base case return 0; else if (index == 1) // Base case return 1; else // Reduction and recursive calls return fib(index - 1) + fib(index - 2); } }
 import java.io.File; import java.util.Scanner; public class DirectorySize { public static void main(String[] args) { // Prompt the user to enter a directory or a file System.out.print("Enter a directory or a file: "); Scanner input = new Scanner(System.in); String directory = input.nextLine(); // Display the size System.out.println(getSize(new File(directory)) + " bytes"); } public static long getSize(File file) { long size = 0; // Store the total size of all files if (file.isDirectory()) { File[] files = file.listFiles(); // All files and subdirectories for (int i = 0; files != null && i < files.length; i++) { size += getSize(files[i]); // Recursive call } } else { // Base case size += file.length(); } return size; } }
 public class RecursiveBinarySearch { public static int recursiveBinarySearch(int[] list, int key) { int low = 0; int high = list.length - 1; return recursiveBinarySearch(list, key, low, high); } private static int recursiveBinarySearch(int[] list, int key, int low, int high) { if (low > high) // The list has been exhausted without a match return -low - 1; int mid = (low + high) / 2; if (key < list[mid]) return recursiveBinarySearch(list, key, low, mid - 1); else if (key == list[mid]) return mid; else return recursiveBinarySearch(list, key, mid + 1, high); } }
 public class RecursiveSelectionSort { public static void sort(double[] list) { sort(list, 0, list.length - 1); // Sort the entire list } private static void sort(double[] list, int low, int high) { if (low < high) { // Find the smallest number and its index in list(low .. high) int indexOfMin = low; double min = list[low]; for (int i = low + 1; i <= high; i++) { if (list[i] < min) { min = list[i]; indexOfMin = i; } } // Swap the smallest in list(low .. high) with list(low) list[indexOfMin] = list[low]; list[low] = min; // Sort the remaining list(low+1 .. high) sort(list, low + 1, high); } } public static void main(String[] args) { double[] list = {2, 1, 3, 1, 2, 5, 2, -1, 0}; sort(list); for (int i = 0; i < list.length; i++) System.out.print(list[i] + " "); } }
 import javafx.application.Application; import javafx.geometry.Point2D; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.scene.shape.Polygon; import javafx.stage.Stage; public class SierpinskiTriangle extends Application { @Override // Override the start method in the Application class public void start(Stage primaryStage) { SierpinskiTrianglePane trianglePane = new SierpinskiTrianglePane(); TextField tfOrder = new TextField(); tfOrder.setOnAction( e -> trianglePane.setOrder(Integer.parseInt(tfOrder.getText()))); tfOrder.setPrefColumnCount(4); tfOrder.setAlignment(Pos.BOTTOM_RIGHT); // Pane to hold label, text field, and a button HBox hBox = new HBox(10); hBox.getChildren().addAll(new Label("Enter an order: "), tfOrder); hBox.setAlignment(Pos.CENTER); BorderPane borderPane = new BorderPane(); borderPane.setCenter(trianglePane); borderPane.setBottom(hBox); // Create a scene and place it in the stage Scene scene = new Scene(borderPane, 200, 210); primaryStage.setTitle("SierpinskiTriangle"); // Set the stage title primaryStage.setScene(scene); // Place the scene in the stage primaryStage.show(); // Display the stage scene.widthProperty().addListener(ov -> trianglePane.paint()); scene.heightProperty().addListener(ov -> trianglePane.paint()); } /** Pane for displaying triangles */ static class SierpinskiTrianglePane extends Pane { private int order = 0; /** Set a new order */ public void setOrder(int order) { this.order = order; paint(); } SierpinskiTrianglePane() { } protected void paint() { // Select three points in proportion to the panel size Point2D p1 = new Point2D(getWidth() / 2, 10); Point2D p2 = new Point2D(10, getHeight() - 10); Point2D p3 = new Point2D(getWidth() - 10, getHeight() - 10); this.getChildren().clear(); // Clear the pane before redisplay displayTriangles(order, p1, p2, p3); } private void displayTriangles(int order, Point2D p1, Point2D p2, Point2D p3) { if (order == 0) { // Draw a triangle to connect three points Polygon triangle = new Polygon(); triangle.getPoints().addAll(p1.getX(), p1.getY(), p2.getX(), p2.getY(), p3.getX(), p3.getY()); triangle.setStroke(Color.BLACK); triangle.setFill(Color.WHITE); this.getChildren().add(triangle); } else { // Get the midpoint on each edge in the triangle Point2D p12 = p1.midpoint(p2); Point2D p23 = p2.midpoint(p3); Point2D p31 = p3.midpoint(p1); // Recursively display three triangles displayTriangles(order - 1, p1, p12, p31); displayTriangles(order - 1, p12, p2, p23); displayTriangles(order - 1, p31, p23, p3); } } } /** * The main method is only needed for the IDE with limited * JavaFX support. Not needed for running from the command line. */ public static void main(String[] args) { launch(args); } }
 import java.util.Scanner; public class TowerOfHanoi { /** Main method */ public static void main(String[] args) { // Create a Scanner Scanner input = new Scanner(System.in); System.out.print("Enter number of disks: "); int n = input.nextInt(); // Find the solution recursively System.out.println("The moves are:"); moveDisks(n, 'A', 'B', 'C'); } /** The method for finding the solution to move n disks from fromTower to toTower with auxTower */ public static void moveDisks(int n, char fromTower, char toTower, char auxTower) { if (n == 1) // Stopping condition System.out.println("Move disk " + n + " from " + fromTower + " to " + toTower); else { moveDisks(n - 1, fromTower, auxTower, toTower); System.out.println("Move disk " + n + " from " + fromTower + " to " + toTower); moveDisks(n - 1, auxTower, toTower, fromTower); } } }