diff --git a/ch01/Goodbye.java b/ch01/Goodbye.java index 2963e2e..05d7b9a 100644 --- a/ch01/Goodbye.java +++ b/ch01/Goodbye.java @@ -1,14 +1,14 @@ -/** - * Example program that demonstrates print vs println. - */ -public class Goodbye { - - /** - * Prints a greeting. - */ - public static void main(String[] args) { - System.out.print("Goodbye, "); // note the space - System.out.println("cruel world"); - } - -} +/** + * Example program that demonstrates print vs println. + */ +public class Goodbye { + + /** + * Prints a greeting. + */ + public static void main(String[] args) { + System.out.print("Goodbye, "); // note the space + System.out.println("cruel world"); + } + +} diff --git a/ch01/Hello.java b/ch01/Hello.java index 593557b..31207ff 100644 --- a/ch01/Hello.java +++ b/ch01/Hello.java @@ -1,8 +1,8 @@ -public class Hello { - - public static void main(String[] args) { - // generate some simple output - System.out.println("Hello, World!"); - } - -} +public class Hello { + + public static void main(String[] args) { + // generate some simple output + System.out.println("Hello, World!"); + } + +} diff --git a/ch01/HelloWorld.java b/ch01/HelloWorld.java new file mode 100644 index 0000000..ba2b85d --- /dev/null +++ b/ch01/HelloWorld.java @@ -0,0 +1,6 @@ +public class HelloWorld{ + public static void main(String[] args){ + System.out.println("Hello World!"); //prints Hello World! + System.out.println("What's up?"); + } +} diff --git a/ch02/Date.java b/ch02/Date.java new file mode 100644 index 0000000..d6ba496 --- /dev/null +++ b/ch02/Date.java @@ -0,0 +1,16 @@ +public class Date{ + public static void main(String[] args){ + String day, month; + int date, year; + day = "Friday"; + month = "October"; + date = 18; + year = 2019; + + System.out.println("American format:"); + System.out.println(day + ", " + month + " " + date + ", " + year); + + System.out.println("European format:"); + System.out.println(day + " " + date + " " + month + " " + year); + } +} \ No newline at end of file diff --git a/ch02/Time.java b/ch02/Time.java new file mode 100644 index 0000000..f328b1c --- /dev/null +++ b/ch02/Time.java @@ -0,0 +1,26 @@ +public class Time{ + public static void main(String[] args){ + int hour, minute, second; + hour = 10; + minute = 45; + second = 30; + + int secSinceMid = second + (minute * 60) + (hour * 60 * 60); + System.out.println(secSinceMid); + + int secRemaining = 86400 - second - (minute * 60) - (hour * 60 * 60); + System.out.println(secRemaining); + + double totalSecInDay = 86400.0; + double secPassed = secSinceMid; + double percentPassed = secPassed / totalSecInDay * 100; + System.out.println(percentPassed); + + hour = 10; + minute = 54; + second = 45; + int newSecSinceMid = second + (minute * 60) + (hour * 60 * 60); + int timeElapsed = newSecSinceMid - secSinceMid; + System.out.println(timeElapsed); + } +} \ No newline at end of file diff --git a/ch02/Variables.java b/ch02/Variables.java index a295abf..d57d90f 100644 --- a/ch02/Variables.java +++ b/ch02/Variables.java @@ -1,83 +1,83 @@ -/** - * Examples from Chapter 2. - */ -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 - - System.out.println(17 * 3); - System.out.println(hour * 60 + minute); - - int percentage; - percentage = (minute * 100) / 60; - - hour = minute + 1; // correct - // minute + 1 = hour; // compiler error - } - -} +/** + * Examples from Chapter 2. + */ +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 + + System.out.println(17 * 3); + System.out.println(hour * 60 + minute); + + int percentage; + percentage = (minute * 100) / 60; + + hour = minute + 1; // correct + // minute + 1 = hour; // compiler error + } + +} diff --git a/ch03/CelsToFahr.java b/ch03/CelsToFahr.java new file mode 100644 index 0000000..c6560bf --- /dev/null +++ b/ch03/CelsToFahr.java @@ -0,0 +1,15 @@ +import java.util.Scanner; + +public class CelsToFahr{ + public static void main(String[] args){ + double tempCels, tempFahr; + final double CELS_RATIO = 9.0 / 5.0; + final double CELS_ADD = 32; + Scanner in = new Scanner(System.in); + + System.out.print("Temperature in Celsius? "); + tempCels = in.nextDouble(); + tempFahr = tempCels * CELS_RATIO + CELS_ADD; + System.out.printf("%.1f C = %.1f F\n", tempCels, tempFahr); + } +} \ No newline at end of file diff --git a/ch03/Convert.java b/ch03/Convert.java index d31fe77..fa4ef4a 100644 --- a/ch03/Convert.java +++ b/ch03/Convert.java @@ -1,27 +1,27 @@ -import java.util.Scanner; - -/** - * Converts centimeters to feet and inches. - */ -public class Convert { - - public static void main(String[] args) { - double cm; - int feet, inches, remainder; - final double CM_PER_INCH = 2.54; - final int IN_PER_FOOT = 12; - Scanner in = new Scanner(System.in); - - // prompt the user and get the value - System.out.print("Exactly how many cm? "); - cm = in.nextDouble(); - - // convert and output the result - inches = (int) (cm / CM_PER_INCH); - feet = inches / IN_PER_FOOT; - remainder = inches % IN_PER_FOOT; - System.out.printf("%.2f cm = %d ft, %d in\n", - cm, feet, remainder); - } - -} +import java.util.Scanner; + +/** + * Converts centimeters to feet and inches. + */ +public class Convert { + + public static void main(String[] args) { + double cm; + int feet, inches, remainder; + final double CM_PER_INCH = 2.54; + final int IN_PER_FOOT = 12; + Scanner in = new Scanner(System.in); + + // prompt the user and get the value + System.out.print("Exactly how many cm? "); + cm = in.nextDouble(); + + // convert and output the result + inches = (int) (cm / CM_PER_INCH); + feet = inches / IN_PER_FOOT; + remainder = inches % IN_PER_FOOT; + System.out.printf("%.2f cm = %d ft, %d in\n", + cm, feet, remainder); + } + +} diff --git a/ch03/Echo.java b/ch03/Echo.java index 500fd9f..07cb0c6 100644 --- a/ch03/Echo.java +++ b/ch03/Echo.java @@ -1,18 +1,18 @@ -import java.util.Scanner; - -public class Echo { - - public static void main(String[] args) { - String line; - Scanner in = new Scanner(System.in); - - System.out.print("Type something: "); - line = in.nextLine(); - System.out.println("You said: " + line); - - System.out.print("Type something else: "); - line = in.nextLine(); - System.out.println("You also said: " + line); - } - -} +import java.util.Scanner; + +public class Echo { + + public static void main(String[] args) { + String line; + Scanner in = new Scanner(System.in); + + System.out.print("Type something: "); + line = in.nextLine(); + System.out.println("You said: " + line); + + System.out.print("Type something else: "); + line = in.nextLine(); + System.out.println("You also said: " + line); + } + +} diff --git a/ch03/GuessStarter.java b/ch03/GuessStarter.java index 64984df..5c9af65 100644 --- a/ch03/GuessStarter.java +++ b/ch03/GuessStarter.java @@ -1,15 +1,25 @@ -import java.util.Random; - -/** - * Starter code for the "Guess My Number" exercise. - */ -public class GuessStarter { - - public static void main(String[] args) { - // pick a random number - Random random = new Random(); - int number = random.nextInt(100) + 1; - System.out.println(number); - } - -} +import java.util.Random; +import java.util.Scanner; + +/** + * Starter code for the "Guess My Number" exercise. + */ +public class GuessStarter { + public static void main(String[] args) { + // read in user input + int userNum; + Scanner in = new Scanner(System.in); + System.out.println("I'm thinking of a number between 1 and 100"); + System.out.println("(including both). Can you guess what it is?"); + System.out.print("Type a number: "); + userNum = in.nextInt(); + System.out.printf("Your guess is: %d\n", userNum); + + // pick a random number + Random random = new Random(); + int number = random.nextInt(100) + 1; + System.out.printf("The number I was thinking of is: %d\n", number); + int diff = Math.abs(number - userNum); + System.out.printf("You were off by: %d\n", diff); + } +} diff --git a/ch03/Input.java b/ch03/Input.java index de97dc0..6086e13 100644 --- a/ch03/Input.java +++ b/ch03/Input.java @@ -1,16 +1,16 @@ -/** - * 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; - } - -} +/** + * 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/ScannerBug.java b/ch03/ScannerBug.java index 353affb..54ca23f 100644 --- a/ch03/ScannerBug.java +++ b/ch03/ScannerBug.java @@ -1,26 +1,26 @@ -import java.util.Scanner; - -/** - * Demonstrates a common problem using Scanner. - */ -public class ScannerBug { - - public static void main(String[] args) { - String name; - int age; - Scanner in = new Scanner(System.in); - - System.out.print("What is your name? "); - name = in.nextLine(); - System.out.print("What is your age? "); - age = in.nextInt(); - System.out.printf("Hello %s, age %d\n", name, age); - - System.out.print("What is your age? "); - age = in.nextInt(); - System.out.print("What is your name? "); - name = in.nextLine(); - System.out.printf("Hello %s, age %d\n", name, age); - } - -} +import java.util.Scanner; + +/** + * Demonstrates a common problem using Scanner. + */ +public class ScannerBug { + + public static void main(String[] args) { + String name; + int age; + Scanner in = new Scanner(System.in); + + System.out.print("What is your name? "); + name = in.nextLine(); + System.out.print("What is your age? "); + age = in.nextInt(); + System.out.printf("Hello %s, age %d\n", name, age); + + System.out.print("What is your age? "); + age = in.nextInt(); + System.out.print("What is your name? "); + name = in.nextLine(); + System.out.printf("Hello %s, age %d\n", name, age); + } + +} diff --git a/ch03/SecondsTo.java b/ch03/SecondsTo.java new file mode 100644 index 0000000..353bd0f --- /dev/null +++ b/ch03/SecondsTo.java @@ -0,0 +1,17 @@ +import java.util.Scanner; + +public class SecondsTo{ + public static void main(String[] args){ + Scanner in = new Scanner(System.in); + int seconds, numHours, numMinutes, numSeconds; + + System.out.print("Number of seconds? "); + seconds = in.nextInt(); + + numHours = seconds / 3600; + numMinutes = seconds % 3600 / 60; + numSeconds = seconds % 3600 % 60; + System.out.printf("%d seconds = %d hours, %d minutes, and %d seconds\n", + seconds, numHours, numMinutes, numSeconds); + } +} \ No newline at end of file diff --git a/ch04/DateParam.java b/ch04/DateParam.java new file mode 100644 index 0000000..5d87a8e --- /dev/null +++ b/ch04/DateParam.java @@ -0,0 +1,24 @@ +public class DateParam{ + public static void printAmerican(String day, String month, int date, int year){ + System.out.println("American format:"); + System.out.println(day + ", " + month + " " + date + ", " + year); + } + + public static void printEuropean(String day, String month, int date, int year){ + System.out.println("European format:"); + System.out.println(day + " " + date + " " + month + " " + year); + } + + public static void main(String[] args){ + String day, month; + int date, year; + day = "Friday"; + month = "October"; + date = 18; + year = 2019; + + printAmerican(day, month, date, year); + + printEuropean(day, month, date, year); + } +} \ No newline at end of file diff --git a/ch04/Exercise.java b/ch04/Exercise.java index ba8c2a9..d4bfcfd 100644 --- a/ch04/Exercise.java +++ b/ch04/Exercise.java @@ -1,25 +1,25 @@ -public class Exercise { - - public static void zoop() { - baffle(); - System.out.print("You wugga "); - baffle(); - } - - public static void main(String[] args) { - System.out.print("No, I "); - zoop(); - System.out.print("I "); - baffle(); - } - - public static void baffle() { - System.out.print("wug"); - ping(); - } - - public static void ping() { - System.out.println("."); - } - -} +public class Exercise { + + public static void zoop() { + baffle(); + System.out.print("You wugga "); + baffle(); + } + + public static void main(String[] args) { + System.out.print("No, I "); + zoop(); + System.out.print("I "); + baffle(); + } + + public static void baffle() { + System.out.print("wug"); + ping(); + } + + public static void ping() { + System.out.println("."); + } + +} diff --git a/ch04/Methods.java b/ch04/Methods.java index 90c1b7a..2b4cd5e 100644 --- a/ch04/Methods.java +++ b/ch04/Methods.java @@ -1,22 +1,22 @@ -/** - * Examples from Chapter 4. - */ -public class Methods { - - public static void main(String[] args) { - double root = Math.sqrt(17.0); - double angle = 1.5; - double height = Math.sin(angle); - - 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); - - 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); - } - -} +/** + * Examples from Chapter 4. + */ +public class Methods { + + public static void main(String[] args) { + double root = Math.sqrt(17.0); + double angle = 1.5; + double height = Math.sin(angle); + + 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); + + 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/NewLine.java b/ch04/NewLine.java index a554e40..987fb80 100644 --- a/ch04/NewLine.java +++ b/ch04/NewLine.java @@ -1,19 +1,19 @@ -public class NewLine { - - public static void newLine() { - System.out.println(); - } - - public static void threeLine() { - newLine(); - newLine(); - newLine(); - } - - public static void main(String[] args) { - System.out.println("First line."); - threeLine(); - System.out.println("Second line."); - } - -} +public class NewLine { + + public static void newLine() { + System.out.println(); + } + + public static void threeLine() { + newLine(); + newLine(); + newLine(); + } + + public static void main(String[] args) { + System.out.println("First line."); + threeLine(); + System.out.println("Second line."); + } + +} diff --git a/ch04/PrintTime.java b/ch04/PrintTime.java index 019d579..1dbb894 100644 --- a/ch04/PrintTime.java +++ b/ch04/PrintTime.java @@ -1,15 +1,15 @@ -public class PrintTime { - - public static void printTime(int hour, int minute) { - System.out.print(hour); - System.out.print(":"); - System.out.println(minute); - } - - public static void main(String[] args) { - int hour = 11; - int minute = 59; - printTime(hour, minute); - } - -} +public class PrintTime { + + public static void printTime(int hour, int minute) { + System.out.print(hour); + System.out.print(":"); + System.out.println(minute); + } + + public static void main(String[] args) { + int hour = 11; + int minute = 59; + printTime(hour, minute); + } + +} diff --git a/ch04/PrintTwice.java b/ch04/PrintTwice.java index 7131085..492f009 100644 --- a/ch04/PrintTwice.java +++ b/ch04/PrintTwice.java @@ -1,12 +1,12 @@ -public class PrintTwice { - - public static void printTwice(String s) { - System.out.println(s); - System.out.println(s); - } - - public static void main(String[] args) { - printTwice("Don't make me say this twice!"); - } - -} +public class PrintTwice { + + public static void printTwice(String s) { + System.out.println(s); + System.out.println(s); + } + + public static void main(String[] args) { + printTwice("Don't make me say this twice!"); + } + +} diff --git a/ch04/Zool.java b/ch04/Zool.java new file mode 100644 index 0000000..78f355a --- /dev/null +++ b/ch04/Zool.java @@ -0,0 +1,9 @@ +public class Zool { + public static void zool(int num, String str1, String str2) { + System.out.printf("%d, %s, %s\n", num, str1, str2); + } + + public static void main(String[] args){ + zool(11, "Gare", "North Star"); + } +} \ No newline at end of file diff --git a/ch05/BottlesOfBeer.java b/ch05/BottlesOfBeer.java new file mode 100644 index 0000000..263d6fd --- /dev/null +++ b/ch05/BottlesOfBeer.java @@ -0,0 +1,53 @@ +/** + * Display entire lyrics of "99 Bottles of Beer" + **/ +import java.util.Scanner; + +public class BottlesOfBeer { + public static void bottlesOfBeer(int n) { + if (n != 0) { + bottlesOfBeer(n - 1); // want to start at (n == 0) case + } + if (n == 0) { // first verse + System.out.println("99 bottles of beer on the wall,"); + System.out.println("99 bottles of beer,"); + System.out.println("ya' take one down, ya' pass it around,"); + System.out.println("98 bottles of beer on the wall."); + } + else if (n == 99) { // last verse + System.out.println("No bottles of beer on the wall,"); + System.out.println("no bottles of beer,"); + System.out.println("ya' can't take one down, ya can't pass it around,"); + System.out.println("'cause there are no more bottles of beer on the wall!"); + } + else if (n > 0) { // middle verses + System.out.printf("%d bottles of beer on the wall,\n", 99 - n); + System.out.printf("%d bottles of beer,\n", 99 - n); + System.out.println("ya' take one down, ya' pass it around,"); + System.out.printf("%d bottles of beer on the wall.\n", 99 - (n + 1)); + } + } + + public static void main(String[] args) { + int n; + Scanner in = new Scanner(System.in); + + System.out.print("How many bottles of beer on the wall? "); + if (!in.hasNextInt()) { // checking if user input is integer + String word = in.next(); + System.err.println(word + " is not an integer."); + return; + } + + n = in.nextInt(); + if (n < 0) { // checking if user input is positive + System.err.printf("%d is not a positive integer.\n", n); + return; + } + else if (n > 99) { // checking if user input is < 100 + System.err.printf("%d is not less than 100.\n", n); + return; + } + bottlesOfBeer(n); // calling recursive method + } +} \ No newline at end of file diff --git a/ch05/Buzz.java b/ch05/Buzz.java index 95e1c2a..350aad8 100644 --- a/ch05/Buzz.java +++ b/ch05/Buzz.java @@ -1,22 +1,22 @@ -public class Buzz { - - public static void baffle(String blimp) { - System.out.println(blimp); - zippo("ping", -5); - } - - public static void zippo(String quince, int flag) { - if (flag < 0) { - System.out.println(quince + " zoop"); - } else { - System.out.println("ik"); - baffle(quince); - System.out.println("boo-wa-ha-ha"); - } - } - - public static void main(String[] args) { - zippo("rattle", 13); - } - -} +public class Buzz { + + public static void baffle(String blimp) { + System.out.println(blimp); + zippo("ping", -5); + } + + public static void zippo(String quince, int flag) { + if (flag < 0) { + System.out.println(quince + " zoop"); + } else { + System.out.println("ik"); + baffle(quince); + System.out.println("boo-wa-ha-ha"); + } + } + + public static void main(String[] args) { + zippo("rattle", 13); + } + +} diff --git a/ch05/CheckFermat.java b/ch05/CheckFermat.java new file mode 100644 index 0000000..b30f7ed --- /dev/null +++ b/ch05/CheckFermat.java @@ -0,0 +1,30 @@ +/** + * checks if Fermat's Last Theorem holds + **/ +import java.util.Scanner; + +public class CheckFermat { + public static void checkFermat(int a, int b, int c, int n) { + boolean fermat = (Math.pow(a, n) + Math.pow(b, n) == Math.pow(c, n)); + if (n > 2 && fermat) { + System.out.println("Holy smokes, Fermat was wrong!"); + } else { + System.out.println("No, that doesn't work."); + } + } + + public static void main(String[] args) { + int a, b, c, n; + Scanner in = new Scanner(System.in); + System.out.println("Testing Fermat's Last Theorem:"); + System.out.print("a? "); + a = in.nextInt(); + System.out.print("b? "); + b = in.nextInt(); + System.out.print("c? "); + c = in.nextInt(); + System.out.print("n? "); + n = in.nextInt(); + checkFermat(a, b, c, n); + } +} \ No newline at end of file diff --git a/ch05/Conditional.java b/ch05/Conditional.java index f2d6d19..85e135a 100644 --- a/ch05/Conditional.java +++ b/ch05/Conditional.java @@ -1,54 +1,54 @@ -/** - * Examples from Chapter 5. - */ -public class Conditional { - - public static void main(String[] args) { - String fruit1 = "Apple"; - String fruit2 = "Orange"; - System.out.println(fruit1.equals(fruit2)); - - 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 zero"); - } else { - if (x > 0) { - System.out.println("x is positive"); - } else { - System.out.println("x is negative"); - } - } - - 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"); - } - } - -} +/** + * Examples from Chapter 5. + */ +public class Conditional { + + public static void main(String[] args) { + String fruit1 = "Apple"; + String fruit2 = "Orange"; + System.out.println(fruit1.equals(fruit2)); + + 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 zero"); + } else { + if (x > 0) { + System.out.println("x is positive"); + } else { + System.out.println("x is negative"); + } + } + + 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/Exercise.java b/ch05/Exercise.java index dbbb6e9..524280d 100644 --- a/ch05/Exercise.java +++ b/ch05/Exercise.java @@ -1,28 +1,28 @@ -public class Exercise { - - public static void zoop(String fred, int bob) { - System.out.println(fred); - if (bob == 5) { - ping("not "); - } else { - System.out.println("!"); - } - } - - public static void main(String[] args) { - int bizz = 5; - int buzz = 2; - zoop("just for", bizz); - clink(2 * buzz); - } - - public static void clink(int fork) { - System.out.print("It's "); - zoop("breakfast ", fork); - } - - public static void ping(String strangStrung) { - System.out.println("any " + strangStrung + "more "); - } - -} +public class Exercise { + + public static void zoop(String fred, int bob) { + System.out.println(fred); + if (bob == 5) { + ping("not "); + } else { + System.out.println("!"); + } + } + + public static void main(String[] args) { + int bizz = 5; + int buzz = 2; + zoop("just for", bizz); + clink(2 * buzz); + } + + public static void clink(int fork) { + System.out.print("It's "); + zoop("breakfast ", fork); + } + + public static void ping(String strangStrung) { + System.out.println("any " + strangStrung + "more "); + } + +} diff --git a/ch05/GuessRecursive.java b/ch05/GuessRecursive.java new file mode 100644 index 0000000..9ccca9b --- /dev/null +++ b/ch05/GuessRecursive.java @@ -0,0 +1,41 @@ +import java.util.Random; +import java.util.Scanner; + +/** + * Guess My Number game with recursive method to guide user to the correct number. + */ + +public class GuessRecursive{ + public static void checkNum(int userNum, int myNum){ //checks if userNum is too high/low + if (myNum > userNum) { + System.out.println("Too low!"); + userNum = getNum(); //if too low, prompts user for another number + checkNum(userNum, myNum); //and then checks that number + } else if (myNum < userNum) { + System.out.println("Too high!"); + userNum = getNum(); //if too high, same as above + checkNum(userNum, myNum); + } else { + System.out.println("You got it!"); //if user is correct, program ends + } + } + + public static int getNum() { //gets user input + int userNum; + Scanner in = new Scanner(System.in); + System.out.print("Type a number: "); + userNum = in.nextInt(); + return userNum; + } + + public static void main(String[] args) { + System.out.println("I'm thinking of a number between 1 and 100"); + System.out.println("(including both). Can you guess what it is?"); + + int userNum = getNum(); + Random random = new Random(); //chooses random number from 1-99 + int myNum = random.nextInt(100) + 1; + + checkNum(userNum, myNum); + } +} \ No newline at end of file diff --git a/ch05/Logarithm.java b/ch05/Logarithm.java index 5c5986a..1a2057b 100644 --- a/ch05/Logarithm.java +++ b/ch05/Logarithm.java @@ -1,44 +1,44 @@ -import java.util.Scanner; - -public class Logarithm { - - public static void main(String[] args) { - System.out.println("printLogarithm"); - printLogarithm(3.0); - - Scanner in = new Scanner(System.in); - - System.out.println("scandouble"); - scanDouble(in); - - System.out.println("scandouble2"); - scanDouble2(in); - } - - public static void printLogarithm(double x) { - if (x <= 0.0) { - System.err.println("Error: x must be positive."); - return; - } - double result = Math.log(x); - System.out.println("The log of x is " + result); - } - - public static void scanDouble(Scanner in) { - System.out.print("Enter a number: "); - double x = in.nextDouble(); - printLogarithm(x); - } - - public static void scanDouble2(Scanner in) { - System.out.print("Enter a number: "); - if (!in.hasNextDouble()) { - String word = in.next(); - System.err.println(word + " is not a number"); - return; - } - double x = in.nextDouble(); - printLogarithm(x); - } - -} +import java.util.Scanner; + +public class Logarithm { + + public static void main(String[] args) { + System.out.println("printLogarithm"); + printLogarithm(3.0); + + Scanner in = new Scanner(System.in); + + System.out.println("scandouble"); + scanDouble(in); + + System.out.println("scandouble2"); + scanDouble2(in); + } + + public static void printLogarithm(double x) { + if (x <= 0.0) { + System.err.println("Error: x must be positive."); + return; + } + double result = Math.log(x); + System.out.println("The log of x is " + result); + } + + public static void scanDouble(Scanner in) { + System.out.print("Enter a number: "); + double x = in.nextDouble(); + printLogarithm(x); + } + + public static void scanDouble2(Scanner in) { + System.out.print("Enter a number: "); + if (!in.hasNextDouble()) { + String word = in.next(); + System.err.println(word + " is not a number"); + return; + } + double x = in.nextDouble(); + printLogarithm(x); + } + +} diff --git a/ch05/Recursion.java b/ch05/Recursion.java index 0e772c8..4c83dc4 100644 --- a/ch05/Recursion.java +++ b/ch05/Recursion.java @@ -1,71 +1,71 @@ -public class Recursion { - - public static void main(String[] args) { - System.out.println("countdown"); - countdown(3); - - System.out.println("countup"); - countup(3); - - System.out.println("newLine"); - newLine(); - - System.out.println("nLines"); - nLines(3); - - System.out.println("threeLine"); - threeLine(); - - System.out.println("displayBinary"); - displayBinary(23); - System.out.println(); - } - - public static void countdown(int n) { - if (n == 0) { - System.out.println("Blastoff!"); - } else { - System.out.println(n); - countdown(n - 1); - } - } - - public static void newLine() { - System.out.println(); - } - - public static void threeLine() { - newLine(); - newLine(); - newLine(); - } - - public static void nLines(int n) { - if (n > 0) { - System.out.println(); - nLines(n - 1); - } - } - - public static void forever(String s) { - System.out.println(s); - forever(s); - } - - public static void countup(int n) { - if (n == 0) { - System.out.println("Blastoff!"); - } else { - countup(n - 1); - System.out.println(n); - } - } - - public static void displayBinary(int value) { - if (value > 0) { - displayBinary(value / 2); - System.out.print(value % 2); - } - } - -} +public class Recursion { + + public static void main(String[] args) { + System.out.println("countdown"); + countdown(3); + + System.out.println("countup"); + countup(3); + + System.out.println("newLine"); + newLine(); + + System.out.println("nLines"); + nLines(3); + + System.out.println("threeLine"); + threeLine(); + + System.out.println("displayBinary"); + displayBinary(23); + System.out.println(); + } + + public static void countdown(int n) { + if (n == 0) { + System.out.println("Blastoff!"); + } else { + System.out.println(n); + countdown(n - 1); + } + } + + public static void newLine() { + System.out.println(); + } + + public static void threeLine() { + newLine(); + newLine(); + newLine(); + } + + public static void nLines(int n) { + if (n > 0) { + System.out.println(); + nLines(n - 1); + } + } + + public static void forever(String s) { + System.out.println(s); + forever(s); + } + + public static void countup(int n) { + if (n == 0) { + System.out.println("Blastoff!"); + } else { + countup(n - 1); + System.out.println(n); + } + } + + public static void displayBinary(int value) { + if (value > 0) { + displayBinary(value / 2); + System.out.print(value % 2); + } + } + +} diff --git a/ch06/Ack.java b/ch06/Ack.java new file mode 100644 index 0000000..1885615 --- /dev/null +++ b/ch06/Ack.java @@ -0,0 +1,57 @@ +import java.util.Scanner; + +/** + * calculates Ackermann function for two user given integers: m, n + */ + +public class Ack { + + /** + * Ackermann function in Java method ack + * @param takes two integers m, n + * @return result of Ackermann function + */ + public static int ack(int m, int n) { + if (m == 0) { + return n + 1; + } else if (m > 0 && n == 0) { + return ack(m - 1, 1); + } else if (m > 0 && n > 0) { + return ack(m - 1, ack(m, n - 1)); + } + return 0; + } + + public static void main(String[] args) { + int m, n, returnVal; + Scanner in = new Scanner(System.in); + + System.out.println("Ackermann function: need two nonnegative integers m and n."); + System.out.print("m? "); + if (!in.hasNextInt()) { //checks if user input is integer + String wrong = in.next(); + System.err.printf("%s is not an integer. UNACCEPTABLE!\n", wrong); + return; + } + m = in.nextInt(); + if (m < 0) { //checks if user input is nonnegative + System.err.printf("%d is negative. UNACCEPTABLE!\n", m); + return; + } + + System.out.print("n? "); + if (!in.hasNextInt()) { //checks if user input is integer + String wrong = in.next(); + System.err.printf("%s is not an integer. UNACCEPTABLE!\n", wrong); + return; + } + n = in.nextInt(); + if (n < 0) { //checks if user input is nonnegative + System.err.printf("%d is negative. UNACCEPTABLE!\n", m); + return; + } + + returnVal = ack(m, n); + System.out.println(returnVal); + } +} \ No newline at end of file diff --git a/ch06/Exercise.java b/ch06/Exercise.java index b826b44..c12e772 100644 --- a/ch06/Exercise.java +++ b/ch06/Exercise.java @@ -1,36 +1,36 @@ -public class Exercise { - - public static void main(String[] args) { - boolean flag1 = isHoopy(202); - boolean flag2 = isFrabjuous(202); - System.out.println(flag1); - System.out.println(flag2); - if (flag1 && flag2) { - System.out.println("ping!"); - } - if (flag1 || flag2) { - System.out.println("pong!"); - } - } - - public static boolean isHoopy(int x) { - boolean hoopyFlag; - if (x % 2 == 0) { - hoopyFlag = true; - } else { - hoopyFlag = false; - } - return hoopyFlag; - } - - public static boolean isFrabjuous(int x) { - boolean frabjuousFlag; - if (x > 0) { - frabjuousFlag = true; - } else { - frabjuousFlag = false; - } - return frabjuousFlag; - } - -} +public class Exercise { + + public static void main(String[] args) { + boolean flag1 = isHoopy(202); + boolean flag2 = isFrabjuous(202); + System.out.println(flag1); + System.out.println(flag2); + if (flag1 && flag2) { + System.out.println("ping!"); + } + if (flag1 || flag2) { + System.out.println("pong!"); + } + } + + public static boolean isHoopy(int x) { + boolean hoopyFlag; + if (x % 2 == 0) { + hoopyFlag = true; + } else { + hoopyFlag = false; + } + return hoopyFlag; + } + + public static boolean isFrabjuous(int x) { + boolean frabjuousFlag; + if (x > 0) { + frabjuousFlag = true; + } else { + frabjuousFlag = false; + } + return frabjuousFlag; + } + +} diff --git a/ch06/IsDivisible.java b/ch06/IsDivisible.java new file mode 100644 index 0000000..723f83b --- /dev/null +++ b/ch06/IsDivisible.java @@ -0,0 +1,41 @@ +/** + * takes two integers and returns true if they're divisible, false if not + */ +import java.util.Scanner; + +public class IsDivisible { + /** + * checks if two integers are divisible + * @param n integer, check if divisible by m + * @param m integer + * @return true if n is divisible by m, false otherwise + */ + public static boolean isDivisible(int n, int m) { + return (n % m == 0); + } + + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + + System.out.println("Check if integer n is divisible by integer m."); + System.out.print("n? "); + if (!in.hasNextInt()) { //check if user input is int + String notInt = in.next(); + System.err.printf("%s is not an integer.\n", notInt); + return; + } + int n = in.nextInt(); + System.out.print("m? "); //check if user input is int + if (!in.hasNextInt()) { + String notInt = in.next(); + System.err.printf("%s is not an integer.\n", notInt); + return; + } + int m = in.nextInt(); + + boolean value = isDivisible(n, m); + System.out.println(value); //prints return boolean from method isDivisible + } +} + + \ No newline at end of file diff --git a/ch06/IsTriangle.java b/ch06/IsTriangle.java new file mode 100644 index 0000000..4e93440 --- /dev/null +++ b/ch06/IsTriangle.java @@ -0,0 +1,67 @@ +import java.util.Scanner; + +/** + * takes three integers, checks if you can form a triangle from sticks with given lengths + */ + +public class IsTriangle { + /** + * checks if any side is greater than the sum of the other two sides + * @param takes three integers a, b, c + * @return false if any side is greater than the sum of the other two sides, else true + */ + public static boolean isTriangle(int a, int b, int c) { + if (a > (b + c)) { + return false; + } else if (b > (a + c)) { + return false; + } else if (c > (a + b)) { + return false; + } else { + return true; + } + } + + /** + * checks if user input is an integer + * @param uses Scanner to check user input + * @return false if user input is not an integer, else true + */ + + public static boolean checkInt(Scanner in) { + if (!in.hasNextInt()) { + String value = in.next(); + System.err.printf("%s is not an integer.\n", value); + return false; + } + return true; + } + + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + int a, b, c; + + System.out.println("Can we form a triangle with lengths a, b, c?"); + + System.out.print("a? "); + if (!checkInt(in)) { //if a is not an integer, return and exit main + return; + } + a = in.nextInt(); + + System.out.print("b? "); + if (!checkInt(in)) { //same as above for b + return; + } + b = in.nextInt(); + + System.out.print("c? "); + if (!checkInt(in)) { //same as above for c + return; + } + c = in.nextInt(); + + boolean value = isTriangle(a, b, c); //tests if a, b, c can form triangle + System.out.println(value); //prints return boolean + } +} \ No newline at end of file diff --git a/ch06/Multadd.java b/ch06/Multadd.java new file mode 100644 index 0000000..7632774 --- /dev/null +++ b/ch06/Multadd.java @@ -0,0 +1,73 @@ +import java.util.Scanner; + +/** + * perform complex arithmetic with functional decomposition + */ +public class Multadd { + + /** + * @param takes three doubles a, b, c + * @return multadd + */ + public static double multadd(double a, double b, double c) { + return (a * b + c); + } + + /** + * @param double x + * @return complex arithemtic with e and square root + */ + public static double expSum(double x) { + double a, b, c; + a = x; + b = Math.exp(-x); + c = Math.sqrt(1 - b); + return multadd(a, b, c); + } + +// public static boolean checkDouble(Scanner in) { +// if (!in.hasNextDouble()) { +// String value = in.next(); +// System.err.printf("%s is not a double.\n", value); +// return false; +// } +// return true; +// } + + public static void main(String[] args) { + double a, b, c, a1, b1, c1, a2, b2, c2, x; +// Scanner in = new Scanner(System.in); +// System.out.print("a? "); +// if (!checkDouble(in)) { +// return; +// } +// a = in.nextDouble(); +// +// System.out.print("b? "); +// if(!checkDouble(in)) { +// return; +// } +// b = in.nextDouble(); +// +// System.out.print("c? "); +// if(!checkDouble(in)) { +// return; +// } +// c = in.nextDouble(); + a = 1.0; + b = 2.0; + c = 3.0; + double value = multadd(a, b, c); //simple example of multadd + a1 = 0.5; + b1 = Math.cos(Math.PI / 4); + c1 = Math.sin(Math.PI / 4); + double value1 = multadd(a1, b1, c1); //advanced-er example of multadd + a2 = 2.0; + b2 = Math.log(10); + c2 = Math.log(2); + double value2 = multadd(a2, b2, c2); //advanced-est example of multadd + x = 1.0; + double value3 = expSum(x); //example of expSum + System.out.println(value + " " + value1 + " " + value2 + " " + value3); + } +} \ No newline at end of file diff --git a/ch06/OddSum.java b/ch06/OddSum.java new file mode 100644 index 0000000..58a1f77 --- /dev/null +++ b/ch06/OddSum.java @@ -0,0 +1,40 @@ +import java.util.Scanner; + +/** + * calculates sum of odd integers from 1 to n, with n being a user given odd positive integer + */ +public class OddSum { + + /** + * recursively finds sum of odd integers from 1 to n + * @param int n determines when to stop adding + * @return returns sum + */ + public static int oddSum(int n) { + if (n == 1) { + return 1; + } else { + return oddSum(n - 2) + n; + } + } + + public static void main(String[] args) { + int n, value; + Scanner in = new Scanner(System.in); + System.out.println("Give me a positive odd integer n and I'll give you the sum of odd integers from 1 to n."); + System.out.print("n? "); + if (!in.hasNextInt()) { //checks if user input is int + String wrong = in.next(); + System.err.printf("%s is not an integer.\n", wrong); + return; + } + n = in.nextInt(); + if (n <= 0 || n % 2 == 0) { //checks if user input is positive and odd + System.err.println("This integer is either negative or even."); + return; + } + value = oddSum(n); + System.out.println(value); + } +} + \ No newline at end of file diff --git a/ch06/Power.java b/ch06/Power.java new file mode 100644 index 0000000..2d1d1c7 --- /dev/null +++ b/ch06/Power.java @@ -0,0 +1,50 @@ +import java.util.Scanner; +/** + * calculate x to the power of n + */ + +public class Power { + /** + * calculates x to the power of n + * @param double x to the power of nonnegative integer n + * @return x to the power of n + */ + public static double power(double x, int n) { + if (n == 0) { + return 1.0; //any number to the power of 0 is 1 + } else if (n % 2 == 0) { + return power(x, n / 2) * power(x, n / 2); //more effecient if n is even + } else { + return x * power(x, n - 1); + } + } + + public static void main(String[] args) { + double x, result; + int n; + Scanner in = new Scanner(System.in); + System.out.println("Calculate x to the power of n."); + System.out.print("x? "); + if(!in.hasNextDouble()) { //checks if x is a double + String wrong = in.next(); + System.err.printf("%s is not a double. UNACCEPTABLE!\n", wrong); + return; + } + x = in.nextDouble(); + + System.out.print("n? "); + if(!in.hasNextInt()) { //checks if n is an integer + String wrong = in.next(); + System.err.printf("%s is not an integer. UNACCEPTABLE!\n", wrong); + return; + } + n = in.nextInt(); + if (n < 0) { //checks if n is nonnegative + System.err.println("n is negative. UNACCEPTABLE!"); + return; + } + + result = power(x, n); + System.out.println(result); + } +} \ No newline at end of file diff --git a/ch06/Recursive.java b/ch06/Recursive.java index f045844..43d2c14 100644 --- a/ch06/Recursive.java +++ b/ch06/Recursive.java @@ -1,17 +1,17 @@ -public class Recursive { - - public static void main(String[] args) { - System.out.println(prod(1, 4)); - } - - public static int prod(int m, int n) { - if (m == n) { - return n; - } else { - int recurse = prod(m, n - 1); - int result = n * recurse; - return result; - } - } - -} +public class Recursive { + + public static void main(String[] args) { + System.out.println(prod(1, 4)); + } + + public static int prod(int m, int n) { + if (m == n) { + return n; + } else { +// int recurse = prod(m, n - 1); +// int result = n * recurse; + return n * prod(m, n - 1); + } + } + +} diff --git a/ch06/Series.java b/ch06/Series.java index 10d2b41..0d7f231 100644 --- a/ch06/Series.java +++ b/ch06/Series.java @@ -1,150 +1,150 @@ -/** - * Examples from Chapter 6. - */ -public class Series { - - public static void countup(int n) { - if (n == 0) { - System.out.println("Blastoff!"); - } else { - countup(n - 1); - System.out.println(n); - } - } - - 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 absoluteValue(double x) { - if (x < 0) { - return -x; - } else { - return x; - } - } - - 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)); - } - - /** - * Tests whether x is a single digit integer. - * - * @param x the integer to test - * @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 int factorial(int n) { - if (n == 0) { - return 1; - } - int recurse = factorial(n - 1); - int result = n * recurse; - return result; - } - - public static int fibonacci(int n) { - if (n == 1 || n == 2) { - return 1; - } - return fibonacci(n - 1) + fibonacci(n - 2); - } - - public static void main(String[] args) { - countup(3); - System.out.println("Have a nice day."); - - System.out.println("calculateArea"); - System.out.println(calculateArea(3.0)); - - System.out.println("calculateArea2"); - System.out.println(calculateArea2(3.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)); - - System.out.println("absolute value"); - System.out.println(absoluteValue(-2)); - - 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(isSingleDigit(2)); - boolean bigFlag = !isSingleDigit2(17); - - int z = 9; - if (isSingleDigit(z)) { - System.out.println("z is small"); - } else { - System.out.println("z is big"); - } - - System.out.println("factorial"); - System.out.println(factorial(3)); - - System.out.println("fibonacci"); - System.out.println(fibonacci(3)); - } - -} +/** + * Examples from Chapter 6. + */ +public class Series { + + public static void countup(int n) { + if (n == 0) { + System.out.println("Blastoff!"); + } else { + countup(n - 1); + System.out.println(n); + } + } + + 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 absoluteValue(double x) { + if (x < 0) { + return -x; + } else { + return x; + } + } + + 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)); + } + + /** + * Tests whether x is a single digit integer. + * + * @param x the integer to test + * @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 int factorial(int n) { + if (n == 0) { + return 1; + } + int recurse = factorial(n - 1); + int result = n * recurse; + return result; + } + + public static int fibonacci(int n) { + if (n == 1 || n == 2) { + return 1; + } + return fibonacci(n - 1) + fibonacci(n - 2); + } + + public static void main(String[] args) { + countup(3); + System.out.println("Have a nice day."); + + System.out.println("calculateArea"); + System.out.println(calculateArea(3.0)); + + System.out.println("calculateArea2"); + System.out.println(calculateArea2(3.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)); + + System.out.println("absolute value"); + System.out.println(absoluteValue(-2)); + + 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(isSingleDigit(2)); + boolean bigFlag = !isSingleDigit2(17); + + int z = 9; + if (isSingleDigit(z)) { + System.out.println("z is small"); + } else { + System.out.println("z is big"); + } + + System.out.println("factorial"); + System.out.println(factorial(3)); + + System.out.println("fibonacci"); + System.out.println(fibonacci(3)); + } + +} diff --git a/ch06/TestLegal.java b/ch06/TestLegal.java new file mode 100644 index 0000000..6aead29 --- /dev/null +++ b/ch06/TestLegal.java @@ -0,0 +1,13 @@ +/** + * testing what is legal by asking the compiler and seeing what exceptions are thrown + */ +public class TestLegal { + public static int returnTwo() { + return 2; + } + + public static void main(String[] args) { + returnTwo(); //nothing happens with this value + //System.out.println("Boo!") + 7; //error: not a statement + } +} \ No newline at end of file diff --git a/ch07/Exercise.java b/ch07/Exercise.java index 6c7b3df..46c8d12 100644 --- a/ch07/Exercise.java +++ b/ch07/Exercise.java @@ -1,19 +1,19 @@ -public class Exercise { - - public static void main(String[] args) { - loop(10); - } - - public static void loop(int n) { - int i = n; - while (i > 1) { - System.out.println(i); - if (i % 2 == 0) { - i = i / 2; - } else { - i = i + 1; - } - } - } - -} +public class Exercise { + + public static void main(String[] args) { + loop(10); + } + + public static void loop(int n) { + int i = n; + while (i > 1) { + System.out.println(i); + if (i % 2 == 0) { + i = i / 2; + } else { + i = i + 1; + } + } + } + +} diff --git a/ch07/FactorialIter.java b/ch07/FactorialIter.java new file mode 100644 index 0000000..64dc49c --- /dev/null +++ b/ch07/FactorialIter.java @@ -0,0 +1,22 @@ +/** + * iterative method of calculating factorial + */ +public class FactorialIter { + + public static void main(String[] args) { + System.out.println(prod(3)); + } + + /** + * calculates x * 1 * 2 * ... * (x - 1) = x! + * @param calculates factorial of integer x + * @return x! + */ + public static int prod(int x) { + int result = x; + for (int i = 1; i < x; i++) { + result = result * i; + } + return result; + } +} diff --git a/ch07/Gauss.java b/ch07/Gauss.java new file mode 100644 index 0000000..8447c8e --- /dev/null +++ b/ch07/Gauss.java @@ -0,0 +1,58 @@ +import java.util.Scanner; + +/** + * evaluate exp(-x^2) using infinite series expansion: + * e(-x^2) = 1 - x^2 + (x^4)/2! - (x^6)/3! + ... + ((-1)^i * x^(2i))/i! + */ +public class Gauss { + + /** + * evaluate exp(-x^2) using iterative method to sum first n terms of infinite series expansion + * @param double x for exp(-x^2) + * @param sum of first n terms of infinite series expansion + * @return estimate of exp(-x^2) using infinite series expansion + */ + public static double gauss(double x, int n) { + double sum = 1.0; + double result1 = 1.0; + double result2 = 1.0; + for (int i = 1; i <= n; i++) { + result2 = (result1 * (-1) * x * x) / i; + sum = sum + result2; + result1 = result2; + } + return sum; + } + + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + double x, result; + int n; + + System.out.println("Estimate e(-x^2) with infinite series expansion."); + System.out.print("x? "); + while (!in.hasNextDouble()) { //check if user input is double + String wrong = in.next(); + System.out.printf("%s is not a double. Try again!\n", wrong); + System.out.print("x? "); + } + x = in.nextDouble(); + + System.out.println("Estimate e(-x^2) with n number of terms from the infinite series expansion."); + System.out.print("n? "); + while (!in.hasNextInt()) { //check if user input is int + String wrong = in.next(); + System.out.printf("%s is not an integer. Try again!\n", wrong); + System.out.print("n? "); + } + n = in.nextInt(); + + if (n < 0) { //check if n is nonnegative + System.out.println("n can not be negative."); + return; + } + + result = gauss(x, n); + System.out.println(result); + } +} \ No newline at end of file diff --git a/ch07/Loops.java b/ch07/Loops.java index dfc03ce..8a51ef8 100644 --- a/ch07/Loops.java +++ b/ch07/Loops.java @@ -1,33 +1,33 @@ -/** - * Examples from Chapter 7. - */ -public class Loops { - - public static void countdown(int n) { - while (n > 0) { - System.out.println(n); - n = n - 1; - } - System.out.println("Blastoff!"); - } - - public static void sequence(int n) { - while (n != 1) { - System.out.println(n); - if (n % 2 == 0) { // n is even - n = n / 2; - } else { // n is odd - n = n * 3 + 1; - } - } - } - - public static void main(String[] args) { - System.out.println("countdown"); - countdown(3); - - System.out.println("sequence"); - sequence(10); - } - -} +/** + * Examples from Chapter 7. + */ +public class Loops { + + public static void countdown(int n) { + while (n > 0) { + System.out.println(n); + n = n - 1; + } + System.out.println("Blastoff!"); + } + + public static void sequence(int n) { + while (n != 1) { + System.out.println(n); + if (n % 2 == 0) { // n is even + n = n / 2; + } else { // n is odd + n = n * 3 + 1; + } + } + } + + public static void main(String[] args) { + System.out.println("countdown"); + countdown(3); + + System.out.println("sequence"); + sequence(10); + } + +} diff --git a/ch07/MyExp.java b/ch07/MyExp.java new file mode 100644 index 0000000..3d0a431 --- /dev/null +++ b/ch07/MyExp.java @@ -0,0 +1,82 @@ +/** + * estimating e^x using infinite series expansion + */ +public class MyExp { + + /** + * calculates x * 1 * 2 * ... * (x - 1) = x! + * @param calculates factorial of integer x + * @return x! + */ + public static int factorial(int x) { + int result = x; + for (int i = 1; i < x; i++) { + result = result * i; + } + return result; + } + + /** + * less efficient way to estimate e^x + * @param double x for e^x + * @param estimate e^x with n number of terms in the expansion + * @return estimated e^x + */ + public static double myexp(double x, int n) { + double result = 1.0; + for (int i = 1; i < n; i++) { + result = result + (Math.pow(x, i) / factorial(i)); + } + return result; + } + + /** + * more efficient way to estimate e^x, gets rid of factorial and Math.pow usage + * relies purely on iterative method + * @param double x for e^x + * @param n number of terms in infinite series expansion + * @return sum of all n terms in infinite series expansion, should estimate e^x + */ + public static double myexpeff(double x, int n) { + double result1 = 1.0; + double result2 = 0.0; + double sum = 1.0; + for (int i = 1; i < n; i++) { + result2 = result1 * (x / i); + sum = sum + result2; + result1 = result2; + } + return sum; + } + + /** + * prints x, e^x as determined by myexpeff, e^x as determined by Math.exp + * for myexpeff, sums first 20 terms in infinite series expansion + * @param double x for e^x + */ + public static void check(double x) { + int n = 20; + double result1 = myexpeff(x, n); + double result2 = Math.exp(x); + System.out.println(x + "\t" + result1 + "\t" + result2); + } + + /** + * note that as |x| grows larger, the result from myexpeff gets more inaccurate + * the results from myexpeff and Math.pow have fewer and fewer digits in common + */ + public static void main(String[] args) { + double x1 = 0.1; + double x2 = -0.1; + + while (x1 <= 100) { //shows results for 0.1, 1, 10, 100 + check(x1); + x1 = x1 * 10; + } + + while(x2 >= -100) { //shows results for -0.1, -1, -10, -100 + check(x2); + x2 = x2 * 10; + } + } +} \ No newline at end of file diff --git a/ch07/PowerIter.java b/ch07/PowerIter.java new file mode 100644 index 0000000..c0bafa3 --- /dev/null +++ b/ch07/PowerIter.java @@ -0,0 +1,51 @@ +import java.util.Scanner; +/** + * calculate x to the power of n using iterative method + */ + +public class PowerIter { + /** + * calculates x to the power of n + * @param double x to the power of nonnegative integer n + * @return x to the power of n + */ + public static double power(double x, int n) { + double result = 1.0; + int i = 1; + while (i <= n) { + result = result * x; + i++; + } + return result; + } + + public static void main(String[] args) { + double x, result; + int n; + Scanner in = new Scanner(System.in); + System.out.println("Calculate x to the power of n."); + System.out.print("x? "); + while (!in.hasNextDouble()) { //checks if x is a double + String wrong = in.next(); + System.err.printf("%s is not a double. UNACCEPTABLE!\n", wrong); + System.out.print("x? "); + } + x = in.nextDouble(); + + System.out.print("n? "); + while(!in.hasNextInt()) { //checks if n is an int + String wrong = in.next(); + System.err.printf("%s is not an integer. UNACCEPTABLE!\n", wrong); + System.out.print("n? "); + } + n = in.nextInt(); + + if (n < 0) { //checks if n is nonnegative + System.err.println("n is negative. UNACCEPTABLE!"); + return; + } + + result = power(x, n); + System.out.println(result); + } +} \ No newline at end of file diff --git a/ch07/SquareRoot.java b/ch07/SquareRoot.java new file mode 100644 index 0000000..d473901 --- /dev/null +++ b/ch07/SquareRoot.java @@ -0,0 +1,59 @@ +import java.util.Scanner; + +/** + * approximates square root of a double using iterative arithmetic + */ +public class SquareRoot { + + /** + * approximates square root of double by using iterative arithmetic + * until difference between last two iterations < 0.001 + * @param approximates square root of a + * @return last iteration + */ + public static double squareRoot(double a) { + double init = a / 2.0; //initial guess is a/2 + double guess1 = approxRoot(a, init); + double guess2 = 0.0; + double difference = 1.0; + + while (difference >= 0.0001) { + guess2 = approxRoot(a, guess1); + difference = diff(guess1, guess2); + guess1 = guess2; + } + + return guess2; + } + + /** + * the formula used to approximate square root + */ + public static double approxRoot(double a, double b) { + return (b + (a / b)) / 2.0; + } + + /** + * calculate difference between a and b + */ + public static double diff(double a, double b) { + return Math.abs(a - b); + } + + public static void main(String[] args) { + double a, result; + Scanner in = new Scanner(System.in); + + System.out.println("Approximate square root of double a."); + System.out.print("a? "); + while (!in.hasNextDouble()) { //iterate until user inputs double + String wrong = in.next(); + System.err.printf("%s is not a double.\n", wrong); + System.out.print("a? "); + } + a = in.nextDouble(); + + result = squareRoot(a); + System.out.println(result); + } +} \ No newline at end of file diff --git a/ch07/Tables.java b/ch07/Tables.java index 3e33905..f779418 100644 --- a/ch07/Tables.java +++ b/ch07/Tables.java @@ -1,157 +1,157 @@ -/** - * Generating tables; encapsulation and generalization. - */ -public class Tables { - - public static void example() { - int i = 1; - while (i < 10) { - double x = i; - System.out.println(x + " " + Math.log(x)); - i = i + 1; - } - } - - public static void example2() { - int i = 1; - while (i < 10) { - double x = i; - System.out.println(x + " " + Math.log(x) / Math.log(2)); - i = i + 1; - } - } - - public static void example3() { - final double LOG2 = Math.log(2); - int i = 1; - while (i < 100) { - double x = i; - System.out.println(x + " " + Math.log(x) / LOG2); - i = i * 2; - } - } - - public static void example4() { - int i = 1; - while (i <= 6) { - System.out.printf("%4d", 2 * i); - i = i + 1; - } - System.out.println(); - } - - public static void printRow() { - int i = 1; - while (i <= 6) { - System.out.printf("%4d", 2 * i); - i = i + 1; - } - System.out.println(); - } - - public static void printRow2(int n) { - int i = 1; - while (i <= 6) { - System.out.printf("%4d", n * i); - i = i + 1; - } - System.out.println(); - } - - public static void example5() { - int i = 1; - while (i <= 6) { - printRow2(i); - i = i + 1; - } - } - - public static void printTable() { - int i = 1; - while (i <= 6) { - printRow2(i); - i = i + 1; - } - } - - public static void printTable2(int rows) { - int i = 1; - while (i <= rows) { - printRow2(i); - i = i + 1; - } - } - - public static void printRow3(int n, int cols) { - int i = 1; - while (i <= cols) { - System.out.printf("%4d", n * i); - i = i + 1; - } - System.out.println(); - } - - public static void printTable3(int rows) { - int i = 1; - while (i <= rows) { - printRow3(i, rows); - i = i + 1; - } - } - - public static void printTable4(int rows) { - for (int i = 1; i <= rows; i = i + 1) { - printRow3(i, rows); - } - } - - public static void printRow4(int n, int cols) { - int i; - for (i = 1; i <= cols; i = i + 1) { - System.out.printf("%4d", n * i); - } - System.out.println(i); - } - - public static void main(String[] args) { - System.out.println("example"); - example(); - - System.out.println("example2"); - example2(); - - System.out.println("example3"); - example3(); - - System.out.println("example4"); - example4(); - - System.out.println("example5"); - example5(); - - System.out.println("printRow"); - printRow(); - - System.out.println("printRow2"); - printRow2(6); - - System.out.println("printTable"); - printTable(); - - System.out.println("printTable2"); - printTable2(6); - - System.out.println("printRow3"); - printRow3(6, 6); - - System.out.println("printTable3"); - printTable3(6); - - System.out.println("printRow4"); - printRow4(6, 6); - - System.out.println("printTable4"); - printTable4(6); - } - -} +/** + * Generating tables; encapsulation and generalization. + */ +public class Tables { + + public static void example() { + int i = 1; + while (i < 10) { + double x = i; + System.out.println(x + " " + Math.log(x)); + i = i + 1; + } + } + + public static void example2() { + int i = 1; + while (i < 10) { + double x = i; + System.out.println(x + " " + Math.log(x) / Math.log(2)); + i = i + 1; + } + } + + public static void example3() { + final double LOG2 = Math.log(2); + int i = 1; + while (i < 100) { + double x = i; + System.out.println(x + " " + Math.log(x) / LOG2); + i = i * 2; + } + } + + public static void example4() { + int i = 1; + while (i <= 6) { + System.out.printf("%4d", 2 * i); + i = i + 1; + } + System.out.println(); + } + + public static void printRow() { + int i = 1; + while (i <= 6) { + System.out.printf("%4d", 2 * i); + i = i + 1; + } + System.out.println(); + } + + public static void printRow2(int n) { + int i = 1; + while (i <= 6) { + System.out.printf("%4d", n * i); + i = i + 1; + } + System.out.println(); + } + + public static void example5() { + int i = 1; + while (i <= 6) { + printRow2(i); + i = i + 1; + } + } + + public static void printTable() { + int i = 1; + while (i <= 6) { + printRow2(i); + i = i + 1; + } + } + + public static void printTable2(int rows) { + int i = 1; + while (i <= rows) { + printRow2(i); + i = i + 1; + } + } + + public static void printRow3(int n, int cols) { + int i = 1; + while (i <= cols) { + System.out.printf("%4d", n * i); + i = i + 1; + } + System.out.println(); + } + + public static void printTable3(int rows) { + int i = 1; + while (i <= rows) { + printRow3(i, rows); + i = i + 1; + } + } + + public static void printTable4(int rows) { + for (int i = 1; i <= rows; i = i + 1) { + printRow3(i, rows); + } + } + + public static void printRow4(int n, int cols) { + int i; + for (i = 1; i <= cols; i = i + 1) { + System.out.printf("%4d", n * i); + } + System.out.println(i); + } + + public static void main(String[] args) { + System.out.println("example"); + example(); + + System.out.println("example2"); + example2(); + + System.out.println("example3"); + example3(); + + System.out.println("example4"); + example4(); + + System.out.println("example5"); + example5(); + + System.out.println("printRow"); + printRow(); + + System.out.println("printRow2"); + printRow2(6); + + System.out.println("printTable"); + printTable(); + + System.out.println("printTable2"); + printTable2(6); + + System.out.println("printRow3"); + printRow3(6, 6); + + System.out.println("printTable3"); + printTable3(6); + + System.out.println("printRow4"); + printRow4(6, 6); + + System.out.println("printTable4"); + printTable4(6); + } + +} diff --git a/ch07/Validate.java b/ch07/Validate.java index e825705..7527ddc 100644 --- a/ch07/Validate.java +++ b/ch07/Validate.java @@ -1,54 +1,54 @@ -import java.util.Scanner; - -/** - * Do-while, break, and continue. - */ -public class Validate { - - public static double scanDouble() { - Scanner in = new Scanner(System.in); - boolean okay; - do { - System.out.print("Enter a number: "); - if (in.hasNextDouble()) { - okay = true; - } else { - okay = false; - String word = in.next(); - System.err.println(word + " is not a number"); - } - } while (!okay); - double x = in.nextDouble(); - return x; - } - - public static double scanDouble2() { - Scanner in = new Scanner(System.in); - while (true) { - System.out.print("Enter a number: "); - if (in.hasNextDouble()) { - break; - } - String word = in.next(); - System.err.println(word + " is not a number"); - } - double x = in.nextDouble(); - return x; - } - - public static double addNumbers() { - Scanner in = new Scanner(System.in); - int x = -1; - int sum = 0; - while (x != 0) { - x = in.nextInt(); - if (x <= 0) { - continue; - } - System.out.println("Adding " + x); - sum += x; - } - return sum; - } - -} +import java.util.Scanner; + +/** + * Do-while, break, and continue. + */ +public class Validate { + + public static double scanDouble() { + Scanner in = new Scanner(System.in); + boolean okay; + do { + System.out.print("Enter a number: "); + if (in.hasNextDouble()) { + okay = true; + } else { + okay = false; + String word = in.next(); + System.err.println(word + " is not a number"); + } + } while (!okay); + double x = in.nextDouble(); + return x; + } + + public static double scanDouble2() { + Scanner in = new Scanner(System.in); + while (true) { + System.out.print("Enter a number: "); + if (in.hasNextDouble()) { + break; + } + String word = in.next(); + System.err.println(word + " is not a number"); + } + double x = in.nextDouble(); + return x; + } + + public static double addNumbers() { + Scanner in = new Scanner(System.in); + int x = -1; + int sum = 0; + while (x != 0) { + x = in.nextInt(); + if (x <= 0) { + continue; + } + System.out.println("Adding " + x); + sum += x; + } + return sum; + } + +} diff --git a/ch08/AreFactors.java b/ch08/AreFactors.java new file mode 100644 index 0000000..42a3423 --- /dev/null +++ b/ch08/AreFactors.java @@ -0,0 +1,27 @@ +/** + * tests if all the numbers in the array are factors of n + */ +public class AreFactors { + /** + * tests if all numbers in a are factors of n + */ + public static boolean areFactors(int n, int[] a) { + for (int i = 0; i < a.length; i++) { + if (n % a[i] != 0) { + return false; + } + } + return true; + } + + public static void main(String[] args) { + int n = 12; + boolean result; + int[] a = new int[3]; + a[0] = 1; + a[1] = 2; + a[2] = 7; + result = areFactors(n, a); + System.out.println(result); + } +} \ No newline at end of file diff --git a/ch08/ArePrimeFactors.java b/ch08/ArePrimeFactors.java new file mode 100644 index 0000000..a7f6f25 --- /dev/null +++ b/ch08/ArePrimeFactors.java @@ -0,0 +1,84 @@ +/** + * tests an array a to see if the product of a's elements is n and + * every element of a is prime + */ +public class ArePrimeFactors { + /** + * creates an array of booleans from 0 to n-1 with prime numbers marked as true + * and nonprime numbers marked as false + * @param n size array + * @return array of booleans + */ + public static boolean[] sieve(int n) { + boolean[] result = new boolean[n]; + //want to check numbers with i^2 < n ----> i < sqrt(n) + //thus, end for loop when i <= floor(sqrt(n)) + int endIndex = (int) Math.floor(Math.sqrt(n)); + + //change values from index i to (n - 1) to true + for (int i = 2; i < n; i++) { + result[i] = true; + } + + for (int i = 2; i <= endIndex; i++) { + //if element has already been marked false, continue to next iteration + if (result[i] == false) { + continue; + } + + //want multiples j of i for i * j <= (n - 1) + //thus, end for loop when j <= the number of multiples + int numMultiple = (int) Math.floor((n - 1) / i); + for (int j = 2; j <= numMultiple; j++) { + result[i * j] = false; + } + } + return result; + } + + /** + * returns product of all elements in array + * @param array a + * @result returns product + */ + public static int product(int[] a) { + int result = 1; + for (int value : a) { + result = result * value; + } + return result; + } + + /** + * tests if product of array is n and all elements in array are prime + * @param int n, product of array should be n + * @param int[] a, tests of all elements in a are prime and they multiply to equal n + * @return true if product of array is n and all elements in array are prime + */ + public static boolean arePrimeFactors(int n, int[] a) { + int prod = product(a); + boolean[] primes = sieve(n + 1); + + if (prod != n) { + return false; + } + + for (int i = 0; i < a.length; i++) { + if (primes[a[i]] == false) { + return false; + } + } + return true; + } + + public static void main(String[] args) { + int[] a = new int[2]; + boolean result; + a[0] = 2; + a[1] = 7; + result = arePrimeFactors(14, a); + System.out.println(result); + } +} + + \ No newline at end of file diff --git a/ch08/ArrayExamples.java b/ch08/ArrayExamples.java index a4cb6c3..ca7c29f 100644 --- a/ch08/ArrayExamples.java +++ b/ch08/ArrayExamples.java @@ -1,100 +1,100 @@ -import java.util.Arrays; - -/** - * Demonstrates uses of arrays. - */ -public class ArrayExamples { - - /** - * Example code from Chapter 8. - */ - public static void main(String[] args) { - int size = 10; - int[] counts = new int[4]; - double[] values = new double[size]; - - counts[0] = 7; - counts[1] = counts[0] * 2; - counts[2]++; - counts[3] -= 60; - - // traversal with a while loop - int j = 0; - while (j < 4) { - System.out.println(counts[j]); - j++; - } - - // traversal with a for loop - for (int i = 0; i < 4; i++) { - System.out.println(counts[i]); - } - - int[] array = {1, 2, 3, 4}; - printArray(array); - - // printing an array as an object - System.out.println(array); - - // printing with Arrays class - System.out.println(Arrays.toString(array)); - - // copying an array - double[] a = {1.0, 2.0, 3.0}; - double[] b = new double[a.length]; - for (int i = 0; i < a.length; i++) { - b[i] = a[i]; - } - - // copying with Arrays class - double[] c = Arrays.copyOf(a, a.length); - - // traversal - for (int i = 0; i < a.length; i++) { - a[i] = Math.pow(a[i], 2.0); - } - - // search - int index = search(a, 2.0); - System.out.println("index = " + index); - - // reduce - double total = sum(a); - System.out.println("total = " + total); - } - - /** - * 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]); - } - System.out.println("}"); - } - - /** - * 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) { - return i; - } - } - return -1; - } - - /** - * Returns the total of the elements in an array. - */ - public static double sum(double[] a) { - double total = 0.0; - for (int i = 0; i < a.length; i++) { - total += a[i]; - } - return total; - } - -} +import java.util.Arrays; + +/** + * Demonstrates uses of arrays. + */ +public class ArrayExamples { + + /** + * Example code from Chapter 8. + */ + public static void main(String[] args) { + int size = 10; + int[] counts = new int[4]; + double[] values = new double[size]; + + counts[0] = 7; + counts[1] = counts[0] * 2; + counts[2]++; + counts[3] -= 60; + + // traversal with a while loop + int j = 0; + while (j < 4) { + System.out.println(counts[j]); + j++; + } + + // traversal with a for loop + for (int i = 0; i < 4; i++) { + System.out.println(counts[i]); + } + + int[] array = {1, 2, 3, 4}; + printArray(array); + + // printing an array as an object + System.out.println(array); + + // printing with Arrays class + System.out.println(Arrays.toString(array)); + + // copying an array + double[] a = {1.0, 2.0, 3.0}; + double[] b = new double[a.length]; + for (int i = 0; i < a.length; i++) { + b[i] = a[i]; + } + + // copying with Arrays class + double[] c = Arrays.copyOf(a, a.length); + + // traversal + for (int i = 0; i < a.length; i++) { + a[i] = Math.pow(a[i], 2.0); + } + + // search + int index = search(a, 2.0); + System.out.println("index = " + index); + + // reduce + double total = sum(a); + System.out.println("total = " + total); + } + + /** + * 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]); + } + System.out.println("}"); + } + + /** + * 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) { + return i; + } + } + return -1; + } + + /** + * Returns the total of the elements in an array. + */ + public static double sum(double[] a) { + double total = 0.0; + for (int i = 0; i < a.length; i++) { + total += a[i]; + } + return total; + } + +} diff --git a/ch08/Fruit.java b/ch08/Fruit.java index 50428c5..c45e394 100644 --- a/ch08/Fruit.java +++ b/ch08/Fruit.java @@ -1,35 +1,45 @@ -/** - * Fruit exercise. - */ -public class Fruit { - - public static int banana(int[] a) { - int kiwi = 1; - int i = 0; - while (i < a.length) { - kiwi = kiwi * a[i]; - i++; - } - return kiwi; - } - - public static int grapefruit(int[] a, int grape) { - for (int i = 0; i < a.length; i++) { - if (a[i] == grape) { - return i; - } - } - return -1; - } - - public static int pineapple(int[] a, int apple) { - int pear = 0; - for (int pine: a) { - if (pine == apple) { - pear++; - } - } - return pear; - } - -} +/** + * Fruit exercise. + */ +public class Fruit { + + /** + * reduces array of integers a to the product of its elements + */ + public static int banana(int[] a) { + int kiwi = 1; + int i = 0; + while (i < a.length) { + kiwi = kiwi * a[i]; + i++; + } + return kiwi; + } + + /** + * searches a for element whose value is equal to grape, + * returns the index of the matching element + */ + public static int grapefruit(int[] a, int grape) { + for (int i = 0; i < a.length; i++) { + if (a[i] == grape) { + return i; + } + } + return -1; + } + + /** + * counts how many times apple shows up in a + */ + public static int pineapple(int[] a, int apple) { + int pear = 0; + for (int pine: a) { + if (pine == apple) { + pear++; + } + } + return pear; + } + +} diff --git a/ch08/Histogram.java b/ch08/Histogram.java index 32b029c..6ae7e61 100644 --- a/ch08/Histogram.java +++ b/ch08/Histogram.java @@ -1,59 +1,59 @@ -import java.util.Random; - -/** - * Example code related to histograms. - */ -public class Histogram { - - /** - * Returns an array of random integers. - */ - public static int[] randomArray(int size) { - Random random = new Random(); - int[] a = new int[size]; - for (int i = 0; i < a.length; i++) { - a[i] = random.nextInt(100); - } - return a; - } - - /** - * Computes the number of array elements in [low, high). - */ - public static int inRange(int[] a, int low, int high) { - int count = 0; - for (int i = 0; i < a.length; i++) { - if (a[i] >= low && a[i] < high) { - count++; - } - } - return count; - } - - public static void main(String[] args) { - int numValues = 8; - int[] array = randomArray(numValues); - ArrayExamples.printArray(array); - - int[] scores = randomArray(30); - int a = inRange(scores, 90, 100); - int b = inRange(scores, 80, 90); - int c = inRange(scores, 70, 80); - int d = inRange(scores, 60, 70); - int f = inRange(scores, 0, 60); - - // making a histogram - int[] counts = new int[100]; - for (int i = 0; i < scores.length; i++) { - int index = scores[i]; - counts[index]++; - } - - // histogram with enhanced for loop - counts = new int[100]; - for (int score : scores) { - counts[score]++; - } - } - -} +import java.util.Random; + +/** + * Example code related to histograms. + */ +public class Histogram { + + /** + * Returns an array of random integers. + */ + public static int[] randomArray(int size) { + Random random = new Random(); + int[] a = new int[size]; + for (int i = 0; i < a.length; i++) { + a[i] = random.nextInt(100); + } + return a; + } + + /** + * Computes the number of array elements in [low, high). + */ + public static int inRange(int[] a, int low, int high) { + int count = 0; + for (int i = 0; i < a.length; i++) { + if (a[i] >= low && a[i] < high) { + count++; + } + } + return count; + } + + public static void main(String[] args) { + int numValues = 8; + int[] array = randomArray(numValues); + ArrayExamples.printArray(array); + + int[] scores = randomArray(30); + int a = inRange(scores, 90, 100); + int b = inRange(scores, 80, 90); + int c = inRange(scores, 70, 80); + int d = inRange(scores, 60, 70); + int f = inRange(scores, 0, 60); + + // making a histogram + int[] counts = new int[100]; + for (int i = 0; i < scores.length; i++) { + int index = scores[i]; + counts[index]++; + } + + // histogram with enhanced for loop + counts = new int[100]; + for (int score : scores) { + counts[score]++; + } + } + +} diff --git a/ch08/IndexOfMax.java b/ch08/IndexOfMax.java new file mode 100644 index 0000000..e1bec3a --- /dev/null +++ b/ch08/IndexOfMax.java @@ -0,0 +1,41 @@ +import java.util.Random; +import java.util.Arrays; + +/** + * find largest element in array and return its index + */ +public class IndexOfMax { + + /** + * return index of largest element in array + * @param array of integers a + * @return index of largest element in a + */ + public static int indexOfMax(int[] a) { + int index = 0; + for (int i = 0; i < a.length - 1; i++) { //need to use a.length - 1 because + if (a[index] < a[i + 1]) { //we use the index (i + 1) + index = i + 1; + } + } + return index; + } + + public static void main(String[] args) { + Random random = new Random(); + int[] a = new int[5]; + int result; + + //initializing array of size 5 with random integers from 0 - 9 + for (int i = 0; i < a.length; i++) { + a[i] = random.nextInt(10); + } + + result = indexOfMax(a); + + System.out.println(Arrays.toString(a)); + System.out.println(result); + } +} + + \ No newline at end of file diff --git a/ch08/MakeDubMus.java b/ch08/MakeDubMus.java index 9c7e193..9da445a 100644 --- a/ch08/MakeDubMus.java +++ b/ch08/MakeDubMus.java @@ -1,34 +1,34 @@ -/** - * Stack diagram exercise. - */ -public class MakeDubMus { - - public static int[] make(int n) { - int[] a = new int[n]; - for (int i = 0; i < n; i++) { - a[i] = i + 1; - } - return a; - } - - public static void dub(int[] jub) { - for (int i = 0; i < jub.length; i++) { - jub[i] *= 2; - } - } - - public static int mus(int[] zoo) { - int fus = 0; - for (int i = 0; i < zoo.length; i++) { - fus += zoo[i]; - } - return fus; - } - - public static void main(String[] args) { - int[] bob = make(5); - dub(bob); - System.out.println(mus(bob)); - } - -} +/** + * Stack diagram exercise. + */ +public class MakeDubMus { + + public static int[] make(int n) { + int[] a = new int[n]; + for (int i = 0; i < n; i++) { + a[i] = i + 1; + } + return a; + } + + public static void dub(int[] jub) { + for (int i = 0; i < jub.length; i++) { + jub[i] *= 2; + } + } + + public static int mus(int[] zoo) { + int fus = 0; + for (int i = 0; i < zoo.length; i++) { + fus += zoo[i]; + } + return fus; + } + + public static void main(String[] args) { + int[] bob = make(5); + dub(bob); + System.out.println(mus(bob)); + } + +} diff --git a/ch08/MaxInRange.java b/ch08/MaxInRange.java new file mode 100644 index 0000000..00effde --- /dev/null +++ b/ch08/MaxInRange.java @@ -0,0 +1,99 @@ +import java.util.Arrays; + +/** + * find largest element in an array using recursive method + */ +public class MaxInRange { + /** + * return index of largest element in array + * @param array of integers a + * @return index of largest element in a + */ + public static int indexOfMax(int[] a) { + int index = 0; + for (int i = 0; i < a.length - 1; i++) { //need to use a.length - 1 because + if (a[index] < a[i + 1]) { //we use the index (i + 1) + index = i + 1; + } + } + return index; + } + + /** + * finds max element in array between lowIndex and highIndex, including both + * breaks this array into two arrays, finds max in each, and then finds max(lowArrayMax, highArrayMax) + * @param array of integers a + * @param lowIndex start of search + * @param highIndex end of search + * @return max element between lowIndex and highIndex, including both + */ + public static int maxInRange(int[] a, int lowIndex, int highIndex) { + int lengthRange = highIndex - lowIndex + 1; //# elements between lowIndex and highIndex + int middleIndex = (int) Math.floor((lowIndex + highIndex) / 2); //midpoint of range + int lowArraySize = middleIndex - lowIndex + 1; //# elements in lowArray + int[] lowArray = new int[lowArraySize]; + int highArraySize = lengthRange - lowArraySize; //# elements in highArray + int[] highArray = new int[highArraySize]; + int lowArrayIndexMax = -1; + int highArrayIndexMax = -1; + int lowArrayMax, highArrayMax, actualMax; + + // if array between lowIndex and highIndex is just one element, + // that element must be the max + if (lengthRange == 1) { + return a[lowIndex]; + } + + // lowArray is comprised of elements in a from 0 to middleIndex + for (int i = 0; i < lowArray.length; i++) { + lowArray[i] = a[lowIndex + i]; + } + + // highArray is comprised of elements in a from (middleIndex + 1) to a.length - 1 + for (int j = 0; j < highArray.length; j++) { + highArray[j] = a[middleIndex + 1 + j]; + } + + //find index of max element in lowArray and highArray + lowArrayIndexMax = indexOfMax(lowArray); + highArrayIndexMax = indexOfMax(highArray); + //find max value in lowArray and highArray + lowArrayMax = lowArray[lowArrayIndexMax]; + highArrayMax = highArray[highArrayIndexMax]; + + //find actual max by calculating max(lowArrayMax, highArrayMax) + if (lowArrayMax >= highArrayMax) { + actualMax = lowArrayMax; + } else { + actualMax = highArrayMax; + } + + return actualMax; + } + + /** + * use maxInRange to find max of entire array + * @param array of integers a + * @return max of elements in a + */ + public static int max(int[] a) { + return maxInRange(a, 0, a.length - 1); + } + + public static void main(String[] args) { + int[] a = new int[5]; + int result; + int lowIndex = 0; + int highIndex = 4; + a[0] = 55; + a[1] = 1; + a[2] = 27; + a[3] = 3; + a[4] = 54; + result = max(a); + System.out.println(result); + } +} + + + \ No newline at end of file diff --git a/ch08/PowArrayAndHist.java b/ch08/PowArrayAndHist.java new file mode 100644 index 0000000..1bbc253 --- /dev/null +++ b/ch08/PowArrayAndHist.java @@ -0,0 +1,76 @@ +import java.util.Random; +import java.util.Arrays; + +/** + * practicing encapsulation and generalization + */ +public class PowArrayAndHist { + + /** + * raises all elements in an array to the nth power + * @param a: array of doubles + * @param n: raise all elements in a to the power of n + * @return the changed array a[i]^n + */ + public static double[] powArray(double[] a, int n) { + for (int i = 0; i < a.length; i++) { + a[i] = Math.pow(a[i], n); + } + return a; + } + + /** + * counts how many times each score in a range appears + * @param int[] scores: an array of integers, ranging from 0 to (range - 1) inclusive + * @param range: range of scores, also determines counts.length + * @return histogram counts + */ + public static int[] histogram(int[] scores, int range) { + int[] counts = new int[range]; + for (int score : scores) { + counts[score]++; + } + return counts; + } + + /** + * produces a random array of size size, with integer elements ranging from 0 to (range - 1) + * @param size: a.length + * @param range: range of integers for elements of a + * @return random array a + */ + public static int[] randomArray(int size, int range) { + Random random = new Random(); + int[] a = new int[size]; + for (int i = 0; i < a.length; i++) { + a[i] = random.nextInt(range); + } + return a; + } + + + public static void main(String[] args) { + double[] a = new double[5]; + int power = 3; + double[] results; + + int range = 10; + //note that the range for scores and counts must be the same + //otherwise, ArrayIndexOutOfBoundsException is thrown + int[] scores = randomArray(10, range); + int[] counts = histogram(scores, range); + + //initializing array of doubles with length 5 + //a = [0, 1, 2, 3, 4] + for (int i = 0; i < a.length; i++) { + a[i] = i; + } + + //raising all elements in a to the 3rd power + results = powArray(a, power); + + System.out.println(Arrays.toString(results)); + System.out.println(Arrays.toString(scores)); + System.out.println(Arrays.toString(counts)); + } +} \ No newline at end of file diff --git a/ch08/Sieve.java b/ch08/Sieve.java new file mode 100644 index 0000000..42497e8 --- /dev/null +++ b/ch08/Sieve.java @@ -0,0 +1,55 @@ +import java.util.Arrays; + +/** + * using the Sieve of Eratosthenes to create an array of booleans from 0 to n-1, + * where prime numbers are true and nonprime numbers are false + */ +public class Sieve { + + /** + * creates an array of booleans from 0 to n-1 with prime numbers marked as true + * and nonprime numbers marked as false + * @param n size array + * @return array of booleans + */ + public static boolean[] sieve(int n) { + boolean[] result = new boolean[n]; + //want to check numbers with i^2 < n ----> i < sqrt(n) + //thus, end for loop when i <= floor(sqrt(n)) + int endIndex = (int) Math.floor(Math.sqrt(n)); + + //change values from index i to (n - 1) to true + for (int i = 2; i < n; i++) { + result[i] = true; + } + + for (int i = 2; i <= endIndex; i++) { + //if element has already been marked false, continue to next iteration + if (result[i] == false) { + continue; + } + + //want multiples j of i for i * j <= (n - 1) + //thus, end for loop when j <= the number of multiples + int numMultiple = (int) Math.floor((n - 1) / i); + for (int j = 2; j <= numMultiple; j++) { + result[i * j] = false; + } + } + return result; + } + + public static void main(String[] args) { + boolean[] result; + int size = 15; + int[] listSize = new int[size]; + result = sieve(size); + + for (int i = 0; i < size; i++) { + listSize[i] = i; + } + + System.out.println(Arrays.toString(listSize)); + System.out.println(Arrays.toString(result)); + } +} \ No newline at end of file diff --git a/ch09/Exercise.java b/ch09/Exercise.java index d8a605d..02d5d53 100644 --- a/ch09/Exercise.java +++ b/ch09/Exercise.java @@ -1,22 +1,36 @@ -/** - * Exercise on encapsulation and generalization. - */ -public class Exercise { - - public static void main(String[] args) { - String s = "((3 + 7) * 2)"; - int count = 0; - - for (int i = 0; i < s.length(); i++) { - char c = s.charAt(i); - if (c == '(') { - count++; - } else if (c == ')') { - count--; - } - } - - System.out.println(count); - } - -} +import java.util.Arrays; + +/** + * Exercise on encapsulation and generalization. + */ +public class Exercise { + + /** + * checks if string is balanced + * @param checks string s + * @param char c1: for every appearance of c1 in s, count++ + * @param char c2: for every appearance of c2 in s, count-- + * @return count + */ + public static int balance(String s, char c1, char c2) { + int count = 0; + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + if (c == c1) { + count++; + } else if (c == c2) { + count--; + } + } + return count; + } + + public static void main(String[] args) { + int count = 0; + System.out.println(Arrays.toString(args)); + for (String arg : args) { + count = balance(arg, 'a', 'b'); + } + System.out.println(count); + } +} diff --git a/ch09/Format.java b/ch09/Format.java index 7e3ff8a..e298759 100644 --- a/ch09/Format.java +++ b/ch09/Format.java @@ -1,33 +1,33 @@ -/** - * Example using the String.format method. - */ -public class Format { - - /** - * Returns a time string in 12-hour format. - * - * @param hour between 0 and 23 - * @param minute between 0 and 59 - */ - public static String timeString(int hour, int minute) { - String ampm; - if (hour < 12) { - ampm = "AM"; - if (hour == 0) { - hour = 12; // midnight - } - } else { - ampm = "PM"; - hour = hour - 12; - } - return String.format("%02d:%02d %s", hour, minute, ampm); - } - - public static void main(String[] args) { - System.out.println(timeString(0, 0)); - System.out.println(timeString(7, 30)); - System.out.println(timeString(12, 5)); - System.out.println(timeString(23, 59)); - } - -} +/** + * Example using the String.format method. + */ +public class Format { + + /** + * Returns a time string in 12-hour format. + * + * @param hour between 0 and 23 + * @param minute between 0 and 59 + */ + public static String timeString(int hour, int minute) { + String ampm; + if (hour < 12) { + ampm = "AM"; + if (hour == 0) { + hour = 12; // midnight + } + } else { + ampm = "PM"; + hour = hour - 12; + } + return String.format("%02d:%02d %s", hour, minute, ampm); + } + + public static void main(String[] args) { + System.out.println(timeString(0, 0)); + System.out.println(timeString(7, 30)); + System.out.println(timeString(12, 5)); + System.out.println(timeString(23, 59)); + } + +} diff --git a/ch09/IsAbecedarian.java b/ch09/IsAbecedarian.java new file mode 100644 index 0000000..e6f9aa6 --- /dev/null +++ b/ch09/IsAbecedarian.java @@ -0,0 +1,34 @@ +import java.util.Arrays; + +/** + * checks if string is abecedarian (if all letters in string show up in + * alphabetical order) + */ +public class IsAbecedarian { + + /** + * checks if String s is abecedarian + */ + public static boolean isAbecedarian(String s) { + for (int i = 0; i < (s.length() - 1); i++) { + char c1 = s.charAt(i); + char c2 = s.charAt(i + 1); + int c1Num = (int) c1; //converts 1st and 2nd character in s to unicode int + int c2Num = (int) c2; + if (c1Num > c2Num) { //if 1st comes before 2nd in alphabet, return false + return false; + } + } + return true; + } + + public static void main(String[] args) { + boolean result; + System.out.println(Arrays.toString(args)); + for (String arg : args) { + result = isAbecedarian(arg); + System.out.println(result); + } + } +} + \ No newline at end of file diff --git a/ch09/IsAnagram.java b/ch09/IsAnagram.java new file mode 100644 index 0000000..76ca60e --- /dev/null +++ b/ch09/IsAnagram.java @@ -0,0 +1,50 @@ +import java.util.Arrays; + +/** + * checks if two strings are anagrams, contain same letters and same numbers of each letter + */ +public class IsAnagram { + + /** + * checks if String s1 and s2 are anagrams + */ + public static boolean isAnagram(String s1, String s2) { + String lowerS1 = s1.toLowerCase(); + String lowerS2 = s2.toLowerCase(); + int[] numChars1 = new int[s1.length()]; + int[] numChars2 = new int[s2.length()]; + int[] counts1 = new int[26]; + int[] counts2 = new int[26]; + + if (s1.length() != s2.length()) { //can't be anagrams if length is different + return false; + } + + for (int i = 0; i < s1.length(); i++) { + char c1 = s1.charAt(i); + char c2 = s2.charAt(i); + numChars1[i] = (int) c1; //integer array of unicode c1 + numChars2[i] = (int) c2; //integer array of unicode c2 + counts1[numChars1[i] - 97]++; //histogram of letters in s1 + counts2[numChars2[i] - 97]++; //histogram of letters in s2 + } + + for (int i = 0; i < 26; i++) { //if histograms are different, return false + if (counts1[i] != counts2[i]) { + return false; + } + } + return true; + } + + public static void main(String[] args) { + boolean resultTrue, resultFalse; + String str1 = "stop"; + String str2 = "pots"; + String str3 = "coffee"; + resultTrue = isAnagram(str1, str2); + resultFalse = isAnagram(str1, str3); + System.out.println(resultTrue + "\t" + resultFalse); + } +} + \ No newline at end of file diff --git a/ch09/IsDoubloon.java b/ch09/IsDoubloon.java new file mode 100644 index 0000000..820e34d --- /dev/null +++ b/ch09/IsDoubloon.java @@ -0,0 +1,37 @@ +import java.util.Arrays; + +/** + * checks if string is doubloon (every letter in string shows up exactly twice) + */ +public class IsDoubloon { + + /** + * checks if String s is a doubloon + */ + public static boolean isDoubloon(String s) { + String lowerS = s.toLowerCase(); + int[] numChars = new int[s.length()]; + int[] counts = new int[26]; + + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + numChars[i] = (int) c; + counts[numChars[i] - 97]++; //histogram of letters in s + } + for (int i = 0; i < 26; i++) { + if (counts[i] != 0 && counts[i] - 2 != 0) { //checks if letters show up exactly twice + return false; + } + } + return true; + } + + public static void main(String[] args) { + boolean result; + System.out.println(Arrays.toString(args)); + for (String arg : args) { + result = isDoubloon(arg); + System.out.println(result); + } + } +} \ No newline at end of file diff --git a/ch09/LetterHist.java b/ch09/LetterHist.java new file mode 100644 index 0000000..b567ff8 --- /dev/null +++ b/ch09/LetterHist.java @@ -0,0 +1,33 @@ +import java.util.Arrays; + +/** + * return histogram of characters in a string + * 0th element of histogram contains # a's, 1st element contains # b's, and so on + */ +public class LetterHist { + + /** + * create histogram of characters in a string + * @param String s: count how many times each element in s shows up + * @return histogram of characters in s + */ + public static int[] letterHist(String s) { + int[] hist = new int[26]; + for (int i = 0; i < s.length(); i++) { + char letter = s.charAt(i); + int charCode = ((int) letter) - 97; //in unicode, alphabet is 97 - 122; + hist[charCode]++; //we want 0 - 25 + } + return hist; + } + + public static void main(String[] args) { + int[] result = new int[26]; + System.out.println(Arrays.toString(args)); //converts command line input to String + for (String arg : args) { + result = letterHist(arg); + } + System.out.println(Arrays.toString(result)); + } +} + \ No newline at end of file diff --git a/ch09/Max.java b/ch09/Max.java index 2bf923e..3f587d7 100644 --- a/ch09/Max.java +++ b/ch09/Max.java @@ -1,24 +1,24 @@ -import java.util.Arrays; - -/** - * Demonstrates command-line arguments. - */ -public class Max { - - /** - * Converts args to integers and prints the max. - */ - public static void main(String[] args) { - System.out.println(Arrays.toString(args)); - - int max = Integer.MIN_VALUE; - for (String arg : args) { - int value = Integer.parseInt(arg); - if (value > max) { - max = value; - } - } - System.out.println("The max is " + max); - } - -} +import java.util.Arrays; + +/** + * Demonstrates command-line arguments. + */ +public class Max { + + /** + * Converts args to integers and prints the max. + */ + public static void main(String[] args) { + System.out.println(Arrays.toString(args)); + + int max = Integer.MIN_VALUE; + for (String arg : args) { + int value = Integer.parseInt(arg); + if (value > max) { + max = value; + } + } + System.out.println("The max is " + max); + } + +} diff --git a/ch09/Recurse.java b/ch09/Recurse.java index c4ba2fb..88ff2f0 100644 --- a/ch09/Recurse.java +++ b/ch09/Recurse.java @@ -1,34 +1,114 @@ -/** - * Recursion exercise. - */ -public class Recurse { - - /** - * Returns the first character of the given String. - */ - public static char first(String s) { - return s.charAt(0); - } - - /** - * Returns all but the first letter of the given String. - */ - public static String rest(String s) { - return s.substring(1); - } - - /** - * Returns all but the first and last letter of the String. - */ - public static String middle(String s) { - return s.substring(1, s.length() - 1); - } - - /** - * Returns the length of the given String. - */ - public static int length(String s) { - return s.length(); - } - -} +import java.util.Arrays; + +/** + * Recursion exercise. + */ +public class Recurse { + + /** + * Returns the first character of the given String. + */ + public static char first(String s) { + return s.charAt(0); + } + + /** + * Returns all but the first letter of the given String. + */ + public static String rest(String s) { + return s.substring(1); + } + + /** + * Returns all but the first and last letter of the String. + */ + public static String middle(String s) { + return s.substring(1, s.length() - 1); + } + + /** + * Returns the length of the given String. + */ + public static int length(String s) { + return s.length(); + } + + /** + * displays letters of String s, one on each line + * only uses previous methods + */ + public static void printString(String s) { + int sLength = length(s); + char firstChar = first(s); + String restString = rest(s); + for (int i = 0; i < sLength; i++) { + if (i == sLength - 1) { + System.out.println(firstChar); + continue; + } + System.out.println(firstChar); + firstChar = first(restString); + restString = rest(restString); + } + } + + /** + * does the same thing as printString but displays string backwards + */ + public static void printBackward(String s) { + if (length(s) == 1) { + System.out.println(s); + } else { + printBackward(rest(s)); + System.out.println(first(s)); + } + } + + /** + * returns String s in reverse + */ + public static String reverseString(String s) { + String backwards = ""; + for (int i = length(s) - 1; i >= 0; i--) { + backwards = backwards + s.charAt(i); + } + return backwards; + } + + /** + * checks if String s is a palindrome (reads the same both forwards and backwards) + */ + public static boolean isPalindrome(String s) { + boolean result = false; + if (length(s) == 1) { + result = true; //one letter words are palindromes + } else if (length(s) == 2) { //two letter words are palindromes if the letters are the same + if (s.charAt(0) == s.charAt(1)) { + result = true; + } else { + result = false; + } + } else { + if ((s.charAt(0) == s.charAt(length(s) - 1)) && isPalindrome(middle(s))) { + result = true; //first and last letter are same, and middle is palindrome + } else { + result = false; + } + } + return result; + } + + public static void main(String[] args) { + boolean result; + String reverse; + System.out.println(Arrays.toString(args)); + for (String arg : args) { + reverse = reverseString(arg); + result = isPalindrome(arg); + printString(arg); + printBackward(arg); + System.out.println(reverse); + System.out.println(result); + } + } +} diff --git a/ch09/Scrabble.java b/ch09/Scrabble.java new file mode 100644 index 0000000..a28e6c1 --- /dev/null +++ b/ch09/Scrabble.java @@ -0,0 +1,46 @@ +import java.util.Arrays; + +/** + * checks if set of tiles can spell word + */ +public class Scrabble { + + /** + * checks if set of tiles (s1) can spell word (s2) + */ + public static boolean canSpell(String s1, String s2) { + String lowerS1 = s1.toLowerCase(); + String lowerS2 = s2.toLowerCase(); + int[] numChars1 = new int[s1.length()]; + int[] counts1 = new int[26]; + + for (int i = 0; i < s1.length(); i++) { + char c1 = s1.charAt(i); + numChars1[i] = (int) c1; + counts1[numChars1[i] - 97]++; //histogram of letters in set of tiles + } + + for (int i = 0; i < s2.length(); i++) { //for each letter in s2, + char c2 = s2.charAt(i); //subtract from histogram of set of tiles + int numC2 = (int) c2; + counts1[numC2 - 97]--; + } + + for (int i = 0; i < 26; i++) { + if (counts1[i] < 0) { //if any value in histogram is negative, + return false; //then can't spell s2 with available tiles + } + } + return true; + } + + public static void main(String[] args) { + boolean resultTrue, resultFalse; + String str1 = "abcdefg"; + String str2 = "face"; + String str3 = "coffee"; + resultTrue = canSpell(str1, str2); + resultFalse = canSpell(str1, str3); + System.out.println(resultTrue + "\t" + resultFalse); + } +} \ No newline at end of file diff --git a/ch09/StringsThings.java b/ch09/StringsThings.java index 8b95e7e..559dc8e 100644 --- a/ch09/StringsThings.java +++ b/ch09/StringsThings.java @@ -1,105 +1,105 @@ -/** - * Demonstates uses of Strings. - */ -public class StringsThings { - - public static void main(String[] args) { - - // Characters - - String fruit = "banana"; - char letter0 = fruit.charAt(0); - - if (letter0 == 'a') { - System.out.println('?'); - } - - System.out.print("Roman alphabet: "); - for (char c = 'A'; c <= 'Z'; c++) { - System.out.print(c); - } - System.out.println(); - - System.out.print("Greek alphabet: "); - for (int i = 913; i <= 937; i++) { - System.out.print((char) i); - } - System.out.println(); - - // Strings are immutable - - String name = "Alan Turing"; - String upperName = name.toUpperCase(); - - String text = "Computer Science is fun!"; - text = text.replace("Computer Science", "CS"); - - // String traversal - - for (int i = 0; i < fruit.length(); i++) { - char letter = fruit.charAt(i); - System.out.println(letter); - } - - for (char letter : fruit.toCharArray()) { - System.out.println(letter); - } - - int length = fruit.length(); - char last = fruit.charAt(length - 1); // correct - - System.out.println(reverse(fruit)); - - // 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)); - - // The indexOf method - - int index = fruit.indexOf('a'); - int index2 = fruit.indexOf('a', 2); - - // String comparison - - String name1 = "Alan Turing"; - String name2 = "Ada Lovelace"; - if (name1.equals(name2)) { - System.out.println("The names are the same."); - } - - int diff = name1.compareTo(name2); - if (diff == 0) { - System.out.println("The names are the same."); - } else if (diff < 0) { - System.out.println("name1 comes before name2."); - } else if (diff > 0) { - System.out.println("name2 comes before name1."); - } - - // Wrapper classes - - String str = "12345"; - int num = Integer.parseInt(str); - - num = 12345; - str = Integer.toString(num); - } - - /** - * Reverses a string, returns a new String. - */ - public static String reverse(String s) { - String r = ""; - for (int i = s.length() - 1; i >= 0; i--) { - r = r + s.charAt(i); - } - return r; - } - -} +/** + * Demonstates uses of Strings. + */ +public class StringsThings { + + public static void main(String[] args) { + + // Characters + + String fruit = "banana"; + char letter0 = fruit.charAt(0); + + if (letter0 == 'a') { + System.out.println('?'); + } + + System.out.print("Roman alphabet: "); + for (char c = 'A'; c <= 'Z'; c++) { + System.out.print(c); + } + System.out.println(); + + System.out.print("Greek alphabet: "); + for (int i = 913; i <= 937; i++) { + System.out.print((char) i); + } + System.out.println(); + + // Strings are immutable + + String name = "Alan Turing"; + String upperName = name.toUpperCase(); + + String text = "Computer Science is fun!"; + text = text.replace("Computer Science", "CS"); + + // String traversal + + for (int i = 0; i < fruit.length(); i++) { + char letter = fruit.charAt(i); + System.out.println(letter); + } + + for (char letter : fruit.toCharArray()) { + System.out.println(letter); + } + + int length = fruit.length(); + char last = fruit.charAt(length - 1); // correct + + System.out.println(reverse(fruit)); + + // 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)); + + // The indexOf method + + int index = fruit.indexOf('a'); + int index2 = fruit.indexOf('a', 2); + + // String comparison + + String name1 = "Alan Turing"; + String name2 = "Ada Lovelace"; + if (name1.equals(name2)) { + System.out.println("The names are the same."); + } + + int diff = name1.compareTo(name2); + if (diff == 0) { + System.out.println("The names are the same."); + } else if (diff < 0) { + System.out.println("name1 comes before name2."); + } else if (diff > 0) { + System.out.println("name2 comes before name1."); + } + + // Wrapper classes + + String str = "12345"; + int num = Integer.parseInt(str); + + num = 12345; + str = Integer.toString(num); + } + + /** + * Reverses a string, returns a new String. + */ + public static String reverse(String s) { + String r = ""; + for (int i = s.length() - 1; i >= 0; i--) { + r = r + s.charAt(i); + } + return r; + } + +} diff --git a/ch09/Test.java b/ch09/Test.java new file mode 100644 index 0000000..4ca1996 --- /dev/null +++ b/ch09/Test.java @@ -0,0 +1,10 @@ +public class Test { + public static void main(String[] args) { + String a1 = ""; + int a2 = 3; + Object result = a1 + a2; + Class typeClass = result.getClass(); + System.out.println(result); + System.out.println(typeClass.getName()); + } +} \ No newline at end of file diff --git a/ch10/Big.java b/ch10/Big.java new file mode 100644 index 0000000..1c15993 --- /dev/null +++ b/ch10/Big.java @@ -0,0 +1,21 @@ +import java.math.BigInteger; + +/** + * calculating factorial with BigInteger + */ +public class Big { + public static BigInteger factorial(int n) { + BigInteger factorial = BigInteger.valueOf(n); + for (int i = 1; i < n; i++) { + BigInteger mult = BigInteger.valueOf(i); + factorial = factorial.multiply(mult); + } + return factorial; + } + + public static void main(String[] args) { + for (int i = 0; i < 31; i++) { + System.out.println(i + "\t" + factorial(i)); + } + } +} \ No newline at end of file diff --git a/ch10/PointRect.java b/ch10/PointRect.java index 36801a5..60d9cb6 100644 --- a/ch10/PointRect.java +++ b/ch10/PointRect.java @@ -1,90 +1,90 @@ -import java.awt.Point; -import java.awt.Rectangle; - -/** - * Demonstates use of Point and Rectangle classes. - */ -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; - - Rectangle box = new Rectangle(0, 0, 100, 200); - moveRect(box, 50, 100); - System.out.println(box); - box.translate(50, 100); - - 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); - } - - /** - * Prints the attributes of a Point object. - */ - public static void printPoint(Point p) { - System.out.println("(" + p.x + ", " + p.y + ")"); - } - - /** - * Computes the distance between two points. - */ - public static double distance(Point p1, Point p2) { - int dx = p2.x - p1.x; - int dy = p2.y - p1.y; - return Math.sqrt(dx * dx + dy * dy); - } - - /** - * Finds the center of a Rectangle and returns a new Point. - */ - public static Point findCenter(Rectangle box) { - int x = box.x + box.width / 2; - int y = box.y + box.height / 2; - return new Point(x, y); - } - - /** - * Moves a Rectangle by modifying the x and y attributes. - */ - public static void moveRect(Rectangle box, int dx, int dy) { - box.x = box.x + dx; - box.y = box.y + dy; - } - - /** - * Exercise on returning objects. - */ - public static void exercise2() { - Point blank = new Point(5, 8); - - Rectangle rect = new Rectangle(0, 2, 4, 4); - Point center = findCenter(rect); - - double dist = distance(center, blank); - System.out.println(dist); - } - - /** - * Exercise on aliasing. - */ - public static void exercise3() { - Rectangle box1 = new Rectangle(2, 4, 7, 9); - Point p1 = findCenter(box1); - printPoint(p1); - - box1.grow(1, 1); - Point p2 = findCenter(box1); - printPoint(p2); - } - -} +import java.awt.Point; +import java.awt.Rectangle; + +/** + * Demonstates use of Point and Rectangle classes. + */ +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; + + Rectangle box = new Rectangle(0, 0, 100, 200); + moveRect(box, 50, 100); + System.out.println(box); + box.translate(50, 100); + + 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); + } + + /** + * Prints the attributes of a Point object. + */ + public static void printPoint(Point p) { + System.out.println("(" + p.x + ", " + p.y + ")"); + } + + /** + * Computes the distance between two points. + */ + public static double distance(Point p1, Point p2) { + int dx = p2.x - p1.x; + int dy = p2.y - p1.y; + return Math.sqrt(dx * dx + dy * dy); + } + + /** + * Finds the center of a Rectangle and returns a new Point. + */ + public static Point findCenter(Rectangle box) { + int x = box.x + box.width / 2; + int y = box.y + box.height / 2; + return new Point(x, y); + } + + /** + * Moves a Rectangle by modifying the x and y attributes. + */ + public static void moveRect(Rectangle box, int dx, int dy) { + box.x = box.x + dx; + box.y = box.y + dy; + } + + /** + * Exercise on returning objects. + */ + public static void exercise2() { + Point blank = new Point(5, 8); + + Rectangle rect = new Rectangle(0, 2, 4, 4); + Point center = findCenter(rect); + + double dist = distance(center, blank); + System.out.println(dist); + } + + /** + * Exercise on aliasing. + */ + public static void exercise3() { + Rectangle box1 = new Rectangle(2, 4, 7, 9); + Point p1 = findCenter(box1); + printPoint(p1); + + box1.grow(1, 1); + Point p2 = findCenter(box1); + printPoint(p2); + } + +} diff --git a/ch10/Pow.java b/ch10/Pow.java index 9ba0952..43837dc 100644 --- a/ch10/Pow.java +++ b/ch10/Pow.java @@ -1,24 +1,26 @@ -/** - * BigInteger exercise. - */ -public class Pow { - - /** - * Integer exponentiation. - */ - public static int pow(int x, int n) { - if (n == 0) return 1; - - // find x to the n/2 recursively - int t = pow(x, n / 2); - - // if n is even, the result is t squared - // if n is odd, the result is t squared times x - if (n % 2 == 0) { - return t * t; - } else { - return t * t * x; - } - } - -} +import java.math.BigInteger; + +/** + * BigInteger exercise. + */ +public class Pow { + + /** + * Integer exponentiation. + */ + public static BigInteger pow(int x, int n) { + if (n == 0) return BigInteger.valueOf(1); + + // find x to the n/2 recursively + BigInteger t = pow(x, n / 2); + + // if n is even, the result is t squared + // if n is odd, the result is t squared times x + if (n % 2 == 0) { + return t.multiply(t); + } else { + return t.multiply(t).multiply(BigInteger.valueOf(x)); + } + } + +} diff --git a/ch10/Riddle.java b/ch10/Riddle.java index cd04a16..db704ec 100644 --- a/ch10/Riddle.java +++ b/ch10/Riddle.java @@ -1,23 +1,23 @@ -import java.awt.Point; - -/** - * Exercise on passing objects as parameters. - */ -public class Riddle { - - public static int riddle(int x, Point p) { - x = x + 7; - return x + p.x + p.y; - } - - public static void main(String[] args) { - int x = 5; - Point blank = new Point(1, 2); - - System.out.println(riddle(x, blank)); - System.out.println(x); - System.out.println(blank.x); - System.out.println(blank.y); - } - -} +import java.awt.Point; + +/** + * Exercise on passing objects as parameters. + */ +public class Riddle { + + public static int riddle(int x, Point p) { + x = x + 7; + return x + p.x + p.y; + } + + public static void main(String[] args) { + int x = 5; + Point blank = new Point(1, 2); + + System.out.println(riddle(x, blank)); + System.out.println(x); + System.out.println(blank.x); + System.out.println(blank.y); + } + +} diff --git a/ch11/Date.java b/ch11/Date.java new file mode 100644 index 0000000..e469207 --- /dev/null +++ b/ch11/Date.java @@ -0,0 +1,33 @@ +/** + * class for date + */ +public class Date { + private int year; + private int month; + private int day; + + //constructor + public Date() { + this.year = 2019; + this.month = 11; + this.day = 4; + } + + //value constructor + public Date(int year, int month, int day) { + this.year = year; + this.month = month; + this.day = day; + } + + //print + public static void printDate(Date date) { + System.out.printf("%d/%d/%d\n", date.month, date.day, date.year); + } + + public static void main(String[] args) { + Date birthday = new Date(1998, 4, 27); + System.out.println(birthday); + printDate(birthday); + } +} \ No newline at end of file diff --git a/ch11/Rational.java b/ch11/Rational.java new file mode 100644 index 0000000..485322e --- /dev/null +++ b/ch11/Rational.java @@ -0,0 +1,81 @@ +/** + * class for rational numbers, stores numerator and denominator + */ +public class Rational { + private int num; + private int den; + + //constructor + public Rational() { + this.num = 0; + this.den = 1; + } + + //value constructor + public Rational(int num, int den) { + this.num = num; + this.den = den; + } + + public void printRational() { + System.out.printf("%d/%d\n", this.num, this.den); + } + + public String toString() { + return String.format("%d/%d", this.num, this.den); + } + + //reverses sign of rational number + public void negate() { + this.num = this.num * -1; + } + + //switches numerator and denominator + public void invert() { + int a = this.num; + int b = this.den; + this.num = b; + this.den = a; + } + + //converts to rational fraction to double + public double toDouble() { + double a = (double) this.num; + double b = (double) this.den; + return a / b; + } + + //finds gcd of numerator and denominator + public static int findGCD(int num1, int num2) { + if (num2 == 0) { + return num1; + } + return findGCD(num2, num1 % num2); + } + + //reduces rational number to lowest terms + public Rational reduce() { + int gcd = findGCD(this.num, this.den); + Rational reduced = new Rational(this.num / gcd, this.den / gcd); + return reduced; + } + + //adds two rational numbers, and reduces sum to lowest terms + public Rational add(Rational that) { + Rational sum = new Rational(); + int thisNum = this.num * that.den; + int thisDen = this.den * that.den; + int thatNum = that.num * this.den; + sum.num = thisNum + thatNum; + sum.den = thisDen; + sum = sum.reduce(); + return sum; + } + + public static void main(String[] args) { + Rational test1 = new Rational(1, 5); + Rational test2 = new Rational(3, 6); + Rational sum = test1.add(test2); + sum.printRational(); + } +} \ No newline at end of file diff --git a/ch11/Tile.java b/ch11/Tile.java new file mode 100644 index 0000000..58f8446 --- /dev/null +++ b/ch11/Tile.java @@ -0,0 +1,52 @@ +/** + * class for Scrabble tile + */ +public class Tile { + private char letter; + private int value; + + //value constructor + public Tile(char letter, int value) { + this.letter = letter; + this.value = value; + } + + //print method + public static void printTile(Tile tile) { + System.out.printf("%c: %d\n", tile.letter, tile.value); + } + + //instantiating new instance of Tile + public static void testTile() { + Tile tile = new Tile('Z', 10); + printTile(tile); + } + + //overloading toString method + public String toString() { + return String.format("%c: %d\n", this.letter, this.value); + } + + //overloading equals method + public boolean equals(Tile that) { + return this.letter == that.letter && this.value == that.value; + } + + //getters + public char getLetter() { + return this.letter; + } + + public int getValue() { + return this.value; + } + + //setters + public void setLetter(char letter) { + this.letter = letter; + } + + public void setValue(int value) { + this.value = value; + } +} \ No newline at end of file diff --git a/ch11/Time.java b/ch11/Time.java index 53afa0d..35bdf22 100644 --- a/ch11/Time.java +++ b/ch11/Time.java @@ -1,102 +1,102 @@ -/** - * Represents a time of day. - */ -public class Time { - - private int hour; - private int minute; - private double second; - - /** - * Construct a Time object with default values. - */ - public Time() { - this.hour = 0; - this.minute = 0; - this.second = 0.0; - } - - /** - * Construct a Time object with given values. - */ - public Time(int hour, int minute, double second) { - this.hour = hour; - this.minute = minute; - this.second = second; - } - - /** - * Prints the time in a simple format. - */ - public static void printTime(Time t) { - System.out.print(t.hour); - System.out.print(":"); - System.out.println(t.minute); - System.out.print(":"); - System.out.println(t.second); - } - - /** - * Returns a String representation of the time. - */ - public String toString() { - return String.format("%02d:%02d:%04.1f\n", - this.hour, this.minute, this.second); - } - - /** - * Tests whether two times are equivalent. - */ - public boolean equals(Time that) { - return this.hour == that.hour - && this.minute == that.minute - && this.second == that.second; - } - - /** - * Adds two Times and returns a new Time object (static method). - */ - public static Time add(Time t1, Time t2) { - Time sum = new Time(); - sum.hour = t1.hour + t2.hour; - sum.minute = t1.minute + t2.minute; - sum.second = t1.second + t2.second; - return sum; - } - - /** - * Adds two Times and returns a new Time object (instance method). - */ - public Time add(Time t2) { - Time sum = new Time(); - 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; - } - if (sum.minute >= 60) { - 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; - } - } - -} +/** + * Represents a time of day. + */ +public class Time { + + private int hour; + private int minute; + private double second; + + /** + * Construct a Time object with default values. + */ + public Time() { + this.hour = 0; + this.minute = 0; + this.second = 0.0; + } + + /** + * Construct a Time object with given values. + */ + public Time(int hour, int minute, double second) { + this.hour = hour; + this.minute = minute; + this.second = second; + } + + /** + * Prints the time in a simple format. + */ + public static void printTime(Time t) { + System.out.print(t.hour); + System.out.print(":"); + System.out.println(t.minute); + System.out.print(":"); + System.out.println(t.second); + } + + /** + * Returns a String representation of the time. + */ + public String toString() { + return String.format("%02d:%02d:%04.1f\n", + this.hour, this.minute, this.second); + } + + /** + * Tests whether two times are equivalent. + */ + public boolean equals(Time that) { + return this.hour == that.hour + && this.minute == that.minute + && this.second == that.second; + } + + /** + * Adds two Times and returns a new Time object (static method). + */ + public static Time add(Time t1, Time t2) { + Time sum = new Time(); + sum.hour = t1.hour + t2.hour; + sum.minute = t1.minute + t2.minute; + sum.second = t1.second + t2.second; + return sum; + } + + /** + * Adds two Times and returns a new Time object (instance method). + */ + public Time add(Time t2) { + Time sum = new Time(); + 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; + } + if (sum.minute >= 60) { + 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; + } + } + +} diff --git a/ch11/TimeClient.java b/ch11/TimeClient.java index aa90401..cd179c4 100644 --- a/ch11/TimeClient.java +++ b/ch11/TimeClient.java @@ -1,33 +1,33 @@ -/** - * Class that uses Time objects. - */ -public class TimeClient { - - public static void main(String[] args) { - Time time = new Time(11, 59, 59.9); - System.out.println(time); - - // cannot access private variables from another class - // System.out.println(time.hour); - - String s = time.toString(); - System.out.println(s); - - Time time1 = new Time(9, 30, 0.0); - Time time2 = time1; - Time time3 = new Time(9, 30, 0.0); - - System.out.println(time1 == time2); - System.out.println(time1 == time3); - System.out.println(time1.equals(time2)); - System.out.println(time1.equals(time3)); - - Time startTime = new Time(18, 50, 0.0); - Time runningTime = new Time(2, 16, 0.0); - Time endTime = Time.add(startTime, runningTime); - - // using the instance method - endTime = startTime.add(runningTime); - } - -} +/** + * Class that uses Time objects. + */ +public class TimeClient { + + public static void main(String[] args) { + Time time = new Time(11, 59, 59.9); + System.out.println(time); + + // cannot access private variables from another class + // System.out.println(time.hour); + + String s = time.toString(); + System.out.println(s); + + Time time1 = new Time(9, 30, 0.0); + Time time2 = time1; + Time time3 = new Time(9, 30, 0.0); + + System.out.println(time1 == time2); + System.out.println(time1 == time3); + System.out.println(time1.equals(time2)); + System.out.println(time1.equals(time3)); + + Time startTime = new Time(18, 50, 0.0); + Time runningTime = new Time(2, 16, 0.0); + Time endTime = Time.add(startTime, runningTime); + + // using the instance method + endTime = startTime.add(runningTime); + } + +} diff --git a/ch12/Card.java b/ch12/Card.java index e7a0661..df90cfa 100644 --- a/ch12/Card.java +++ b/ch12/Card.java @@ -1,83 +1,91 @@ -/** - * A standard playing card. - */ -public class Card { - - public static final String[] RANKS = { - null, "Ace", "2", "3", "4", "5", "6", "7", - "8", "9", "10", "Jack", "Queen", "King"}; - - public static final String[] SUITS = { - "Clubs", "Diamonds", "Hearts", "Spades"}; - - private final int rank; - - private final int suit; - - /** - * Constructs a card of the given rank and suit. - */ - public Card(int rank, int suit) { - this.rank = rank; - this.suit = suit; - } - - /** - * Returns a negative integer if this card comes before - * the given card, zero if the two cards are equal, or - * a positive integer if this card comes after the card. - */ - public int compareTo(Card that) { - if (this.suit < that.suit) { - return -1; - } - if (this.suit > that.suit) { - return 1; - } - if (this.rank < that.rank) { - return -1; - } - if (this.rank > that.rank) { - return 1; - } - return 0; - } - - /** - * Returns true if the given card has the same - * rank AND same suit; otherwise returns false. - */ - public boolean equals(Card that) { - return this.rank == that.rank - && this.suit == that.suit; - } - - /** - * Gets the card's rank. - */ - public int getRank() { - return this.rank; - } - - /** - * Gets the card's suit. - */ - public int getSuit() { - return this.suit; - } - - /** - * Returns the card's index in a sorted deck of 52 cards. - */ - public int position() { - return this.suit * 13 + this.rank - 1; - } - - /** - * Returns a string representation of the card. - */ - public String toString() { - return RANKS[this.rank] + " of " + SUITS[this.suit]; - } - -} +/** + * A standard playing card. + */ +public class Card { + + public static final String[] RANKS = { + null, "Ace", "2", "3", "4", "5", "6", "7", + "8", "9", "10", "Jack", "Queen", "King"}; + + public static final String[] SUITS = { + "Clubs", "Diamonds", "Hearts", "Spades"}; + + private final int rank; + + private final int suit; + + /** + * Constructs a card of the given rank and suit. + */ + public Card(int rank, int suit) { + this.rank = rank; + this.suit = suit; + } + + /** + * Returns a negative integer if this card comes before + * the given card, zero if the two cards are equal, or + * a positive integer if this card comes after the card. + */ + public int compareTo(Card that) { + if (this.suit < that.suit) { + return -1; + } + if (this.suit > that.suit) { + return 1; + } + //in some games, Aces are ranked higher than Kings + if (this.rank == 1 && that.rank == 1) { + return 0; + } else if (this.rank == 1 && that.rank != 1) { + return 1; + } else if (this.rank != 1 && that.rank == 1) { + return -1; + } + if (this.rank < that.rank) { + return -1; + } + if (this.rank > that.rank) { + return 1; + } + return 0; + } + + /** + * Returns true if the given card has the same + * rank AND same suit; otherwise returns false. + */ + public boolean equals(Card that) { + return this.rank == that.rank + && this.suit == that.suit; + } + + /** + * Gets the card's rank. + */ + public int getRank() { + return this.rank; + } + + /** + * Gets the card's suit. + */ + public int getSuit() { + return this.suit; + } + + /** + * Returns the card's index in a sorted deck of 52 cards. + */ + public int position() { + return this.suit * 13 + this.rank - 1; + } + + /** + * Returns a string representation of the card. + */ + public String toString() { + return RANKS[this.rank] + " of " + SUITS[this.suit]; + } + +} diff --git a/ch12/CardTable.java b/ch12/CardTable.java index 727d307..0b32a29 100644 --- a/ch12/CardTable.java +++ b/ch12/CardTable.java @@ -1,93 +1,93 @@ -import java.awt.Canvas; -import java.awt.Color; -import java.awt.Graphics; -import java.awt.Image; - -import javax.swing.ImageIcon; -import javax.swing.JFrame; - -public class CardTable extends Canvas { - - private Image[][] images; - private int cardWidth, cardHeight; - - /** - * Creates a CardTable. - * cardset is the name of the folder that contains the card images. - */ - public CardTable(String cardset) { - setBackground(new Color(0x088A4B)); - - // create a 2-D array of card images - images = new Image[14][4]; - String suits = "cdhs"; - - for (int suit = 0; suit <= 3; suit++) { - char c = suits.charAt(suit); - - for (int rank = 1; rank <= 13; rank++) { - String s = String.format("%s/%02d%c.gif", - cardset, rank, c); - images[rank][suit] = new ImageIcon(s).getImage(); - } - } - - // get the width and height of the cards and set the size of - // the frame accordingly - cardWidth = images[1][1].getWidth(null); - cardHeight = images[1][1].getHeight(null); - - // set the size temporarily to get the insets - setTableSize(14, 4); - } - - /** - * Sets the table size. - * x and y are in units of card width/height. - */ - public void setTableSize(double x, double y) { - setSize((int) (x * cardWidth), - (int) (y * cardHeight)); - } - - /** - * Draws a card at the given coordinates. - * x and y are in units of card width/height. - */ - public void drawCard(Graphics g, int rank, int suit, double x, double y) { - Image image = images[rank][suit]; - g.drawImage(image, - (int) (x * cardWidth), - (int) (y * cardHeight), - null); - } - - /** - * Special method invoked when the Frame needs to be drawn. - */ - public void paint(Graphics g) { - for (int rank = 1; rank <= 13; rank++) { - for (int suit = 0; suit <= 3; suit++) { - double x = rank - 1 + suit / 5.0; - double y = suit / 2.0; - drawCard(g, rank, suit, x, y); - } - } - } - - public static void main(String[] args) { - // make the frame - JFrame frame = new JFrame("Card Table"); - frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - - // add the CardTable - String cardset = "cardset-oxymoron"; - Canvas canvas = new CardTable(cardset); - frame.getContentPane().add(canvas); - - // show the frame - frame.pack(); - frame.setVisible(true); - } - -} +import java.awt.Canvas; +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Image; + +import javax.swing.ImageIcon; +import javax.swing.JFrame; + +public class CardTable extends Canvas { + + private Image[][] images; + private int cardWidth, cardHeight; + + /** + * Creates a CardTable. + * cardset is the name of the folder that contains the card images. + */ + public CardTable(String cardset) { + setBackground(new Color(0x088A4B)); + + // create a 2-D array of card images + images = new Image[14][4]; + String suits = "cdhs"; + + for (int suit = 0; suit <= 3; suit++) { + char c = suits.charAt(suit); + + for (int rank = 1; rank <= 13; rank++) { + String s = String.format("%s/%02d%c.gif", + cardset, rank, c); + images[rank][suit] = new ImageIcon(s).getImage(); + } + } + + // get the width and height of the cards and set the size of + // the frame accordingly + cardWidth = images[1][1].getWidth(null); + cardHeight = images[1][1].getHeight(null); + + // set the size temporarily to get the insets + setTableSize(14, 4); + } + + /** + * Sets the table size. + * x and y are in units of card width/height. + */ + public void setTableSize(double x, double y) { + setSize((int) (x * cardWidth), + (int) (y * cardHeight)); + } + + /** + * Draws a card at the given coordinates. + * x and y are in units of card width/height. + */ + public void drawCard(Graphics g, int rank, int suit, double x, double y) { + Image image = images[rank][suit]; + g.drawImage(image, + (int) (x * cardWidth), + (int) (y * cardHeight), + null); + } + + /** + * Special method invoked when the Frame needs to be drawn. + */ + public void paint(Graphics g) { + for (int rank = 1; rank <= 13; rank++) { + for (int suit = 0; suit <= 3; suit++) { + double x = rank - 1 + suit / 5.0; + double y = suit / 2.0; + drawCard(g, rank, suit, x, y); + } + } + } + + public static void main(String[] args) { + // make the frame + JFrame frame = new JFrame("Card Table"); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + // add the CardTable + String cardset = "cardset-oxymoron"; + Canvas canvas = new CardTable(cardset); + frame.getContentPane().add(canvas); + + // show the frame + frame.pack(); + frame.setVisible(true); + } + +} diff --git a/ch12/Search.java b/ch12/Search.java index 2f83023..d9b8d74 100644 --- a/ch12/Search.java +++ b/ch12/Search.java @@ -1,112 +1,141 @@ -/** - * Search algorithms for arrays of cards. - */ -public class Search { - - /** - * Make an array of 52 cards. - */ - public static Card[] makeDeck() { - Card[] cards = new Card[52]; - int index = 0; - for (int suit = 0; suit <= 3; suit++) { - for (int rank = 1; rank <= 13; rank++) { - cards[index] = new Card(rank, suit); - index++; - } - } - return cards; - } - - /** - * Displays the given deck of cards. - */ - public static void printDeck(Card[] cards) { - for (int i = 0; i < cards.length; i++) { - System.out.println(cards[i]); - } - } - - /** - * Sequential search. - */ - public static int search(Card[] cards, Card target) { - for (int i = 0; i < cards.length; i++) { - if (cards[i].equals(target)) { - return i; - } - } - return -1; - } - - /** - * Binary search (iterative version). - */ - public static int binarySearch(Card[] cards, Card target) { - int low = 0; - int high = cards.length - 1; - while (low <= high) { - System.out.println(low + ", " + high); - - int mid = (low + high) / 2; // step 1 - int comp = cards[mid].compareTo(target); - - if (comp == 0) { // step 2 - return mid; - } else if (comp < 0) { // step 3 - low = mid + 1; - } else { // step 4 - high = mid - 1; - } - } - return -1; - } - - /** - * Binary search (recursive version). - */ - public static int binarySearch(Card[] cards, Card target, - int low, int high) { - System.out.println(low + ", " + high); - - if (high < low) { - return -1; - } - int mid = (low + high) / 2; // step 1 - int comp = cards[mid].compareTo(target); - - if (comp == 0) { // step 2 - return mid; - } else if (comp < 0) { // step 3 - return binarySearch(cards, target, mid + 1, high); - } else { // step 4 - return binarySearch(cards, target, low, mid - 1); - } - } - - /** - * Demonstrates how to call the search methods. - */ - public static void main(String[] args) { - Card[] cards = makeDeck(); - Card jack = new Card(11, 0); - Card fake = new Card(15, 1); - - System.out.println("Sequential search"); - System.out.println(search(cards, jack)); - System.out.println(); - - System.out.println("Binary search"); - System.out.println(binarySearch(cards, jack)); - System.out.println(); - - System.out.println("Failed binary search"); - System.out.println(binarySearch(cards, fake)); - System.out.println(); - - System.out.println("Recursive binary search"); - System.out.println(binarySearch(cards, jack, 0, 51)); - System.out.println(); - } - -} +import java.util.Arrays; + +/** + * Search algorithms for arrays of cards. + */ +public class Search { + + /** + * Make an array of 52 cards. + */ + public static Card[] makeDeck() { + Card[] cards = new Card[52]; + int index = 0; + for (int suit = 0; suit <= 3; suit++) { + for (int rank = 1; rank <= 13; rank++) { + cards[index] = new Card(rank, suit); + index++; + } + } + return cards; + } + + /** + * Displays the given deck of cards. + */ + public static void printDeck(Card[] cards) { + for (int i = 0; i < cards.length; i++) { + System.out.println(cards[i]); + } + } + + /** + * Sequential search. + */ + public static int search(Card[] cards, Card target) { + for (int i = 0; i < cards.length; i++) { + if (cards[i].equals(target)) { + return i; + } + } + return -1; + } + + /** + * Binary search (iterative version). + */ + public static int binarySearch(Card[] cards, Card target) { + int low = 0; + int high = cards.length - 1; + while (low <= high) { + System.out.println(low + ", " + high); + + int mid = (low + high) / 2; // step 1 + int comp = cards[mid].compareTo(target); + + if (comp == 0) { // step 2 + return mid; + } else if (comp < 0) { // step 3 + low = mid + 1; + } else { // step 4 + high = mid - 1; + } + } + return -1; + } + + /** + * Binary search (recursive version). + */ + public static int binarySearch(Card[] cards, Card target, + int low, int high) { + System.out.println(low + ", " + high); + + if (high < low) { + return -1; + } + int mid = (low + high) / 2; // step 1 + int comp = cards[mid].compareTo(target); + + if (comp == 0) { // step 2 + return mid; + } else if (comp < 0) { // step 3 + return binarySearch(cards, target, mid + 1, high); + } else { // step 4 + return binarySearch(cards, target, low, mid - 1); + } + } + + /** + * histogram of suits + */ + public static int[] suitHist(Card[] cards) { + int[] hist = new int[4]; + for (int i = 0; i < cards.length; i++) { + hist[cards[i].getSuit()]++; + } + return hist; + } + + /** + * checks if hand has a flush (>= 5 cards with same suit) + */ + public static boolean hasFlush(Card[] cards) { + int[] hist = suitHist(cards); + for (int i = 0; i < 4; i++) { + if (hist[i] >= 5) { + return true; + } + } + return false; + } + + /** + * Demonstrates how to call the search methods. + */ + public static void main(String[] args) { + Card[] cards = new Card[2]; + cards[0] = new Card(11, 0); + cards[1] = new Card(15, 1); + System.out.println(hasFlush(cards)); +// Card jack = new Card(11, 0); +// Card fake = new Card(15, 1); +// +// System.out.println("Sequential search"); +// System.out.println(search(cards, jack)); +// System.out.println(); +// +// System.out.println("Binary search"); +// System.out.println(binarySearch(cards, jack)); +// System.out.println(); +// +// System.out.println("Failed binary search"); +// System.out.println(binarySearch(cards, fake)); +// System.out.println(); +// +// System.out.println("Recursive binary search"); +// System.out.println(binarySearch(cards, jack, 0, 51)); +// System.out.println(); + } + +} diff --git a/ch13/Card.java b/ch13/Card.java index 1c6483e..9499b1c 120000 --- a/ch13/Card.java +++ b/ch13/Card.java @@ -1 +1,91 @@ -../ch12/Card.java \ No newline at end of file +/** + * A standard playing card. + */ +public class Card { + + public static final String[] RANKS = { + null, "Ace", "2", "3", "4", "5", "6", "7", + "8", "9", "10", "Jack", "Queen", "King"}; + + public static final String[] SUITS = { + "Clubs", "Diamonds", "Hearts", "Spades"}; + + private final int rank; + + private final int suit; + + /** + * Constructs a card of the given rank and suit. + */ + public Card(int rank, int suit) { + this.rank = rank; + this.suit = suit; + } + + /** + * Returns a negative integer if this card comes before + * the given card, zero if the two cards are equal, or + * a positive integer if this card comes after the card. + */ + public int compareTo(Card that) { + if (this.suit < that.suit) { + return -1; + } + if (this.suit > that.suit) { + return 1; + } + //in some games, Aces are ranked higher than Kings +// if (this.rank == 1 && that.rank == 1) { +// return 0; +// } else if (this.rank == 1 && that.rank != 1) { +// return 1; +// } else if (this.rank != 1 && that.rank == 1) { +// return -1; +// } + if (this.rank < that.rank) { + return -1; + } + if (this.rank > that.rank) { + return 1; + } + return 0; + } + + /** + * Returns true if the given card has the same + * rank AND same suit; otherwise returns false. + */ + public boolean equals(Card that) { + return this.rank == that.rank + && this.suit == that.suit; + } + + /** + * Gets the card's rank. + */ + public int getRank() { + return this.rank; + } + + /** + * Gets the card's suit. + */ + public int getSuit() { + return this.suit; + } + + /** + * Returns the card's index in a sorted deck of 52 cards. + */ + public int position() { + return this.suit * 13 + this.rank - 1; + } + + /** + * Returns a string representation of the card. + */ + public String toString() { + return RANKS[this.rank] + " of " + SUITS[this.suit]; + } + +} diff --git a/ch13/Deck.java b/ch13/Deck.java index 742120e..3840fed 100644 --- a/ch13/Deck.java +++ b/ch13/Deck.java @@ -1,119 +1,182 @@ -import java.util.Arrays; -import java.util.Random; - -/** - * A deck of playing cards (of fixed size). - */ -public class Deck { - - private Card[] cards; - - /** - * Constructs a standard deck of 52 cards. - */ - public Deck() { - this.cards = new Card[52]; - int index = 0; - for (int suit = 0; suit <= 3; suit++) { - for (int rank = 1; rank <= 13; rank++) { - this.cards[index] = new Card(rank, suit); - index++; - } - } - } - - /** - * Constructs a deck of n cards (null). - */ - public Deck(int n) { - this.cards = new Card[n]; - } - - /** - * Gets the internal cards array. - */ - public Card[] getCards() { - return this.cards; - } - - /** - * Displays each of the cards in the deck. - */ - public void print() { - for (int i = 0; i < this.cards.length; i++) { - System.out.println(this.cards[i]); - } - } - - /** - * Returns a string representation of the deck. - */ - public String toString() { - return Arrays.toString(this.cards); - } - - /** - * Chooses a random number between low and high, including both. - */ - public int randomInt(int low, int high) { - return 0; - } - - /** - * Swaps the cards at indexes i and j. - */ - public void swapCards(int i, int j) { - } - - /** - * Randomly permutes the array of cards. - */ - public void shuffle() { - } - - /** - * Finds the index of the lowest card - * between low and high inclusive. - */ - public int indexLowest(int low, int high) { - return 0; - } - - /** - * Sorts the cards (in place) using selection sort. - */ - public void selectionSort() { - } - - /** - * Returns a subset of the cards in the deck. - */ - public Deck subdeck(int low, int high) { - Deck sub = new Deck(high - low + 1); - for (int i = 0; i < sub.cards.length; i++) { - sub.cards[i] = this.cards[low + i]; - } - return sub; - } - - /** - * Combines two previously sorted subdecks. - */ - public static Deck merge(Deck d1, Deck d2) { - return null; - } - - /** - * Returns a sorted copy of the deck using merge sort. - */ - public Deck mergeSort() { - return this; - } - - /** - * Reorders the cards (in place) using insertion sort. - */ - public void insertionSort() { - } - -} +import java.util.Arrays; +import java.util.Random; + +/** + * A deck of playing cards (of fixed size). + */ +public class Deck { + + private Card[] cards; + public static final Random ran = new Random(); + + /** + * Constructs a standard deck of 52 cards. + */ + public Deck() { + this.cards = new Card[52]; + int index = 0; + for (int suit = 0; suit <= 3; suit++) { + for (int rank = 1; rank <= 13; rank++) { + this.cards[index] = new Card(rank, suit); + index++; + } + } + } + + /** + * Constructs a deck of n cards (null). + */ + public Deck(int n) { + this.cards = new Card[n]; + } + + /** + * Gets the internal cards array. + */ + public Card[] getCards() { + return this.cards; + } + + /** + * Displays each of the cards in the deck. + */ + public void print() { + for (int i = 0; i < this.cards.length; i++) { + System.out.println(this.cards[i]); + } + } + + /** + * Returns a string representation of the deck. + */ + public String toString() { + StringBuilder str = new StringBuilder(); + for (int i = 0; i < this.cards.length; i++) { + str.append(this.cards[i].toString()); + if (i < this.cards.length - 1) { + str.append("\n"); + } + } + return str.toString(); + } + + /** + * Chooses a random number between low and high, including both. + */ + public int randomInt(int low, int high) { + int diff = high - low + 1; + int random = ran.nextInt(diff); + return low + random; + } + + /** + * Swaps the cards at indexes i and j. + */ + public void swapCards(int i, int j) { + Card cardi = this.cards[i]; + Card cardj = this.cards[j]; + this.cards[i] = cardj; + this.cards[j] = cardi; + } + + /** + * Randomly permutes the array of cards. + */ + public void shuffle() { + for (int i = 0; i < this.cards.length; i++) { + int random = randomInt(i, this.cards.length - 1); + swapCards(i, random); + } + } + + /** + * Finds the index of the lowest card + * between low and high inclusive. + */ + public int indexLowest(int low, int high) { + int lowIndex = low; + for (int i = low; i <= high; i++) { + if (this.cards[i].compareTo(this.cards[lowIndex]) == -1) { + lowIndex = i; + } + } + return lowIndex; + } + + /** + * Sorts the cards (in place) using selection sort. + */ + public void selectionSort() { + int lowIndex = 0; + for (int i = 0; i < this.cards.length - 1; i++) { + lowIndex = indexLowest(i, this.cards.length - 1); + swapCards(i, lowIndex); + } + } + + /** + * Returns a subset of the cards in the deck. + */ + public Deck subdeck(int low, int high) { + Deck sub = new Deck(high - low + 1); + for (int i = 0; i < sub.cards.length; i++) { + sub.cards[i] = this.cards[low + i]; + } + return sub; + } + + /** + * Combines two previously sorted subdecks. + */ + public static Deck merge(Deck d1, Deck d2) { + Deck merged = new Deck(d1.cards.length + d2.cards.length); + int i = 0; + int j = 0; + for (int k = 0; k < merged.cards.length; k++) { + if (i >= d1.cards.length) { + merged.cards[k] = d2.cards[j]; + j++; + } else if (j >= d2.cards.length) { + merged.cards[k] = d1.cards[i]; + i++; + } else { + if (d1.cards[i].compareTo(d2.cards[j]) == -1) { + merged.cards[k] = d1.cards[i]; + i++; + } else { + merged.cards[k] = d2.cards[j]; + j++; + } + } + } + return merged; + } + + /** + * Returns a sorted copy of the deck using merge sort. + */ + public Deck mergeSort() { + if (this.cards.length <= 1) { + return this; + } + int midIndex = this.cards.length / 2; + Deck deck1 = this.subdeck(0, midIndex - 1); + Deck deck2 = this.subdeck(midIndex, this.cards.length - 1); + deck1 = deck1.mergeSort(); + deck2 = deck2.mergeSort(); + Deck merged = merge(deck1, deck2); + return merged; + } + + /** + * Reorders the cards (in place) using insertion sort. + */ + public void insertionSort() { + for (int i = 1; i < this.cards.length; i++) { + for (int j = i; j > 0 && this.cards[j].compareTo(this.cards[j - 1]) == -1; j--) { + swapCards(j, j - 1); + } + } + } + +} diff --git a/ch13/Test.java b/ch13/Test.java index 5f49ef1..580b2df 100644 --- a/ch13/Test.java +++ b/ch13/Test.java @@ -1,43 +1,43 @@ -/** - * Test sorting algorithms for decks of cards. - */ -public class Test { - - /** - * Checks that the deck is sorted. - */ - public static void checkSorted(Deck deck) { - Card[] cards = deck.getCards(); - for (int i = 0; i < cards.length - 1; i++) { - if (cards[i].compareTo(cards[i + 1]) >= 0) { - System.out.println("Card #" + i + " not sorted!"); - } - } - } - - /** - * Demonstrates how to call the sorting methods. - */ - public static void main(String[] args) { - Deck deck; - - System.out.println("Testing selection..."); - deck = new Deck(); - deck.shuffle(); - deck.selectionSort(); - checkSorted(deck); - - System.out.println("Testing mergesort..."); - deck = new Deck(); - deck.shuffle(); - deck = deck.mergeSort(); - checkSorted(deck); - - System.out.println("Testing insertion..."); - deck = new Deck(); - deck.shuffle(); - deck.insertionSort(); - checkSorted(deck); - } - -} +/** + * Test sorting algorithms for decks of cards. + */ +public class Test { + + /** + * Checks that the deck is sorted. + */ + public static void checkSorted(Deck deck) { + Card[] cards = deck.getCards(); + for (int i = 0; i < cards.length - 1; i++) { + if (cards[i].compareTo(cards[i + 1]) >= 0) { + System.out.println("Card #" + i + " not sorted!"); + } + } + } + + /** + * Demonstrates how to call the sorting methods. + */ + public static void main(String[] args) { + Deck deck; + + System.out.println("Testing selection..."); + deck = new Deck(); + deck.shuffle(); + deck.selectionSort(); + checkSorted(deck); + + System.out.println("Testing mergesort..."); + deck = new Deck(); + deck.shuffle(); + deck = deck.mergeSort(); + checkSorted(deck); + + System.out.println("Testing insertion..."); + deck = new Deck(); + deck.shuffle(); + deck.insertionSort(); + checkSorted(deck); + } + +} diff --git a/ch14/Card.java b/ch14/Card.java index 1c6483e..df90cfa 120000 --- a/ch14/Card.java +++ b/ch14/Card.java @@ -1 +1,91 @@ -../ch12/Card.java \ No newline at end of file +/** + * A standard playing card. + */ +public class Card { + + public static final String[] RANKS = { + null, "Ace", "2", "3", "4", "5", "6", "7", + "8", "9", "10", "Jack", "Queen", "King"}; + + public static final String[] SUITS = { + "Clubs", "Diamonds", "Hearts", "Spades"}; + + private final int rank; + + private final int suit; + + /** + * Constructs a card of the given rank and suit. + */ + public Card(int rank, int suit) { + this.rank = rank; + this.suit = suit; + } + + /** + * Returns a negative integer if this card comes before + * the given card, zero if the two cards are equal, or + * a positive integer if this card comes after the card. + */ + public int compareTo(Card that) { + if (this.suit < that.suit) { + return -1; + } + if (this.suit > that.suit) { + return 1; + } + //in some games, Aces are ranked higher than Kings + if (this.rank == 1 && that.rank == 1) { + return 0; + } else if (this.rank == 1 && that.rank != 1) { + return 1; + } else if (this.rank != 1 && that.rank == 1) { + return -1; + } + if (this.rank < that.rank) { + return -1; + } + if (this.rank > that.rank) { + return 1; + } + return 0; + } + + /** + * Returns true if the given card has the same + * rank AND same suit; otherwise returns false. + */ + public boolean equals(Card that) { + return this.rank == that.rank + && this.suit == that.suit; + } + + /** + * Gets the card's rank. + */ + public int getRank() { + return this.rank; + } + + /** + * Gets the card's suit. + */ + public int getSuit() { + return this.suit; + } + + /** + * Returns the card's index in a sorted deck of 52 cards. + */ + public int position() { + return this.suit * 13 + this.rank - 1; + } + + /** + * Returns a string representation of the card. + */ + public String toString() { + return RANKS[this.rank] + " of " + SUITS[this.suit]; + } + +} diff --git a/ch14/CardCollection.java b/ch14/CardCollection.java index f9c3be2..f58a3bc 100644 --- a/ch14/CardCollection.java +++ b/ch14/CardCollection.java @@ -1,123 +1,123 @@ -import java.util.ArrayList; -import java.util.Random; - -/** - * A collection of playing cards. - */ -public class CardCollection { - - private String label; - private ArrayList cards; - - /** - * Constructs an empty collection. - */ - public CardCollection(String label) { - this.label = label; - this.cards = new ArrayList(); - } - - /** - * Returns the label of the card collection. - */ - public String getLabel() { - return label; - } - - /** - * Adds the given card to the collection. - */ - public void addCard(Card card) { - cards.add(card); - } - - /** - * Removes and returns the card with the given index. - */ - public Card popCard(int i) { - return cards.remove(i); - } - - /** - * Removes and returns the last card. - */ - public Card popCard() { - int i = size() - 1; - return popCard(i); - } - - /** - * Returns the number of cards. - */ - public int size() { - return cards.size(); - } - - /** - * True if the collection is empty, false otherwise. - */ - public boolean empty() { - return cards.size() == 0; - } - - /** - * Moves n cards from this collection to the given collection. - */ - public void deal(CardCollection that, int n) { - for (int i = 0; i < n; i++) { - Card card = popCard(); - that.addCard(card); - } - } - - /** - * Moves all remaining cards to the given collection. - */ - public void dealAll(CardCollection that) { - int n = size(); - deal(that, n); - } - - /** - * Returns the card with the given index. - */ - public Card getCard(int i) { - return cards.get(i); - } - - /** - * Returns the last card. - */ - public Card last() { - int i = size() - 1; - return cards.get(i); - } - - /** - * Swaps the cards at indexes i and j. - */ - public void swapCards(int i, int j) { - Card temp = cards.get(i); - cards.set(i, cards.get(j)); - cards.set(j, temp); - } - - /** - * Randomly permute the cards. - */ - public void shuffle() { - Random random = new Random(); - for (int i = size() - 1; i > 0; i--) { - int j = random.nextInt(i); - swapCards(i, j); - } - } - - /** - * Returns a string representation of the card collection. - */ - public String toString() { - return label + ": " + cards.toString(); - } - -} +import java.util.ArrayList; +import java.util.Random; + +/** + * A collection of playing cards. + */ +public class CardCollection { + + private String label; + private ArrayList cards; + + /** + * Constructs an empty collection. + */ + public CardCollection(String label) { + this.label = label; + this.cards = new ArrayList(); + } + + /** + * Returns the label of the card collection. + */ + public String getLabel() { + return label; + } + + /** + * Adds the given card to the collection. + */ + public void addCard(Card card) { + cards.add(card); + } + + /** + * Removes and returns the card with the given index. + */ + public Card popCard(int i) { + return cards.remove(i); + } + + /** + * Removes and returns the last card. + */ + public Card popCard() { + int i = size() - 1; + return popCard(i); + } + + /** + * Returns the number of cards. + */ + public int size() { + return cards.size(); + } + + /** + * True if the collection is empty, false otherwise. + */ + public boolean empty() { + return cards.size() == 0; + } + + /** + * Moves n cards from this collection to the given collection. + */ + public void deal(CardCollection that, int n) { + for (int i = 0; i < n; i++) { + Card card = popCard(); + that.addCard(card); + } + } + + /** + * Moves all remaining cards to the given collection. + */ + public void dealAll(CardCollection that) { + int n = size(); + deal(that, n); + } + + /** + * Returns the card with the given index. + */ + public Card getCard(int i) { + return cards.get(i); + } + + /** + * Returns the last card. + */ + public Card last() { + int i = size() - 1; + return cards.get(i); + } + + /** + * Swaps the cards at indexes i and j. + */ + public void swapCards(int i, int j) { + Card temp = cards.get(i); + cards.set(i, cards.get(j)); + cards.set(j, temp); + } + + /** + * Randomly permute the cards. + */ + public void shuffle() { + Random random = new Random(); + for (int i = size() - 1; i > 0; i--) { + int j = random.nextInt(i); + swapCards(i, j); + } + } + + /** + * Returns a string representation of the card collection. + */ + public String toString() { + return label + ": " + cards.toString(); + } + +} diff --git a/ch14/Deck.java b/ch14/Deck.java index 8db1814..edc035a 100644 --- a/ch14/Deck.java +++ b/ch14/Deck.java @@ -1,19 +1,19 @@ -/** - * A deck of playing cards. - */ -public class Deck extends CardCollection { - - /** - * Constructs a standard deck of 52 cards. - */ - public Deck(String label) { - super(label); - - for (int suit = 0; suit <= 3; suit++) { - for (int rank = 1; rank <= 13; rank++) { - addCard(new Card(rank, suit)); - } - } - } - -} +/** + * A deck of playing cards. + */ +public class Deck extends CardCollection { + + /** + * Constructs a standard deck of 52 cards. + */ + public Deck(String label) { + super(label); + + for (int suit = 0; suit <= 3; suit++) { + for (int rank = 1; rank <= 13; rank++) { + addCard(new Card(rank, suit)); + } + } + } + +} diff --git a/ch14/Eights.java b/ch14/Eights.java index 13b7961..9832e0f 100644 --- a/ch14/Eights.java +++ b/ch14/Eights.java @@ -1,145 +1,163 @@ -import java.util.Scanner; - -/** - * Simulates a game of Crazy Eights. See - * https://en.wikipedia.org/wiki/Crazy_Eights - * for basic play and scoring rules. - */ -public class Eights { - - private Player one; - private Player two; - private Hand drawPile; - private Hand discardPile; - private Scanner in; - - /** - * Initializes the state of the game. - */ - public Eights() { - Deck deck = new Deck("Deck"); - deck.shuffle(); - - // deal cards to each player - int handSize = 5; - one = new Player("Allen"); - deck.deal(one.getHand(), handSize); - - two = new Player("Chris"); - deck.deal(two.getHand(), handSize); - - // turn one card face up - discardPile = new Hand("Discards"); - deck.deal(discardPile, 1); - - // put the rest of the deck face down - drawPile = new Hand("Draw pile"); - deck.dealAll(drawPile); - - // create the scanner we'll use to wait for the user - in = new Scanner(System.in); - } - - /** - * Returns true if either hand is empty. - */ - public boolean isDone() { - return one.getHand().empty() || two.getHand().empty(); - } - - /** - * Moves cards from the discard pile to the draw pile and shuffles. - */ - public void reshuffle() { - // save the top card - Card prev = discardPile.popCard(); - - // move the rest of the cards - discardPile.dealAll(drawPile); - - // put the top card back - discardPile.addCard(prev); - - // shuffle the draw pile - drawPile.shuffle(); - } - - /** - * Returns a card from the draw pile. - */ - public Card draw() { - if (drawPile.empty()) { - reshuffle(); - } - return drawPile.popCard(); - } - - /** - * Switches players. - */ - public Player nextPlayer(Player current) { - if (current == one) { - return two; - } else { - return one; - } - } - - /** - * Displays the state of the game. - */ - public void displayState() { - one.display(); - two.display(); - discardPile.display(); - System.out.print("Draw pile: "); - System.out.println(drawPile.size() + " cards"); - } - - /** - * Waits for the user to press enter. - */ - public void waitForUser() { - in.nextLine(); - } - - /** - * One player takes a turn. - */ - public void takeTurn(Player player) { - Card prev = discardPile.last(); - Card next = player.play(this, prev); - discardPile.addCard(next); - - System.out.println(player.getName() + " plays " + next); - System.out.println(); - } - - /** - * Plays the game. - */ - public void playGame() { - Player player = one; - - // keep playing until there's a winner - while (!isDone()) { - displayState(); - waitForUser(); - takeTurn(player); - player = nextPlayer(player); - } - - // display the final score - one.displayScore(); - two.displayScore(); - } - - /** - * Creates the game and runs it. - */ - public static void main(String[] args) { - Eights game = new Eights(); - game.playGame(); - } - -} +import java.util.Scanner; + +/** + * Simulates a game of Crazy Eights. See + * https://en.wikipedia.org/wiki/Crazy_Eights + * for basic play and scoring rules. + */ +public class Eights { + + private Genius one; + private Player two; + private Hand drawPile; + private Hand discardPile; + private Scanner in; + + /** + * Initializes the state of the game. + */ + public Eights() { + Deck deck = new Deck("Deck"); + deck.shuffle(); + + // deal cards to each player + int handSize = 5; + one = new Genius("Allen"); + deck.deal(one.getHand(), handSize); + + two = new Player("Chris"); + deck.deal(two.getHand(), handSize); + + // turn one card face up + discardPile = new Hand("Discards"); + deck.deal(discardPile, 1); + + // put the rest of the deck face down + drawPile = new Hand("Draw pile"); + deck.dealAll(drawPile); + + // create the scanner we'll use to wait for the user + in = new Scanner(System.in); + } + + /** + * Returns true if either hand is empty. + */ + public boolean isDone() { + return one.getHand().empty() || two.getHand().empty(); + } + + /** + * Moves cards from the discard pile to the draw pile and shuffles. + */ + public void reshuffle() { + // save the top card + Card prev = discardPile.popCard(); + + // move the rest of the cards + discardPile.dealAll(drawPile); + + // put the top card back + discardPile.addCard(prev); + + // shuffle the draw pile + drawPile.shuffle(); + } + + /** + * Returns a card from the draw pile. + */ + public Card draw() { + if (drawPile.empty()) { + reshuffle(); + } + return drawPile.popCard(); + } + + /** + * Switches players. + */ + public Player nextPlayer(Player current) { + if (current == one) { + return two; + } else { + return one; + } + } + + /** + * Displays the state of the game. + */ + public void displayState() { + one.display(); + two.display(); + discardPile.display(); + System.out.print("Draw pile: "); + System.out.println(drawPile.size() + " cards"); + } + + /** + * Waits for the user to press enter. + */ + public void waitForUser() { + in.nextLine(); + } + + /** + * One player takes a turn. + */ + public void takeTurn(Player player) { + Card prev = discardPile.last(); + Card next = player.play(this, prev); + discardPile.addCard(next); + + //System.out.println(player.getName() + " plays " + next); + //System.out.println(); + } + + /** + * Plays the game. + */ + public int[] playGame() { + Player player = one; + int[] scores = new int[2]; + + // keep playing until there's a winner + while (!isDone()) { + //displayState(); + //waitForUser(); + takeTurn(player); + player = nextPlayer(player); + } + + scores[0] = one.score(); + scores[1] = two.score(); + // display the final score + //one.displayScore(); + //two.displayScore(); + return scores; + } + + /** + * Creates the game and runs it. + */ + public static void main(String[] args) { + int[] scores = new int[2]; + int geniusWins = 0; + int playerWins = 0; + + for (int i = 0; i < 100; i++) { + Eights game = new Eights(); + scores = game.playGame(); + if (scores[0] == 0) { + geniusWins++; + } else { + playerWins++; + } + } + + System.out.printf("Genius won %d times.\n", geniusWins); + System.out.printf("Player won %d times.\n", playerWins); + } + +} diff --git a/ch14/Genius.java b/ch14/Genius.java new file mode 100644 index 0000000..102e3a1 --- /dev/null +++ b/ch14/Genius.java @@ -0,0 +1,66 @@ +public class Genius extends Player { + + /** + * Constructs Genius using Player constructor. + */ + public Genius(String name) { + super(name); + } + + /** + * Removes and returns a legal card from the player's hand. + */ + public Card play(Eights eights, Card prev) { + Card card = searchForMatch(prev); + if (card == null) { + card = drawForMatch(eights, prev); + } + return card; + } + + /** + * Searches the player's hand for a matching card. + */ + public Card searchForMatch(Card prev) { + int[] indexWorks = new int[getHand().size()]; + + //Searches for an 8 first, since these cost the most points at the end of the game. + for (int i = 0; i < getHand().size(); i++) { + Card card = getHand().getCard(i); + if (card.getRank() == 8) { + return getHand().popCard(i); + } + } + + //Searches for the highest rank that works. + Card chosenCard = new Card(0, 0); + int index = -1; + for (int i = 0; i < getHand().size(); i++) { + Card card = getHand().getCard(i); + if (cardMatches(card, prev) && card.getRank() > chosenCard.getRank()) { + chosenCard = card; + index = i; + } + } + + if (index != -1) { + return getHand().popCard(index); + } else { + return null; + } + } + + /** + * Draws cards until a match is found. + */ + public Card drawForMatch(Eights eights, Card prev) { + while (true) { + Card card = eights.draw(); + //System.out.println(getName() + " draws " + card); + if (cardMatches(card, prev)) { + return card; + } + getHand().addCard(card); + } + } +} \ No newline at end of file diff --git a/ch14/Hand.java b/ch14/Hand.java index 8089a49..b1fc7e8 100644 --- a/ch14/Hand.java +++ b/ch14/Hand.java @@ -1,24 +1,24 @@ -/** - * A hand of playing cards. - */ -public class Hand extends CardCollection { - - /** - * Constructs an empty hand. - */ - public Hand(String label) { - super(label); - } - - /** - * Prints the label and cards. - */ - public void display() { - System.out.println(getLabel() + ": "); - for (int i = 0; i < size(); i++) { - System.out.println(getCard(i)); - } - System.out.println(); - } - -} +/** + * A hand of playing cards. + */ +public class Hand extends CardCollection { + + /** + * Constructs an empty hand. + */ + public Hand(String label) { + super(label); + } + + /** + * Prints the label and cards. + */ + public void display() { + System.out.println(getLabel() + ": "); + for (int i = 0; i < size(); i++) { + System.out.println(getCard(i)); + } + System.out.println(); + } + +} diff --git a/ch14/Player.java b/ch14/Player.java index 433ff28..9b55f3f 100644 --- a/ch14/Player.java +++ b/ch14/Player.java @@ -1,118 +1,118 @@ -/** - * A player in a game of crazy eights. - */ -public class Player { - - private String name; - private Hand hand; - - /** - * Constructs a player with an empty hand. - */ - public Player(String name) { - this.name = name; - this.hand = new Hand(name); - } - - /** - * Gets the player's name. - */ - public String getName() { - return name; - } - - /** - * Gets the player's hand. - */ - public Hand getHand() { - return hand; - } - - /** - * Removes and returns a legal card from the player's hand. - */ - public Card play(Eights eights, Card prev) { - Card card = searchForMatch(prev); - if (card == null) { - card = drawForMatch(eights, prev); - } - return card; - } - - /** - * Searches the player's hand for a matching card. - */ - public Card searchForMatch(Card prev) { - for (int i = 0; i < hand.size(); i++) { - Card card = hand.getCard(i); - if (cardMatches(card, prev)) { - return hand.popCard(i); - } - } - return null; - } - - /** - * Draws cards until a match is found. - */ - public Card drawForMatch(Eights eights, Card prev) { - while (true) { - Card card = eights.draw(); - System.out.println(name + " draws " + card); - if (cardMatches(card, prev)) { - return card; - } - hand.addCard(card); - } - } - - /** - * Checks whether two cards match. - */ - public static boolean cardMatches(Card card1, Card card2) { - if (card1.getSuit() == card2.getSuit()) { - return true; - } - if (card1.getRank() == card2.getRank()) { - return true; - } - if (card1.getRank() == 8) { - return true; - } - return false; - } - - /** - * Calculates the player's score (penalty points). - */ - public int score() { - int sum = 0; - for (int i = 0; i < hand.size(); i++) { - Card card = hand.getCard(i); - int rank = card.getRank(); - if (rank == 8) { - sum -= 20; - } else if (rank > 10) { - sum -= 10; - } else { - sum -= rank; - } - } - return sum; - } - - /** - * Displays the player's hand. - */ - public void display() { - hand.display(); - } - - /** - * Displays the player's name and score. - */ - public void displayScore() { - System.out.println(name + " has " + score() + " points"); - } - -} +/** + * A player in a game of crazy eights. + */ +public class Player { + + private String name; + private Hand hand; + + /** + * Constructs a player with an empty hand. + */ + public Player(String name) { + this.name = name; + this.hand = new Hand(name); + } + + /** + * Gets the player's name. + */ + public String getName() { + return name; + } + + /** + * Gets the player's hand. + */ + public Hand getHand() { + return hand; + } + + /** + * Removes and returns a legal card from the player's hand. + */ + public Card play(Eights eights, Card prev) { + Card card = searchForMatch(prev); + if (card == null) { + card = drawForMatch(eights, prev); + } + return card; + } + + /** + * Searches the player's hand for a matching card. + */ + public Card searchForMatch(Card prev) { + for (int i = 0; i < hand.size(); i++) { + Card card = hand.getCard(i); + if (cardMatches(card, prev)) { + return hand.popCard(i); + } + } + return null; + } + + /** + * Draws cards until a match is found. + */ + public Card drawForMatch(Eights eights, Card prev) { + while (true) { + Card card = eights.draw(); + //System.out.println(name + " draws " + card); + if (cardMatches(card, prev)) { + return card; + } + hand.addCard(card); + } + } + + /** + * Checks whether two cards match. + */ + public static boolean cardMatches(Card card1, Card card2) { + if (card1.getSuit() == card2.getSuit()) { + return true; + } + if (card1.getRank() == card2.getRank()) { + return true; + } + if (card1.getRank() == 8) { + return true; + } + return false; + } + + /** + * Calculates the player's score (penalty points). + */ + public int score() { + int sum = 0; + for (int i = 0; i < hand.size(); i++) { + Card card = hand.getCard(i); + int rank = card.getRank(); + if (rank == 8) { + sum -= 20; + } else if (rank > 10) { + sum -= 10; + } else { + sum -= rank; + } + } + return sum; + } + + /** + * Displays the player's hand. + */ + public void display() { + hand.display(); + } + + /** + * Displays the player's name and score. + */ + public void displayScore() { + System.out.println(name + " has " + score() + " points"); + } + +} diff --git a/ch14/Test.java b/ch14/Test.java index 274710c..e82bfdb 100644 --- a/ch14/Test.java +++ b/ch14/Test.java @@ -1,20 +1,20 @@ -/** - * Test code for Deck and Hand. - */ -public class Test { - - public static void main(String[] args) { - Deck deck = new Deck("Deck"); - deck.shuffle(); - - Hand hand = new Hand("Hand"); - deck.deal(hand, 5); - hand.display(); - - Hand drawPile = new Hand("Draw Pile"); - deck.dealAll(drawPile); - System.out.printf("Draw Pile has %d cards.\n", - drawPile.size()); - } - -} +/** + * Test code for Deck and Hand. + */ +public class Test { + + public static void main(String[] args) { + Deck deck = new Deck("Deck"); + deck.shuffle(); + + Hand hand = new Hand("Hand"); + deck.deal(hand, 5); + hand.display(); + + Hand drawPile = new Hand("Draw Pile"); + deck.dealAll(drawPile); + System.out.printf("Draw Pile has %d cards.\n", + drawPile.size()); + } + +}