diff --git a/Checkstyle.xml b/Checkstyle.xml index 75ad255..36dbd1f 100644 --- a/Checkstyle.xml +++ b/Checkstyle.xml @@ -1,35 +1,40 @@ + "-//Checkstyle//DTD Checkstyle Configuration 1.3//EN" + "https://checkstyle.org/dtds/configuration_1_3.dtd"> + - + - + - + + - + - + + + + @@ -37,51 +42,70 @@ Checkstyle configuration for Think Java, 2nd Edition. - - + + + - + - + - + - + + + + + + - + + + + + + + + + + + + + - + + + + - + - + + @@ -94,42 +118,38 @@ Checkstyle configuration for Think Java, 2nd Edition. - + - - + - + + + - - - + + - + diff --git a/Formatter.xml b/Formatter.xml index f97740d..ab6e68e 100644 --- a/Formatter.xml +++ b/Formatter.xml @@ -1,318 +1,390 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/appb/Convert.java b/appb/Convert.java index cc25cb0..232abd6 100644 --- a/appb/Convert.java +++ b/appb/Convert.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Allen Downey and Chris Mayfield + * Copyright (c) 2019 Allen Downey and Chris Mayfield * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -23,7 +23,7 @@ import java.util.Scanner; /** - * Utility class for converting to/from the metric system. + * Methods for converting to/from the metric system. * * @author Allen Downey * @author Chris Mayfield diff --git a/appb/DigitUtil.java b/appb/DigitUtil.java index 9cd7256..04c55eb 100644 --- a/appb/DigitUtil.java +++ b/appb/DigitUtil.java @@ -13,20 +13,16 @@ public class DigitUtil { * @return true if x has one digit, false otherwise */ public static boolean isSingleDigit(int x) { - if (x > -10 && x < 10) { - return true; - } else { - return false; - } - } - - public static boolean isSingleDigit2(int x) { return x > -10 && x < 10; } public static void main(String[] args) { System.out.println(isSingleDigit(2)); + boolean bigFlag = !isSingleDigit(17); + if (bigFlag) { + System.out.println("not single"); + } int z = 9; if (isSingleDigit(z)) { diff --git a/appc/Mickey.java b/appc/Mickey.java index b303b20..73236d6 100644 --- a/appc/Mickey.java +++ b/appc/Mickey.java @@ -11,7 +11,7 @@ public static void main(String[] args) { frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Canvas canvas = new Mickey(); canvas.setSize(400, 400); - canvas.setBackground(Color.white); + canvas.setBackground(Color.WHITE); frame.add(canvas); frame.pack(); frame.setVisible(true); diff --git a/appc/Moire.java b/appc/Moire.java index b736d97..6c3e78c 100644 --- a/appc/Moire.java +++ b/appc/Moire.java @@ -10,7 +10,7 @@ public static void main(String[] args) { frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Canvas canvas = new Moire(); canvas.setSize(400, 400); - canvas.setBackground(Color.white); + canvas.setBackground(Color.WHITE); frame.add(canvas); frame.pack(); frame.setVisible(true); diff --git a/appd/Complex.java b/appd/Complex.java index ac4c50f..2a86ee6 100644 --- a/appd/Complex.java +++ b/appd/Complex.java @@ -1,10 +1,13 @@ import java.awt.Rectangle; /** - * Example from "My method doesn't return what I expect." + * Examples from Logic Errors section. */ public class Complex { + /** + * My method doesn't return what I expect. + */ public static Rectangle intersection(Rectangle a, Rectangle b) { int x1 = Math.min(a.x, b.x); int y1 = Math.min(a.y, b.y); @@ -14,10 +17,19 @@ public static Rectangle intersection(Rectangle a, Rectangle b) { return rect; } + /** + * I've got a big, hairy expression and it doesn’t do what I expect. + */ public static void main(String[] args) { - Rectangle x = new Rectangle(0, 0, 10, 10); - Rectangle y = new Rectangle(-5, -5, -5, -5); - System.out.println(intersection(x, y)); + Rectangle rect = new Rectangle(0, 0, 10, 10); + Rectangle ngle = new Rectangle(-5, -5, -5, -5); + System.out.println(intersection(rect, ngle)); + + double halfWidth = 0.5 * rect.getWidth(); + double halfHeight = 0.5 * rect.getHeight(); + int dx = (int) Math.round(halfWidth); + int dy = (int) Math.round(halfHeight); + rect.translate(dx, dy); } } diff --git a/ch02/DeclareAssign.java b/ch02/DeclareAssign.java new file mode 100644 index 0000000..87a8e02 --- /dev/null +++ b/ch02/DeclareAssign.java @@ -0,0 +1,23 @@ +public class DeclareAssign { + + public static void main(String[] args) { + String message; + int x; + + String firstName; + String lastName; + int hour, minute; + + message = "Hello!"; // give message the value "Hello!" + hour = 11; // assign the value 11 to hour + minute = 59; // set minute to 59 + + message = "123"; // legal + // message = 123; // not legal + + String message2 = "Hello!"; + int hour2 = 11; + int minute2 = 59; + } + +} diff --git a/ch02/FloatingPoint.java b/ch02/FloatingPoint.java new file mode 100644 index 0000000..b9afa1c --- /dev/null +++ b/ch02/FloatingPoint.java @@ -0,0 +1,21 @@ +public class FloatingPoint { + + public static void main(String[] args) { + double pi; + pi = 3.14159; + + double minute3 = 59.0; + System.out.print("Fraction of the hour that has passed: "); + System.out.println(minute3 / 60.0); + + double y = 1.0 / 3.0; // correct + + System.out.println(0.1 * 10); + System.out.println(0.1 + 0.1 + 0.1 + 0.1 + 0.1 + + 0.1 + 0.1 + 0.1 + 0.1 + 0.1); + + double balance = 123.45; // potential rounding error + int balance2 = 12345; // total number of cents + } + +} diff --git a/ch02/Hello.java b/ch02/Hello.java new file mode 100644 index 0000000..bbc0349 --- /dev/null +++ b/ch02/Hello.java @@ -0,0 +1,8 @@ +public class Hello { + + public static void main(String[] args) { + System.out.println("Hello, "); + System.out.println("World!"); + } + +} diff --git a/ch02/MemoryDiagram.java b/ch02/MemoryDiagram.java new file mode 100644 index 0000000..1fecfd8 --- /dev/null +++ b/ch02/MemoryDiagram.java @@ -0,0 +1,10 @@ +public class MemoryDiagram { + + public static void main(String[] args) { + int a = 5; + int b = a; // a and b are now equal + a = 3; // a and b are no longer equal + int c = 0; + } + +} diff --git a/ch02/PrintingVars.java b/ch02/PrintingVars.java new file mode 100644 index 0000000..27a0f08 --- /dev/null +++ b/ch02/PrintingVars.java @@ -0,0 +1,28 @@ +public class PrintingVars { + + public static void main(String[] args) { + String firstLine = "Hello, again!"; + System.out.println(firstLine); + + System.out.print("The value of firstLine is "); + System.out.println(firstLine); + + int hour = 11; + int minute = 59; + System.out.print("The current time is "); + System.out.print(hour); + System.out.print(":"); + System.out.print(minute); + System.out.println("."); + + System.out.print("Number of minutes since midnight: "); + System.out.println(hour * 60 + minute); + + System.out.print("Fraction of the hour that has passed: "); + System.out.println(minute / 60); + + System.out.print("Percent of the hour that has passed: "); + System.out.println(minute * 100 / 60); + } + +} diff --git a/ch02/StringConcat.java b/ch02/StringConcat.java new file mode 100644 index 0000000..4ec9902 --- /dev/null +++ b/ch02/StringConcat.java @@ -0,0 +1,12 @@ +public class StringConcat { + + public static void main(String[] args) { + System.out.println(1 + 2 + "Hello"); + // the output is 3Hello + + System.out.println("Hello" + 1 + 2); + // the output is Hello12 + + } + +} diff --git a/ch02/Variables.java b/ch02/Variables.java deleted file mode 100644 index f6ce6ee..0000000 --- a/ch02/Variables.java +++ /dev/null @@ -1,71 +0,0 @@ -public class Variables { - - public static void main(String[] args) { - - String message; - int x; - - String firstName; - String lastName; - int hour, minute; - - message = "Hello!"; // give message the value "Hello!" - hour = 11; // assign the value 11 to hour - minute = 59; // set minute to 59 - - message = "123"; // legal - // message = 123; // not legal - - String message2 = "Hello!"; - int hour2 = 11; - int minute2 = 59; - - int a = 5; - int b = a; // a and b are now equal - a = 3; // a and b are no longer equal - - String firstLine = "Hello, again!"; - System.out.println(firstLine); - - System.out.print("The value of firstLine is "); - System.out.println(firstLine); - - System.out.print("The current time is "); - System.out.print(hour); - System.out.print(":"); - System.out.print(minute); - System.out.println("."); - - System.out.print("Number of minutes since midnight: "); - System.out.println(hour * 60 + minute); - - System.out.print("Fraction of the hour that has passed: "); - System.out.println(minute / 60); - - System.out.print("Percent of the hour that has passed: "); - System.out.println(minute * 100 / 60); - - double pi; - pi = 3.14159; - - double minute3 = 59.0; - System.out.print("Fraction of the hour that has passed: "); - System.out.println(minute3 / 60.0); - - double y = 1.0 / 3.0; // correct - - System.out.println(0.1 * 10); - System.out.println(0.1 + 0.1 + 0.1 + 0.1 + 0.1 - + 0.1 + 0.1 + 0.1 + 0.1 + 0.1); - - double balance = 123.45; // potential rounding error - int balance2 = 12345; // total number of cents - - System.out.println(1 + 2 + "Hello"); - // the output is 3Hello - - System.out.println("Hello" + 1 + 2); - // the output is Hello12 - } - -} diff --git a/ch03/Formatting.java b/ch03/Formatting.java new file mode 100644 index 0000000..7beced4 --- /dev/null +++ b/ch03/Formatting.java @@ -0,0 +1,33 @@ +/** + * Examples from the middle of the chapter. + */ +public class Formatting { + + public static void main(String[] args) { + final double CM_PER_INCH = 2.54; + + System.out.println(System.out); + + // formatting output + + System.out.print(4.0 / 3.0); + System.out.printf("Four thirds = %.3f", 4.0 / 3.0); + + int inch = 100; + double cm = inch * CM_PER_INCH; + System.out.printf("%d in = %f cm\n", inch, cm); + + // type cast operators + + double pi = 3.14159; + int xi = (int) pi; + + double x = (int) pi * 20.0; // result is 60.0, not 62.0 + + inch = (int) (cm / CM_PER_INCH); + System.out.printf("%f cm = %d in\n", cm, inch); + + System.out.printf("inches = %d" + inch); // error + } + +} diff --git a/ch03/Input.java b/ch03/Input.java deleted file mode 100644 index de97dc0..0000000 --- a/ch03/Input.java +++ /dev/null @@ -1,16 +0,0 @@ -/** - * Examples from Chapter 3. - */ -public class Input { - - public static void main(String[] args) { - System.out.println(System.out); - - System.out.print(4.0 / 3.0); - System.out.printf("Four thirds = %.3f", 4.0 / 3.0); - - double pi = 3.14159; - double x = (int) pi * 20.0; - } - -} diff --git a/ch03/Literals.java b/ch03/Literals.java new file mode 100644 index 0000000..3741364 --- /dev/null +++ b/ch03/Literals.java @@ -0,0 +1,22 @@ +import java.util.Scanner; + +/** + * Converts inches to centimeters. + */ +public class Literals { + + public static void main(String[] args) { + int inch; + double cm; + Scanner in = new Scanner(System.in); + + System.out.print("How many inches? "); + inch = in.nextInt(); + + final double CM_PER_INCH = 2.54; + cm = inch * CM_PER_INCH; + System.out.print(inch + " in = "); + System.out.println(cm + " cm"); + } + +} diff --git a/ch03/ScannerBug.java b/ch03/ScannerBug.java index 353affb..bef7834 100644 --- a/ch03/ScannerBug.java +++ b/ch03/ScannerBug.java @@ -16,6 +16,9 @@ public static void main(String[] args) { age = in.nextInt(); System.out.printf("Hello %s, age %d\n", name, age); + in.reset(); + System.out.println(); + System.out.print("What is your age? "); age = in.nextInt(); System.out.print("What is your name? "); diff --git a/ch04/Circle.java b/ch04/Circle.java index a09e594..f79af90 100644 --- a/ch04/Circle.java +++ b/ch04/Circle.java @@ -1,76 +1,13 @@ public class Circle { public static double calculateArea(double radius) { - double result = Math.PI * radius * radius; - return result; - } - - public static double calculateArea2(double radius) { return Math.PI * radius * radius; } - public static double distance - (double x1, double y1, double x2, double y2) { - double dx = x2 - x1; - double dy = y2 - y1; - System.out.println("dx is " + dx); - System.out.println("dy is " + dy); - return 0.0; - } - - public static double distance2 - (double x1, double y1, double x2, double y2) { - double dx = x2 - x1; - double dy = y2 - y1; - double dsquared = dx * dx + dy * dy; - System.out.println("dsquared is " + dsquared); - return 0.0; - } - - public static double distance3 - (double x1, double y1, double x2, double y2) { - double dx = x2 - x1; - double dy = y2 - y1; - double dsquared = dx * dx + dy * dy; - double result = Math.sqrt(dsquared); - return result; - } - - public static double circleArea - (double xc, double yc, double xp, double yp) { - double radius = distance(xc, yc, xp, yp); - double area = calculateArea(radius); - return area; - } - - public static double calculateArea - (double xc, double yc, double xp, double yp) { - return calculateArea(distance(xc, yc, xp, yp)); - } - public static void main(String[] args) { - - System.out.println("calculateArea"); - System.out.println(calculateArea(3.0)); - - System.out.println("calculateArea2"); - System.out.println(calculateArea2(3.0)); - - System.out.println("distance"); - System.out.println(distance(1.0, 2.0, 4.0, 6.0)); - - System.out.println("distance2"); - System.out.println(distance2(1.0, 2.0, 4.0, 6.0)); - - System.out.println("distance3"); - System.out.println(distance3(1.0, 2.0, 4.0, 6.0)); - - System.out.println("circleArea"); - System.out.println(circleArea(1.0, 2.0, 4.0, 6.0)); - - System.out.println("calculateArea with 4 doubles"); - System.out.println(calculateArea(1.0, 2.0, 4.0, 6.0)); - + double diameter = 10.0; + double area = calculateArea(diameter / 2); + System.out.println(area); } } diff --git a/ch04/Distance.java b/ch04/Distance.java new file mode 100644 index 0000000..5bdb9ad --- /dev/null +++ b/ch04/Distance.java @@ -0,0 +1,45 @@ +public class Distance { + + public static double distance1(double x1, double y1, double x2, double y2) { + return 0.0; // stub + } + + public static double distance2(double x1, double y1, double x2, double y2) { + double dx = x2 - x1; + double dy = y2 - y1; + System.out.println("dx is " + dx); + System.out.println("dy is " + dy); + return 0.0; // stub + } + + public static double distance3(double x1, double y1, double x2, double y2) { + double dx = x2 - x1; + double dy = y2 - y1; + double dsquared = dx * dx + dy * dy; + System.out.println("dsquared is " + dsquared); + return 0.0; // stub + } + + public static double distance4(double x1, double y1, double x2, double y2) { + double dx = x2 - x1; + double dy = y2 - y1; + double dsquared = dx * dx + dy * dy; + double result = Math.sqrt(dsquared); + return result; + } + + public static void main(String[] args) { + System.out.println("\ndistance version 1"); + System.out.println(distance1(1.0, 2.0, 4.0, 6.0)); + + System.out.println("\ndistance version 2"); + System.out.println(distance2(1.0, 2.0, 4.0, 6.0)); + + System.out.println("\ndistance version 3"); + System.out.println(distance3(1.0, 2.0, 4.0, 6.0)); + + System.out.println("\ndistance version 4"); + System.out.println(distance4(1.0, 2.0, 4.0, 6.0)); + } + +} diff --git a/ch04/Methods.java b/ch04/MathMethods.java similarity index 89% rename from ch04/Methods.java rename to ch04/MathMethods.java index 90c1b7a..51ef7dc 100644 --- a/ch04/Methods.java +++ b/ch04/MathMethods.java @@ -1,7 +1,4 @@ -/** - * Examples from Chapter 4. - */ -public class Methods { +public class MathMethods { public static void main(String[] args) { double root = Math.sqrt(17.0); @@ -10,10 +7,14 @@ public static void main(String[] args) { double degrees = 90; double angle2 = degrees / 180.0 * Math.PI; + double radians = Math.toRadians(180.0); double degrees2 = Math.toDegrees(Math.PI); + long x = Math.round(Math.PI * 20.0); + // examples of composition + double x2 = Math.cos(angle + Math.PI / 2.0); double x3 = Math.exp(Math.log(10.0)); double x4 = Math.pow(2.0, 10.0); diff --git a/ch04/PrintTime.java b/ch04/PrintTime.java index 019d579..055781f 100644 --- a/ch04/PrintTime.java +++ b/ch04/PrintTime.java @@ -10,6 +10,9 @@ public static void main(String[] args) { int hour = 11; int minute = 59; printTime(hour, minute); + + // additional example for stack diagram + printTime(hour + 1, 0); } } diff --git a/ch04/PrintTwice.java b/ch04/PrintTwice.java index 7131085..1180417 100644 --- a/ch04/PrintTwice.java +++ b/ch04/PrintTwice.java @@ -7,6 +7,9 @@ public static void printTwice(String s) { public static void main(String[] args) { printTwice("Don't make me say this twice!"); + + String message = "Never say never."; + printTwice(message); } } diff --git a/ch05/ChainNest.java b/ch05/ChainNest.java new file mode 100644 index 0000000..9d1fd11 --- /dev/null +++ b/ch05/ChainNest.java @@ -0,0 +1,25 @@ +public class ChainNest { + + public static void main(String[] args) { + int x = 0; + + if (x > 0) { + System.out.println("x is positive"); + } else if (x < 0) { + System.out.println("x is negative"); + } else { + System.out.println("x is zero"); + } + + if (x > 0) { + System.out.println("x is positive"); + } else { + if (x < 0) { + System.out.println("x is negative"); + } else { + System.out.println("x is zero"); + } + } + } + +} diff --git a/ch05/Conditional.java b/ch05/Conditional.java deleted file mode 100644 index 5a5a4ca..0000000 --- a/ch05/Conditional.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Examples from Chapter 5. - */ -public class Conditional { - - public static void main(String[] args) { - int x = 17; - int n = 18; - - if (x > 0) { - System.out.println("x is positive"); - } - - if (x % 2 == 0) { - System.out.println("x is even"); - } else { - System.out.println("x is odd"); - } - - if (x > 0) { - System.out.println("x is positive"); - } else if (x < 0) { - System.out.println("x is negative"); - } else { - System.out.println("x is zero"); - } - - if (x > 0) { - System.out.println("x is positive"); - } else { - if (x < 0) { - System.out.println("x is negative"); - } else { - System.out.println("x is zero"); - } - } - - boolean evenFlag = (n % 2 == 0); // true if n is even - boolean positiveFlag = (x > 0); // true if x is positive - - if (evenFlag) { - System.out.println("n was even when I checked it"); - } - - if (!evenFlag) { - System.out.println("n was odd when I checked it"); - } - } - -} diff --git a/ch05/DigitUtil.java b/ch05/DigitUtil.java new file mode 100644 index 0000000..551e9a9 --- /dev/null +++ b/ch05/DigitUtil.java @@ -0,0 +1,27 @@ +public class DigitUtil { + + public static boolean isSingleDigit(int x) { + if (x > -10 && x < 10) { + return true; + } else { + return false; + } + } + + public static boolean isSingleDigit2(int x) { + return x > -10 && x < 10; + } + + public static void main(String[] args) { + System.out.println(isSingleDigit(2)); + boolean bigFlag = !isSingleDigit(17); + + int z = 9; + if (isSingleDigit(z)) { + System.out.println("z is small"); + } else { + System.out.println("z is big"); + } + } + +} diff --git a/ch05/IfElse.java b/ch05/IfElse.java new file mode 100644 index 0000000..83a0e72 --- /dev/null +++ b/ch05/IfElse.java @@ -0,0 +1,32 @@ +public class IfElse { + + public static void main(String[] args) { + int x = 17; + int n = 18; + + if (x > 0) { + System.out.println("x is positive"); + } + + if (x % 2 == 0) { + System.out.println("x is even"); + } else { + System.out.println("x is odd"); + } + + // look, no braces...bad idea! + if (x % 2 == 0) + System.out.println("x is even"); + else + System.out.println("x is odd"); + + if (x > 0) + System.out.println("x is positive"); + System.out.println("x is not zero"); + + if (x % 2 == 0); { // incorrect semicolon + System.out.println("x is even"); + } + } + +} diff --git a/ch05/Logarithm.java b/ch05/Logarithm.java index 4e2fd45..ef9e53a 100644 --- a/ch05/Logarithm.java +++ b/ch05/Logarithm.java @@ -20,7 +20,7 @@ public static void main(String[] args) { // check the range double x = in.nextDouble(); - if (x >= 0) { + if (x > 0) { double y = Math.log(x); System.out.println("The log is " + y); } else { diff --git a/ch05/LogicalOpers.java b/ch05/LogicalOpers.java new file mode 100644 index 0000000..e9dc6dd --- /dev/null +++ b/ch05/LogicalOpers.java @@ -0,0 +1,56 @@ +public class LogicalOpers { + + public static void main(String[] args) { + int x = 0; + int y = 0; + + // nested + if (x == 0) { + if (y == 0) { + System.out.println("Both x and y are zero"); + } + } + + // combined + if (x == 0 && y == 0) { + System.out.println("Both x and y are zero"); + } + + // chained + if (x == 0) { + System.out.println("Either x or y is zero"); + } else if (y == 0) { + System.out.println("Either x or y is zero"); + } + + // combined + if (x == 0 || y == 0) { + System.out.println("Either x or y is zero"); + } + + // De Morgan's + if (!(x == 0 || y == 0)) { + System.out.println("Neither x nor y is zero"); + } + if (x != 0 && y != 0) { + System.out.println("Neither x nor y is zero"); + } + + // boolean variables + boolean flag; + flag = true; + boolean testResult = false; + + boolean evenFlag = (x % 2 == 0); // true if x is even + boolean positiveFlag = (x > 0); // true if x is positive + + if (evenFlag) { + System.out.println("n was even when I checked it"); + } + + if (!evenFlag) { + System.out.println("n was odd when I checked it"); + } + } + +} diff --git a/ch05/Switch.java b/ch05/Switch.java new file mode 100644 index 0000000..70916b7 --- /dev/null +++ b/ch05/Switch.java @@ -0,0 +1,56 @@ +public class Switch { + + public static void main(String[] args) { + int number = 0; + String word; + + // if-else-if + + if (number == 1) { + word = "one"; + } else if (number == 2) { + word = "two"; + } else if (number == 3) { + word = "three"; + } else { + word = "unknown"; + } + + // same result as above + + switch (number) { + case 1: + word = "one"; + break; + case 2: + word = "two"; + break; + case 3: + word = "three"; + break; + default: + word = "unknown"; + break; + } + + System.out.print(number); + System.out.print(word); + + // switch blocks fall through + + String food = "apple"; + switch (food) { + case "apple": + case "banana": + case "cherry": + System.out.println("Fruit!"); + break; + case "asparagus": + case "broccoli": + case "carrot": + System.out.println("Vegetable!"); + break; + } + } + +} diff --git a/ch06/Loops.java b/ch06/Loops.java index f333df9..4f59564 100644 --- a/ch06/Loops.java +++ b/ch06/Loops.java @@ -1,5 +1,5 @@ /** - * Examples from Chapter 6. + * Demonstrates uses of loops. */ public class Loops { @@ -26,7 +26,7 @@ public static void plusplus() { int i = 1; while (i <= 5) { System.out.println(i); - i++; // add 1 to i + i++; // add 1 to i } } @@ -34,7 +34,14 @@ public static void appreciate() { int i = 2; while (i <= 8) { System.out.print(i + ", "); - i += 2; // add 2 to i + i += 2; // add 2 to i + } + System.out.println("Who do we appreciate?"); + } + + public static void appreciate2() { + for (int i = 2; i <= 8; i += 2) { + System.out.print(i + ", "); } System.out.println("Who do we appreciate?"); } @@ -57,22 +64,25 @@ public static void nested() { } public static void main(String[] args) { - System.out.println("countdown"); + System.out.println("\ncountdown"); countdown(3); - System.out.println("sequence"); + System.out.println("\nsequence"); sequence(10); - System.out.println("plusplus"); + System.out.println("\nplusplus"); plusplus(); - System.out.println("appreciate"); + System.out.println("\nappreciate"); appreciate(); - System.out.println("loopvar"); + System.out.println("\nappreciate2"); + appreciate2(); + + System.out.println("\nloopvar"); loopvar(); - System.out.println("nested"); + System.out.println("\nnested"); nested(); } diff --git a/ch06/Strings.java b/ch06/Strings.java index 09b817f..f8b40f0 100644 --- a/ch06/Strings.java +++ b/ch06/Strings.java @@ -1,5 +1,7 @@ +import java.util.Scanner; + /** - * Demonstrates uses of Strings. + * Demonstrates uses of strings. */ public class Strings { @@ -10,8 +12,8 @@ public static void main(String[] args) { String fruit = "banana"; char letter0 = fruit.charAt(0); - if (letter0 == 'a') { - System.out.println('?'); + if (letter0 == 'A') { + System.out.println("It's an A!"); } System.out.print("Roman alphabet: "); @@ -26,6 +28,18 @@ public static void main(String[] args) { } System.out.println(); + // Which loop to use + + Scanner in = new Scanner(System.in); + System.out.print("Enter a number: "); + while (!in.hasNextDouble()) { + String word = in.next(); + System.err.println(word + " is not a number"); + System.out.print("Enter a number: "); + } + double number = in.nextDouble(); + in.nextLine(); // read the newline + // String iteration for (int i = 0; i < fruit.length(); i++) { @@ -43,8 +57,30 @@ public static void main(String[] args) { int index = fruit.indexOf('a'); int index2 = fruit.indexOf('a', 2); + // Substrings + + System.out.println(fruit.substring(0, 3)); + System.out.println(fruit.substring(2, 5)); + System.out.println(fruit.substring(6, 6)); + + System.out.println(fruit.substring(0)); + System.out.println(fruit.substring(2)); + System.out.println(fruit.substring(6)); + // String comparison + System.out.print("Play again? "); + String answer = in.nextLine(); + if (answer == "yes") { // wrong! + System.out.println("Let's go!"); + } else { + System.out.println("Goodbye!"); + } + + if (answer.equals("yes")) { // correct + System.out.println("Let's go!"); + } + String name1 = "Alan Turing"; String name2 = "Ada Lovelace"; if (name1.equals(name2)) { @@ -52,24 +88,13 @@ public static void main(String[] args) { } int diff = name1.compareTo(name2); - if (diff == 0) { - System.out.println("The names are the same."); - } else if (diff < 0) { + if (diff < 0) { System.out.println("name1 comes before name2."); } else if (diff > 0) { System.out.println("name2 comes before name1."); + } else { + System.out.println("The names are the same."); } - - // Substrings - - System.out.println(fruit.substring(0)); - System.out.println(fruit.substring(2)); - System.out.println(fruit.substring(6)); - - System.out.println(fruit.substring(0, 3)); - System.out.println(fruit.substring(2, 5)); - System.out.println(fruit.substring(6, 6)); - } /** diff --git a/ch07/ArrayExamples.java b/ch07/ArrayExamples.java index 0ac26f3..9fecdc0 100644 --- a/ch07/ArrayExamples.java +++ b/ch07/ArrayExamples.java @@ -30,6 +30,7 @@ public static void main(String[] args) { System.out.println(counts[i]); } + // displaying arrays int[] array = {1, 2, 3, 4}; printArray(array); @@ -49,9 +50,9 @@ public static void main(String[] args) { // copying with Arrays class double[] c = Arrays.copyOf(a, a.length); - // traversal + // traversing arrays for (int i = 0; i < a.length; i++) { - a[i] = Math.pow(a[i], 2.0); + a[i] *= a[i]; } // search @@ -66,10 +67,10 @@ public static void main(String[] args) { /** * Prints the elements of an array. */ - public static void printArray(int[] array) { - System.out.print("{" + array[0]); - for (int i = 1; i < array.length; i++) { - System.out.print(", " + array[i]); + public static void printArray(int[] a) { + System.out.print("{" + a[0]); + for (int i = 1; i < a.length; i++) { + System.out.print(", " + a[i]); } System.out.println("}"); } @@ -77,22 +78,22 @@ public static void printArray(int[] array) { /** * Returns the index of the target in the array, or -1 if not found. */ - public static int search(double[] a, double target) { - for (int i = 0; i < a.length; i++) { - if (a[i] == target) { + public static int search(double[] array, double target) { + for (int i = 0; i < array.length; i++) { + if (array[i] == target) { return i; } } - return -1; + return -1; // not found } /** * Returns the total of the elements in an array. */ - public static double sum(double[] a) { + public static double sum(double[] array) { double total = 0.0; - for (int i = 0; i < a.length; i++) { - total += a[i]; + for (int i = 0; i < array.length; i++) { + total += array[i]; } return total; } diff --git a/ch07/Doubloon.java b/ch07/Doubloon.java index 61103e0..aba5ed7 100644 --- a/ch07/Doubloon.java +++ b/ch07/Doubloon.java @@ -2,7 +2,7 @@ * Example from the end of Chapter 7. */ public class Doubloon { - + public static boolean isDoubloon(String s) { // count the number of times each letter appears @@ -21,10 +21,9 @@ public static boolean isDoubloon(String s) { } return true; } - + public static void main(String[] args) { - System.out.println(isDoubloon("Mama")); - System.out.println(isDoubloon("Lama")); + System.out.println(isDoubloon("Mama")); // true + System.out.println(isDoubloon("Lama")); // false } - } diff --git a/ch07/Histogram.java b/ch07/Histogram.java index 32b029c..fe9f0b7 100644 --- a/ch07/Histogram.java +++ b/ch07/Histogram.java @@ -31,8 +31,7 @@ public static int inRange(int[] a, int low, int high) { } public static void main(String[] args) { - int numValues = 8; - int[] array = randomArray(numValues); + int[] array = randomArray(8); ArrayExamples.printArray(array); int[] scores = randomArray(30); diff --git a/ch08/CodingBat.java b/ch08/CodingBat.java index c51f2f4..f6ad0d5 100644 --- a/ch08/CodingBat.java +++ b/ch08/CodingBat.java @@ -3,26 +3,35 @@ */ public class CodingBat { - public static String noX(String str) { + /** + * See https://codingbat.com/prob/p118230. + */ + public String noX(String str) { if (str.length() == 0) { return ""; } - char c = str.charAt(0); - if (c == 'x') { - return noX(str.substring(1)); + char first = str.charAt(0); + String rest = str.substring(1); + String recurse = noX(rest); + if (first == 'x') { + return recurse; } else { - return c + noX(str.substring(1)); + return first + recurse; } } + /** + * See https://codingbat.com/prob/p135988. + */ public int array11(int[] nums, int index) { if (index >= nums.length) { return 0; } + int recurse = array11(nums, index + 1); if (nums[index] == 11) { - return 1 + array11(nums, index + 1); + return recurse + 1; } else { - return array11(nums, index + 1); + return recurse; } } diff --git a/ch08/Recursion.java b/ch08/Examples.java similarity index 92% rename from ch08/Recursion.java rename to ch08/Examples.java index 04ac198..39b22dd 100644 --- a/ch08/Recursion.java +++ b/ch08/Examples.java @@ -1,19 +1,4 @@ -public class Recursion { - - public static void main(String[] args) { - System.out.println("countdown"); - countdown(3); - - System.out.println("nLines"); - nLines(3); - - System.out.println("countup"); - countup(3); - - System.out.println("displayBinary"); - displayBinary(23); - System.out.println(); - } +public class Examples { public static void countdown(int n) { if (n == 0) { @@ -24,10 +9,6 @@ public static void countdown(int n) { } } - public static void newLine() { - System.out.println(); - } - public static void nLines(int n) { if (n > 0) { System.out.println(); @@ -56,4 +37,21 @@ public static void displayBinary(int value) { } } + public static void main(String[] args) { + System.out.println("countdown"); + countdown(3); + + System.out.println("nLines"); + nLines(3); + + // forever("Ha!"); + + System.out.println("countup"); + countup(3); + + System.out.println("displayBinary"); + displayBinary(23); + System.out.println(); + } + } diff --git a/ch08/Series.java b/ch08/Series.java index 86e8148..fb1c860 100644 --- a/ch08/Series.java +++ b/ch08/Series.java @@ -1,6 +1,3 @@ -/** - * Examples from Chapter 8. - */ public class Series { public static int factorial(int n) { diff --git a/ch09/ArgValid.java b/ch09/ArgValid.java new file mode 100644 index 0000000..29e4d0a --- /dev/null +++ b/ch09/ArgValid.java @@ -0,0 +1,20 @@ +/** + * Example of argument validation. + */ +public class ArgValid { + + public static boolean isCapitalized(String str) { + if (str == null || str.isEmpty()) { + return false; + } + return Character.isUpperCase(str.charAt(0)); + } + + public static void main(String[] args) { + System.out.println(isCapitalized("Hi!")); + System.out.println(isCapitalized("bye")); + System.out.println(isCapitalized("")); + System.out.println(isCapitalized(null)); + } + +} diff --git a/ch09/BigInt.java b/ch09/BigInt.java new file mode 100644 index 0000000..05b4da5 --- /dev/null +++ b/ch09/BigInt.java @@ -0,0 +1,20 @@ +import java.math.BigInteger; + +/** + * BigInteger examples. + */ +public class BigInt { + + public static void main(String[] args) { + long x = 17; + BigInteger big = BigInteger.valueOf(x); + + String s = "12345678901234567890"; + BigInteger bigger = new BigInteger(s); + + BigInteger a = BigInteger.valueOf(17); + BigInteger b = BigInteger.valueOf(1700000000); + BigInteger c = a.add(b); + } + +} diff --git a/ch09/Objects.java b/ch09/Objects.java index 6dde3a0..ae7b350 100644 --- a/ch09/Objects.java +++ b/ch09/Objects.java @@ -1,5 +1,3 @@ -import java.math.BigInteger; - /** * Demonstrates uses of objects and wrappers. */ @@ -14,22 +12,40 @@ public static void main(String[] args) { char[] array = {'c', 'a', 't'}; String word = "dog"; + String word1 = new String("dog"); // creates a string object + String word2 = "dog"; // implicitly creates a string object + + // the null keyword + + String name0 = null; + int[] combo = null; + // System.out.println(name0.length()); // NullPointerException + // System.out.println(combo[0]); // NullPointerException + // Strings are immutable String name = "Alan Turing"; String upperName = name.toUpperCase(); + name.toUpperCase(); // ignores the return value + System.out.println(name); + name = name.toUpperCase(); // references the new string + System.out.println(name); + String text = "Computer Science is fun!"; text = text.replace("Computer Science", "CS"); // Wrapper classes + Integer i = Integer.valueOf(5); + System.out.println(i.equals(5)); // displays true + Integer x = Integer.valueOf(123); Integer y = Integer.valueOf(123); - if (x == y) { // false + if (x == y) { // false System.out.println("x and y are the same object"); } - if (x.equals(y)) { // true + if (x.equals(y)) { // true System.out.println("x and y have the same value"); } @@ -38,18 +54,6 @@ public static void main(String[] args) { num = 12345; str = Integer.toString(num); - - // BigInteger arithmetic - - long z = 17; - BigInteger big = BigInteger.valueOf(z); - - String s = "12345678901234567890"; - BigInteger bigger = new BigInteger(s); - - BigInteger a = BigInteger.valueOf(17); - BigInteger b = BigInteger.valueOf(1700000000); - BigInteger c = a.add(b); } } diff --git a/ch09/Tables.java b/ch09/Tables.java index f1a5423..1ceaec9 100644 --- a/ch09/Tables.java +++ b/ch09/Tables.java @@ -4,73 +4,61 @@ public class Tables { public static void printRow() { - int i = 1; - while (i <= 6) { + for (int i = 1; i <= 6; i++) { System.out.printf("%4d", 2 * i); - i = i + 1; } System.out.println(); } public static void printRow(int n) { - int i = 1; - while (i <= 6) { + for (int i = 1; i <= 6; i++) { System.out.printf("%4d", n * i); // generalized n - i = i + 1; } System.out.println(); } public static void printTable() { - int i = 1; - while (i <= 6) { + for (int i = 1; i <= 6; i++) { printRow(i); - i = i + 1; } } public static void printTable(int rows) { - int i = 1; - while (i <= rows) { // generalized rows + for (int i = 1; i <= rows; i++) { // generalized rows printRow(i); - i = i + 1; } } public static void printRow(int n, int cols) { - int i = 1; - while (i <= cols) { // generalized cols + for (int i = 1; i <= cols; i++) { // generalized cols System.out.printf("%4d", n * i); - i = i + 1; } System.out.println(); } public static void printTable2(int rows) { - int i = 1; - while (i <= rows) { - printRow(i, rows); // added rows argument - i = i + 1; + for (int i = 1; i <= rows; i++) { + printRow(i, rows); } } public static void main(String[] args) { - System.out.println("printRow()"); + System.out.println("\nprintRow()"); printRow(); - System.out.println("printRow(6)"); + System.out.println("\nprintRow(6)"); printRow(6); - System.out.println("printTable()"); + System.out.println("\nprintTable()"); printTable(); - System.out.println("printTable(6)"); + System.out.println("\nprintTable(6)"); printTable(6); - System.out.println("printRow(6, 6)"); + System.out.println("\nprintRow(6, 6)"); printRow(6, 6); - System.out.println("printTable2(6)"); + System.out.println("\nprintTable2(6)"); printTable2(6); } diff --git a/ch10/Append.java b/ch10/Append.java deleted file mode 100644 index 98a9c10..0000000 --- a/ch10/Append.java +++ /dev/null @@ -1,13 +0,0 @@ -import java.util.Scanner; -public class Append { - public static void main(String[] args) { - Scanner in = new Scanner(System.in); - System.out.println("Enter 10 lines:"); - String text = ""; - for (int i = 0; i < 10; i++) { - String line = in.nextLine(); // new string - text = text + line + '\n'; // two more strings - } - System.out.print("You entered:\n" + text); - } -} diff --git a/ch10/Builder.java b/ch10/Builder.java new file mode 100644 index 0000000..8fe955e --- /dev/null +++ b/ch10/Builder.java @@ -0,0 +1,35 @@ +import java.util.Scanner; + +/* + * StringBuilder example. + */ +public class Builder { + + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + + // less efficient + System.out.println("Enter 10 lines:"); + + String slow = ""; + for (int i = 0; i < 10; i++) { + String line = in.nextLine(); // new string + slow = slow + line + '\n'; // two more strings + } + System.out.print("You entered:\n" + slow); + + // more efficient + System.out.println("Enter 10 lines:"); + + StringBuilder text = new StringBuilder(); + for (int i = 0; i < 10; i++) { + String line = in.nextLine(); + text.append(line); + text.append('\n'); + } + System.out.print("You entered:\n" + text); + + String result = text.toString(); + } + +} diff --git a/ch10/PointRect.java b/ch10/PointRect.java index cb0af07..301dd90 100644 --- a/ch10/PointRect.java +++ b/ch10/PointRect.java @@ -9,27 +9,40 @@ public class PointRect { public static void main(String[] args) { Point blank; blank = new Point(3, 4); - System.out.println(blank); int x = blank.x; System.out.println(blank.x + ", " + blank.y); int sum = blank.x * blank.x + blank.y * blank.y; + // objects as parameters + Point p1 = new Point(0, 0); Point p2 = new Point(3, 4); + double temp = distance(p1, p2); double dist = p1.distance(p2); // dist is 5.0 + System.out.println(blank); + + // objects as return values Rectangle box = new Rectangle(0, 0, 100, 200); - moveRect(box, 50, 100); + Point center = findCenter(box); + + // rectangles are mutable + + moveRect(box, 50, 100); // now at (50, 100, 100, 200) System.out.println(box); + + box = new Rectangle(0, 0, 100, 200); box.translate(50, 100); + // aliasing revisited + Rectangle box1 = new Rectangle(0, 0, 100, 200); Rectangle box2 = box1; - System.out.println(box2.width); box1.grow(50, 50); - System.out.println(box2.width); + System.out.println(box1); + System.out.println(box2); } /** diff --git a/ch11/Time.java b/ch11/Time.java index 951d5bf..fe5bfd6 100644 --- a/ch11/Time.java +++ b/ch11/Time.java @@ -25,6 +25,30 @@ public Time(int hour, int minute, double second) { this.second = second; } + public int getHour() { + return this.hour; + } + + public int getMinute() { + return this.minute; + } + + public double getSecond() { + return this.second; + } + + public void setHour(int hour) { + this.hour = hour; + } + + public void setMinute(int minute) { + this.minute = minute; + } + + public void setSecond(double second) { + this.second = second; + } + /** * Prints the time in a simple format. */ @@ -48,9 +72,10 @@ public String toString() { * Tests whether two times are equivalent. */ public boolean equals(Time that) { + final double DELTA = 0.001; return this.hour == that.hour && this.minute == that.minute - && this.second == that.second; + && Math.abs(this.second - that.second) < DELTA; } /** @@ -72,6 +97,7 @@ public Time add(Time t2) { sum.hour = this.hour + t2.hour; sum.minute = this.minute + t2.minute; sum.second = this.second + t2.second; + if (sum.second >= 60.0) { sum.second -= 60.0; sum.minute += 1; @@ -80,22 +106,10 @@ public Time add(Time t2) { sum.minute -= 60; sum.hour += 1; } - return sum; - } - - /** - * Adds the given number of seconds to this object (modifier). - */ - public void increment(double seconds) { - this.second += seconds; - while (this.second >= 60.0) { - this.second -= 60.0; - this.minute += 1; - } - while (this.minute >= 60) { - this.minute -= 60; - this.hour += 1; + if (sum.hour >= 24) { + sum.hour -= 24; } + return sum; } } diff --git a/ch15/Cell.java b/ch15/Cell.java index d468b6d..5b6a0f9 100644 --- a/ch15/Cell.java +++ b/ch15/Cell.java @@ -3,6 +3,9 @@ /** * A square at a fixed location that changes color. + * + * @author Chris Mayfield + * @version 7.1.0 */ public class Cell { @@ -40,28 +43,32 @@ public void draw(Graphics g) { } /** - * @return true if the cell is OFF + * Tests whether the cell is off. + * + * @return true if the cell is off */ public boolean isOff() { return state == 0; } /** - * @return true if the cell is ON + * Tests whether the cell is on. + * + * @return true if the cell is on */ public boolean isOn() { return state == 1; } /** - * Sets the cell's state to OFF. + * Sets the cell's state to off. */ public void turnOff() { state = 0; } /** - * Sets the cell's state to ON. + * Sets the cell's state to on. */ public void turnOn() { state = 1; diff --git a/ch15/Conway.java b/ch15/Conway.java index 93faf28..5ac48c6 100644 --- a/ch15/Conway.java +++ b/ch15/Conway.java @@ -2,6 +2,9 @@ /** * Conway's Game of Life. + * + * @author Chris Mayfield + * @version 7.1.0 */ public class Conway { @@ -109,8 +112,6 @@ public void update() { /** * The simulation loop. - * - * @param rate frames per second */ private void mainloop() { while (true) { diff --git a/ch15/GridCanvas.java b/ch15/GridCanvas.java index c936135..3856a57 100644 --- a/ch15/GridCanvas.java +++ b/ch15/GridCanvas.java @@ -3,6 +3,9 @@ /** * 2D array of cells representing a rectangular grid. + * + * @author Chris Mayfield + * @version 7.1.0 */ public class GridCanvas extends Canvas { @@ -33,6 +36,8 @@ public GridCanvas(int rows, int cols, int size) { } /** + * Gets the number of rows. + * * @return number of rows */ public int numRows() { @@ -40,6 +45,8 @@ public int numRows() { } /** + * Gets the number of columns. + * * @return number of columns */ public int numCols() { @@ -47,6 +54,8 @@ public int numCols() { } /** + * Gets the cell at index (r, c). + * * @param r row index * @param c column index * @return the cell diff --git a/user.dict b/user.dict new file mode 100644 index 0000000..11b2406 --- /dev/null +++ b/user.dict @@ -0,0 +1,2 @@ +chris +mayfield