From 18afb72bf3ab1d613147c84e90c032494ae813dd Mon Sep 17 00:00:00 2001 From: tfylee98 <56703109+tfylee98@users.noreply.github.com> Date: Fri, 18 Oct 2019 17:07:03 -0700 Subject: [PATCH 01/32] ch01 - 03 --- ch01/HelloWorld.java | 6 ++++++ ch02/Date.java | 16 ++++++++++++++++ ch02/Time.java | 26 ++++++++++++++++++++++++++ ch03/CelsToFahr.java | 15 +++++++++++++++ ch03/GuessStarter.java | 16 +++++++++++++--- ch03/SecondsTo.java | 17 +++++++++++++++++ 6 files changed, 93 insertions(+), 3 deletions(-) create mode 100644 ch01/HelloWorld.java create mode 100644 ch02/Date.java create mode 100644 ch02/Time.java create mode 100644 ch03/CelsToFahr.java create mode 100644 ch03/SecondsTo.java diff --git a/ch01/HelloWorld.java b/ch01/HelloWorld.java new file mode 100644 index 0000000..fac8cbe --- /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..7b2bc4d --- /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..05f1741 --- /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/ch03/CelsToFahr.java b/ch03/CelsToFahr.java new file mode 100644 index 0000000..132b980 --- /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/GuessStarter.java b/ch03/GuessStarter.java index 64984df..233dd4c 100644 --- a/ch03/GuessStarter.java +++ b/ch03/GuessStarter.java @@ -1,15 +1,25 @@ 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.println(number); + 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/SecondsTo.java b/ch03/SecondsTo.java new file mode 100644 index 0000000..ed82d33 --- /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 From 1eb06424cc92d994881e2bde2e8e8ccf5e591674 Mon Sep 17 00:00:00 2001 From: tfylee98 <56703109+tfylee98@users.noreply.github.com> Date: Mon, 21 Oct 2019 16:27:14 -0700 Subject: [PATCH 02/32] Revert "ch01 - 03" This reverts commit 18afb72bf3ab1d613147c84e90c032494ae813dd. --- ch01/HelloWorld.java | 6 ------ ch02/Date.java | 16 ---------------- ch02/Time.java | 26 -------------------------- ch03/CelsToFahr.java | 15 --------------- ch03/GuessStarter.java | 16 +++------------- ch03/SecondsTo.java | 17 ----------------- 6 files changed, 3 insertions(+), 93 deletions(-) delete mode 100644 ch01/HelloWorld.java delete mode 100644 ch02/Date.java delete mode 100644 ch02/Time.java delete mode 100644 ch03/CelsToFahr.java delete mode 100644 ch03/SecondsTo.java diff --git a/ch01/HelloWorld.java b/ch01/HelloWorld.java deleted file mode 100644 index fac8cbe..0000000 --- a/ch01/HelloWorld.java +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 7b2bc4d..0000000 --- a/ch02/Date.java +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 05f1741..0000000 --- a/ch02/Time.java +++ /dev/null @@ -1,26 +0,0 @@ -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/ch03/CelsToFahr.java b/ch03/CelsToFahr.java deleted file mode 100644 index 132b980..0000000 --- a/ch03/CelsToFahr.java +++ /dev/null @@ -1,15 +0,0 @@ -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/GuessStarter.java b/ch03/GuessStarter.java index 233dd4c..64984df 100644 --- a/ch03/GuessStarter.java +++ b/ch03/GuessStarter.java @@ -1,25 +1,15 @@ 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); + System.out.println(number); } + } diff --git a/ch03/SecondsTo.java b/ch03/SecondsTo.java deleted file mode 100644 index ed82d33..0000000 --- a/ch03/SecondsTo.java +++ /dev/null @@ -1,17 +0,0 @@ -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 From 4109083b9b110a1b6fe3e0a73a3f1e16c40b6a16 Mon Sep 17 00:00:00 2001 From: tfylee98 <56703109+tfylee98@users.noreply.github.com> Date: Mon, 21 Oct 2019 16:28:35 -0700 Subject: [PATCH 03/32] Revert "Revert "ch01 - 03"" This reverts commit 1eb06424cc92d994881e2bde2e8e8ccf5e591674. --- ch01/HelloWorld.java | 6 ++++++ ch02/Date.java | 16 ++++++++++++++++ ch02/Time.java | 26 ++++++++++++++++++++++++++ ch03/CelsToFahr.java | 15 +++++++++++++++ ch03/GuessStarter.java | 16 +++++++++++++--- ch03/SecondsTo.java | 17 +++++++++++++++++ 6 files changed, 93 insertions(+), 3 deletions(-) create mode 100644 ch01/HelloWorld.java create mode 100644 ch02/Date.java create mode 100644 ch02/Time.java create mode 100644 ch03/CelsToFahr.java create mode 100644 ch03/SecondsTo.java diff --git a/ch01/HelloWorld.java b/ch01/HelloWorld.java new file mode 100644 index 0000000..fac8cbe --- /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..7b2bc4d --- /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..05f1741 --- /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/ch03/CelsToFahr.java b/ch03/CelsToFahr.java new file mode 100644 index 0000000..132b980 --- /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/GuessStarter.java b/ch03/GuessStarter.java index 64984df..233dd4c 100644 --- a/ch03/GuessStarter.java +++ b/ch03/GuessStarter.java @@ -1,15 +1,25 @@ 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.println(number); + 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/SecondsTo.java b/ch03/SecondsTo.java new file mode 100644 index 0000000..ed82d33 --- /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 From ccb0ea979345d4e0948ff8cf2055bc553f54ab2b Mon Sep 17 00:00:00 2001 From: tfylee98 <56703109+tfylee98@users.noreply.github.com> Date: Mon, 21 Oct 2019 16:37:01 -0700 Subject: [PATCH 04/32] ch04 --- ch04/DateParam.java | 24 ++++++++++++++++++++++++ ch04/Zool.java | 9 +++++++++ 2 files changed, 33 insertions(+) create mode 100644 ch04/DateParam.java create mode 100644 ch04/Zool.java diff --git a/ch04/DateParam.java b/ch04/DateParam.java new file mode 100644 index 0000000..19d2b5c --- /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/Zool.java b/ch04/Zool.java new file mode 100644 index 0000000..16b3c0e --- /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 From 2bd036580c7c7e2932db9d8ee54f8b9b39a14faf Mon Sep 17 00:00:00 2001 From: tfylee98 <56703109+tfylee98@users.noreply.github.com> Date: Mon, 21 Oct 2019 16:37:09 -0700 Subject: [PATCH 05/32] ch05 --- ch05/BottlesOfBeer.java | 53 ++++++++++++++++++++++++++++++++++++++++ ch05/CheckFermat.java | 30 +++++++++++++++++++++++ ch05/GuessRecursive.java | 41 +++++++++++++++++++++++++++++++ 3 files changed, 124 insertions(+) create mode 100644 ch05/BottlesOfBeer.java create mode 100644 ch05/CheckFermat.java create mode 100644 ch05/GuessRecursive.java diff --git a/ch05/BottlesOfBeer.java b/ch05/BottlesOfBeer.java new file mode 100644 index 0000000..576b197 --- /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/CheckFermat.java b/ch05/CheckFermat.java new file mode 100644 index 0000000..0ab5ddb --- /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/GuessRecursive.java b/ch05/GuessRecursive.java new file mode 100644 index 0000000..a477199 --- /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 From 810750f0c087bb50a739fdf0702e48cafd2455b3 Mon Sep 17 00:00:00 2001 From: tfylee98 <56703109+tfylee98@users.noreply.github.com> Date: Mon, 21 Oct 2019 16:37:01 -0700 Subject: [PATCH 06/32] ch04 --- ch04/DateParam.java | 24 ++++++++++++++++++++++++ ch04/Zool.java | 9 +++++++++ 2 files changed, 33 insertions(+) create mode 100644 ch04/DateParam.java create mode 100644 ch04/Zool.java diff --git a/ch04/DateParam.java b/ch04/DateParam.java new file mode 100644 index 0000000..19d2b5c --- /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/Zool.java b/ch04/Zool.java new file mode 100644 index 0000000..16b3c0e --- /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 From 34ab44bd7aee65735b485ec1d0520581ebecee93 Mon Sep 17 00:00:00 2001 From: tfylee98 <56703109+tfylee98@users.noreply.github.com> Date: Mon, 21 Oct 2019 16:37:09 -0700 Subject: [PATCH 07/32] ch05 --- ch05/BottlesOfBeer.java | 53 ++++++++++++++++++++++++++++++++++++++++ ch05/CheckFermat.java | 30 +++++++++++++++++++++++ ch05/GuessRecursive.java | 41 +++++++++++++++++++++++++++++++ 3 files changed, 124 insertions(+) create mode 100644 ch05/BottlesOfBeer.java create mode 100644 ch05/CheckFermat.java create mode 100644 ch05/GuessRecursive.java diff --git a/ch05/BottlesOfBeer.java b/ch05/BottlesOfBeer.java new file mode 100644 index 0000000..576b197 --- /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/CheckFermat.java b/ch05/CheckFermat.java new file mode 100644 index 0000000..0ab5ddb --- /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/GuessRecursive.java b/ch05/GuessRecursive.java new file mode 100644 index 0000000..a477199 --- /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 From 350ec25b929d10fba45fd777d2141ceeff780852 Mon Sep 17 00:00:00 2001 From: tfylee98 <56703109+tfylee98@users.noreply.github.com> Date: Tue, 22 Oct 2019 15:31:55 -0700 Subject: [PATCH 08/32] ch06 --- ch06/Ack.class | Bin 0 -> 1447 bytes ch06/Exercise.class | Bin 0 -> 759 bytes ch06/Exercise.java | 72 +++++----- ch06/IsDivisible.class | Bin 0 -> 1133 bytes ch06/IsTriangle.class | Bin 0 -> 1306 bytes ch06/Multadd.class | Bin 0 -> 1325 bytes ch06/OddSum.class | Bin 0 -> 1208 bytes ch06/Power.class | Bin 0 -> 1388 bytes ch06/Recursive.class | Bin 0 -> 505 bytes ch06/Recursive.java | 34 ++--- ch06/Series.class | Bin 0 -> 2887 bytes ch06/Series.java | 300 ++++++++++++++++++++--------------------- ch06/TestLegal.class | Bin 0 -> 339 bytes 13 files changed, 203 insertions(+), 203 deletions(-) create mode 100644 ch06/Ack.class create mode 100644 ch06/Exercise.class create mode 100644 ch06/IsDivisible.class create mode 100644 ch06/IsTriangle.class create mode 100644 ch06/Multadd.class create mode 100644 ch06/OddSum.class create mode 100644 ch06/Power.class create mode 100644 ch06/Recursive.class create mode 100644 ch06/Series.class create mode 100644 ch06/TestLegal.class diff --git a/ch06/Ack.class b/ch06/Ack.class new file mode 100644 index 0000000000000000000000000000000000000000..66eb6b7c95be6ec5f64b7032a03432e7398b1595 GIT binary patch literal 1447 zcma)5QBxaL7(F-HupwOxP@s?yTol@bwh3*uwFyuur8Y_d4dPU-0+gojR&%AYqm=aeF^C}(!xm0rDF^awb%4Zz9*ep zA%+2rX@aK&#?!}M$!zNi6BZIkl2E-#;{Stfdamk%MUfK7lehG0q-Ni1s7cE>0%#fZJ#k&GCvklvAP@PXHU13@K)Ai+*mDSCyDL2S-EM4q1qjRGW#Rs%cwcRf2#(hZpcz2uIO1&Zl z;%lyw>&@DZ^tPOxDo+MVKF9jDv)74@nxiLlEZr;oc|%Qn%vm@l#U_^OO|L9(x*9dg z!OQBA!8Bh|h;I-GgS|%|*N+&bxC`!)xhD{h`5~~zRi^Ds9KcK( zUmqqOBAz_JiG)!xp2F1eX!0S37$=fOg-7}{e8_)80qPVHfjDsnNoR=bFvj^rZHyp` zG2CW0f^alG%EIf|XcrcDNvDsg-~YtGog>7bU^H(WVSIS9g(!7}v?Ab~5=C@3+$$=;rGKEl$1)C^<>lON2|c za7$a-7XKAa@jFR7Qfgc6r4@sZ0tBqn~(x=LJ5@OR28{!K}{0+sFx6o%1>K*4?7J<`M_ z8&%CJt7I?shT~Z{OH8bwCQ-L>35|dJ1}91CPiYg*=-SxNDp6tYd8~qTkjB0@-L`NU zS0t|5Xu=VwU%+7{kP zAbiQrs{1PNpU$R3KR)n=6P^^No}&D!`{E)EfyyBDMz5ZD(VTA$!dX1>_mobqEZ*#n zt{xpeRF1O%3ZONLTyHXJ69v)O`~vZj8-aDM`daTz+`(<3jOym@_pySUymB~fg088OlzRR$!I-^T=@rt j?vGz*uC`0mYL(`@|7*3V*k;-q^*ReJGt&}qGvn@W8rOge literal 0 HcmV?d00001 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.class b/ch06/IsDivisible.class new file mode 100644 index 0000000000000000000000000000000000000000..0da48e8096c0b9afb11e79d0a23d2110235dab44 GIT binary patch literal 1133 zcmZuw+fv$46kR6-f*7r$;9XQ59n|7H=IuQ37~Ptm$S3azOA*_$)A5eegjD0T>uh13S<>t_!znl^VC)-~W@@~u?eb$@<@utaBO+XH5L#M9;tYYC#0SOVUJO?8QwZmGXDYh+40B# literal 0 HcmV?d00001 diff --git a/ch06/IsTriangle.class b/ch06/IsTriangle.class new file mode 100644 index 0000000000000000000000000000000000000000..2180c7f75e26867bcd65c78ca7d856ed958ff2cf GIT binary patch literal 1306 zcmZuxTT|0O7(GkUCe$eRDlJG5(H1II6ugv+ilS96j&<<*U|JT4wkgx5UjB;DKJuau z)zQ%(;H!VfaXg#Gv8c^7yZv_0Ip6ud-G2M|=_`PXxD!JMGy}SY2%-Yr&zu)dw(NM@ z+4bTxS@H#G1lt?FTh10rj_1jmKy1gUugO<_-XoZp zM+$SuLKnIPbdM_n{i*cIAEkm{bG_|cCwkFmpx?p(;`>r5ysrDQLN-~Wz(5P?RJ@KzzJzyLH>E`nKcQT$J0gHWiB@fuw;U3&S`n&=*MW$J6JoV%rj!OZ}VM zyLx^KpSAp&psqx1={zK~7poscLA| zhHqj*AhSegFQvUztyOHtX6e|hvb0~i{*GOi-nPF}x1Ee#%-E$xWjtfy6s81>z+YLV z^dE!i4HKs+<1E?=G;QIm0!0E)3^SNDaNfcNTx5sy^?RYLfLYp+rRPDj;~{VRdC0Z; zpR+KBc_yLyA8h8y$eUQCWO30pafOqT(w@PRg=@G@8MjR)n#$+%iYtK|%Fs=orPQPJ z28X5UrWEK}aXq=#s1#-Go>MF{aRC_bSv!{q+g=(W#lFP0F zcm44=rH%_bI>W1?J~~(zMETD1*Dy!HF*5N1;vFXfxA<1efPqfsg>$v_0W>~@B$7i< z-y)*zB@^LfD3NSM^gV9q2q=yc4jkgUi!|MQdUzmuF^E1Sc}H$@H3F^EJ)d54Fic6NC4)y*8ydc>tSAqp)y{p2jeO@jyX?7$N@( zRzv>p^bqBC`5ETJ_ZazrG18ytO*b*A#%vR3CO_ib8|d#Qo47Quf(w5I7gX@_U%^>@ zXm~*Xh^w;^E)PVSSXKpXRb!d%fi(YjGW0*i3S^n-X=Xaj8*+}b8Jx!~3vmJSxWuC8 lnDiXeUO)kt@dQ_}iK~I9ZfHL+X2AS`exbg!wiYO@{{r323xxmx literal 0 HcmV?d00001 diff --git a/ch06/Multadd.class b/ch06/Multadd.class new file mode 100644 index 0000000000000000000000000000000000000000..aac237968653ebd33bead1dc7b7aee20c21cf07f GIT binary patch literal 1325 zcmaJ>+fEZv6kP{~8CnL)rNBYtrU)$x^{zvK0CeCC-vJnS6Gj6XH7Giopfa={nWtvL zG2Mg2*8Y)|6AbE%?b>3Fp)nTU4Wk($4PhNE&>7k;;TxtnB#iZ;$e_eB@r;DF>4-?2 z5}f!Vj1F{a=+Y5IH-olOa)g=BQ&hN!)L14%rRqG1lOJ`yxfY~;T?D^J{_JEXxuhS` zF)ZmDb6z0xJ38)G^1yc0`O#{HJQ&vzs~kAqfs`?!{%eJ0^Q)1$cpauO24+3*!FE#WQA{;g=8n)^F+r}JY(oBn8#Myb91KHv&A7rfiPVW zFmTygCSGNz7)<51dyov{1zu_}bW9`3&~?KVWKmIG=(waIcAX-=OBScSyu}b%w_R(q zRM@xt9dqBICrZJzsjesX_U6KH)+_lrYsr>iz4oI_NfqS8qUVV~_-1j#5{F(sh^U|+ z_7#>iEX$Tx7)CE=z;;i)V=GZ@tm?v&nG>FW#_+LTcMVu2T`}FfV+Et@o_Aa-CagC(+iMhQ({Zx4u#(MKBY)X&F+xMwP?=8!Oul-w&QLx;JEOg6;v3j!3K(W-mB(@o$ybMB2_1q$ zPXKK!cFdLBCkpGqtpuhSuYpqpm9J9&*y`B(GBiVpaOI$kRzr<(g{x(>UlMc@Gtff< zdx?aj6MeMLAyp&$LD>Ky{K!faJ!?^LqiH&n#+VVIMD88Dl}C7oJnxGbUA(J|xY7Rw4|q54<$b*W9FKvocz)@~BHBrT zK^mv2wIux=&5$>Mk?+O7?Q8bEZ84GU@x{x8PCcCN4hLT_L!SVxq zfd{a(^aCuv3GLY=8moAj+nMRp-Dl3vy{|t2OkpvB2%;to3o&#E^u4t=>}=U~OW8*& zZ`Eob&@tn=%C6)R=*FOCd01d5z3-LG zvd%DUA&C^}dUdk@2lm)^+!k0IqXN(FIvYw>l(c2lt2u$*QHJC-RZ_lmrR^4F{$#l< zOFFjc)n%}*WUXG2-dg+Bnq2d}iaaj^Pr8!{9ECJ7X5ko)3mj;vX(J$DRyCcnmfI8) znohBfTgqjY;~1v|cTQ@wlNQn%Di%J{PMorE8fOF&>vnBPy$|v(wX#4jb#T%`7Uu*E zml1)3=}g0}_6*vo3l=VhPAT7y3RXBw|tmPXbM*?T*DL#9a2~mnAwN+ ztF}Ci?~`k$W-;63hsDfUn87Ta&@5a0^Kr}xq@S*nMyn27Du>3iBC2FJ%H&J6p&C}- z)IQ&$TK>FcPV-(-3G^;Hu3D;BR+RtLUMcgWyAar`?;hIK=H95-`nL_H+gbnh-$b6J z+b2ZN3trt{RSS+r?P_$uq%JbX*c}n}6%Ylhg$|DM+>LS;oMWeUA-1>>xXn?A_1LMK ziEDjziU9hwFKK*2%=ny)6~DktzWL0vNcgIU;6M-Idtss)qURGkm^izG%m<8cIy-G_b^70Q5-Ht7keqD$Sm()hjY7U$FkG(fXs)ff&$;Hw(CiJ(8d7ixnv6~r zUFc?LJ|JHOqE2 zLtFPyhqR^nsbq3yVR33YGt;REMmJU5!fhI{$7q9L{1g?dH9e2+#8{OEji|;AZ$x7% z#&L&15sYi(q(Yb^U6ybnj42hJ+elIGOcF`P*N`=pmt6^&| z7K;YfDY3Ojl|B!vmD+(O5x`kOs3*JzMA3u=$_C&IMyShUJUQyZu2M~ic0PVZc;x`~ zhlq>@4{*LIT0w`1Jr%^-f)(hyXczJFsC5caB1qc-xrZc$}FMi6+9H~94UH&7FxHFk_)uDNNS?!Au9*afjczz z39>tdZe%FCh+eEBh9df4K}Q+=cte$MF^G5c`8DIhEW literal 0 HcmV?d00001 diff --git a/ch06/Recursive.class b/ch06/Recursive.class new file mode 100644 index 0000000000000000000000000000000000000000..22bcb18c7e22fe3621e8cd9992bee9d9d30bfdb5 GIT binary patch literal 505 zcmZvZ%TB^T7=_P3%h+0OBB<2suDFo3V%(URG{H-(VdJWlMh9t2N=xF~_yBBlp~i&| z;6oYzsYGMqX8yUH@64HhK0e>x0qkR2M-F)o#ej+eLuKer-S)^0Z`$Ymq3 zducooQ=dT@$I*a6wQRd(>sUseqhVkLs|>Y&ycqacI*&qPExXmDavTlFsoWKzf0hP) zKfZGNBk3Kuf@BTr`a4zjJc=a3n~nsFPU3oZr|x*J*PSShJ^w^VxbzcpPsYFwy&*@v z1M;A}DA2e@s|~7*s=E6E_DBx!GGuq5$mzBsE^g|NlC{m^@B`1f?Otkd{QV?2+ literal 0 HcmV?d00001 diff --git a/ch06/Recursive.java b/ch06/Recursive.java index f045844..9f06b29 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 result; + } + } + +} diff --git a/ch06/Series.class b/ch06/Series.class new file mode 100644 index 0000000000000000000000000000000000000000..7846524529787b0e0d50180ba30e8fd30577711d GIT binary patch literal 2887 zcmaKt-)|IE6vw}}-R{nAr`u&|%d!+)eyv-OR?6jTkcBkyj z7K*=6`~m)mMtuNc;*Xf{LP9hK8)A$PKKbIae}FOZ%@w^V z5RD+FqY?Uw<)ibiXU%YxQ=wDqK_6s0T}R4x$s6^`mNC<-AubRdC>pNkOiXNyA%Rs9 zBz3Gti@@r;xClgMC7@U$GpC?_bR^oP$=;5!7}~HVf|QQ6NHf||t87~?{Y=smO#7QC>_BDf%x({4;kK6xIen_&at5#sU%g|q+>I-2&|bg3f7=gG7ayz?M?B` z^^B57c57~^qc)Z#1U4n9=cX9eBd4PS+qk=Xrc6OXbQzMd-lt;+It8@6EpevBP;*24 zQ|9}1JRsegOrvO4iiT(Hqjb{oK^@)LMg1lW({swUQB+48md1y4JgkiNxKlDr)7J0^ z^Yer;XJw2`$u_M_-k9&y@Ibg<<01JcC3#dz(yziB(=b3~R&2ae!iRJWV4H^h0x{Dr zn?*mSaKBFh!u<*L7Vb}}7wL3Z$9{0XBLeL!keRa-Gt-^PJC*UG<;t~B%0qMQF>Y^+ zyH2sar-PAM^7%o|VYcRfY#8WL(E- zbjr894hs{M+IB}-OGRtQp0xc`4R@T7;!H_#Y$?tORc8eqMd=Y=;jvQ#t21^!W4jr5 z#wZpwu8yIo4~f* z$=Vw07~@W(PNi&G`)%pmsOr5_)-&@x;5eS^m5td$mN(_(-R3Y}jNv7`9KkEHtS<;` zSuTCMH0KnoE_IhwrSJEPYhK_=^=%6lD(DkNDbK`hIp{cr%4~0KkX17)9FNVtOSPF@fUT6jF30Qn6nr*p`xfFWz6f~y zm1ZD>sBBt%mrF+okhAO4*AV|2kz~^?G+##|9m+4Dl@sY(SSJy6KBA4g0PNiC$j!VS zt?bC{XhMavA=EYNgtLBMImSXq8=Xb9L-1=qY^x_x8k7 zHQ;W#?jm?M!4DzBJ|2~wGXU>mTBIngS;~?MFJL>B(H79v!>E@PPy+8^4eUh{j}pO# z8X&e3AzOaa5`yl_t}2;BbYV9PTzZ%{S&NBu;?FP9m`=pLKtt$8{SD4lXY?>*8=N)#2h$@jYO+VwYO+^7ThK?vZ(*;r?W>v_4CWqF zbImPyyamH8IIw_2foY`HbTlxHE|Q*F!0}-2MD6nJf$3ze>AApks@7yEQ^NwxTbN9& zTEO%*sND4>qI=poe^s@q89HA_qdc3VILR~WNjY}1XGu$WX=e9|E;h#w2~0C{1qwWa z7L<4eW|6}g7J-XC_PP;DeVk%XV;*Ik$IEyTZ}OXV6|dlPT);PY4d3A+e#RU4g_hrN z3BThq{=nP#3-5{$-WNJP5N-HSY`{k%hmZY4HX(EezxIp2(JDlQ89c{O>bS{yK3h0` Yf%$#a|Gnt{zJa%BiE;K4(eGmIzsG4Qz5oCK literal 0 HcmV?d00001 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.class b/ch06/TestLegal.class new file mode 100644 index 0000000000000000000000000000000000000000..2cf59a5d184016aeee8301135876007338cc12d8 GIT binary patch literal 339 zcmZ9Ize)o^5XQf`zux9FQNcp6NS9ccS`-^W5DqPJ#KLMXF2{z;9;|!%QZ`nKg%99E ziL-|ou$lRG<~K7R`}O_t3E&j_0s+DlQH~f1VYHG@a@I&w&u*)gS~@~yCGyXLsfuOrUHIX->^y|Um@j=l{< s$h>3L9zE=9KoGzD;}YhE82xf%&i%@Fq<5Q@{?7oxO9$NEWgTGe2PMrk Date: Tue, 22 Oct 2019 15:39:43 -0700 Subject: [PATCH 09/32] ch06 --- ch06/Ack.java | 57 +++++++++++++++++++++++++++++++++ ch06/IsDivisible.java | 41 ++++++++++++++++++++++++ ch06/IsTriangle.java | 67 +++++++++++++++++++++++++++++++++++++++ ch06/Multadd.java | 73 +++++++++++++++++++++++++++++++++++++++++++ ch06/OddSum.java | 40 ++++++++++++++++++++++++ ch06/Power.java | 50 +++++++++++++++++++++++++++++ ch06/Recursive.java | 6 ++-- ch06/TestLegal.java | 13 ++++++++ 8 files changed, 344 insertions(+), 3 deletions(-) create mode 100644 ch06/Ack.java create mode 100644 ch06/IsDivisible.java create mode 100644 ch06/IsTriangle.java create mode 100644 ch06/Multadd.java create mode 100644 ch06/OddSum.java create mode 100644 ch06/Power.java create mode 100644 ch06/TestLegal.java 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/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 9f06b29..43d2c14 100644 --- a/ch06/Recursive.java +++ b/ch06/Recursive.java @@ -8,9 +8,9 @@ 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; +// int recurse = prod(m, n - 1); +// int result = n * recurse; + return n * prod(m, n - 1); } } 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 From 4c7ad8331f8c52c4b4f75b11f7cbaabd335e4ef9 Mon Sep 17 00:00:00 2001 From: tfylee98 <56703109+tfylee98@users.noreply.github.com> Date: Tue, 22 Oct 2019 15:41:03 -0700 Subject: [PATCH 10/32] Delete Ack.class --- ch06/Ack.class | Bin 1447 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 ch06/Ack.class diff --git a/ch06/Ack.class b/ch06/Ack.class deleted file mode 100644 index 66eb6b7c95be6ec5f64b7032a03432e7398b1595..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1447 zcma)5QBxaL7(F-HupwOxP@s?yTol@bwh3*uwFyuur8Y_d4dPU-0+gojR&%AYqm=aeF^C}(!xm0rDF^awb%4Zz9*ep zA%+2rX@aK&#?!}M$!zNi6BZIkl2E-#;{Stfdamk%MUfK7lehG0q-Ni1s7cE>0%#fZJ#k&GCvklvAP@PXHU13@K)Ai+*mDSCyDL2S-EM4q1qjRGW#Rs%cwcRf2#(hZpcz2uIO1&Zl z;%lyw>&@DZ^tPOxDo+MVKF9jDv)74@nxiLlEZr;oc|%Qn%vm@l#U_^OO|L9(x*9dg z!OQBA!8Bh|h;I-GgS|%|*N+&bxC`!)xhD{h`5~~zRi^Ds9KcK( zUmqqOBAz_JiG)!xp2F1eX!0S37$=fOg-7}{e8_)80qPVHfjDsnNoR=bFvj^rZHyp` zG2CW0f^alG%EIf|XcrcDNvDsg-~YtGog>7bU^H(WVSIS9g(!7}v?Ab~5=C@3+$$=;rGKEl$1)C^<>lON2|c za7$a-7XKAa@jFR7Q Date: Tue, 22 Oct 2019 15:41:19 -0700 Subject: [PATCH 11/32] Delete Exercise.class --- ch06/Exercise.class | Bin 759 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 ch06/Exercise.class diff --git a/ch06/Exercise.class b/ch06/Exercise.class deleted file mode 100644 index 1aa8710e08b21348eeff8329579481724221d145..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 759 zcmZ`%O>fgc6r4@sZ0tBqn~(x=LJ5@OR28{!K}{0+sFx6o%1>K*4?7J<`M_ z8&%CJt7I?shT~Z{OH8bwCQ-L>35|dJ1}91CPiYg*=-SxNDp6tYd8~qTkjB0@-L`NU zS0t|5Xu=VwU%+7{kP zAbiQrs{1PNpU$R3KR)n=6P^^No}&D!`{E)EfyyBDMz5ZD(VTA$!dX1>_mobqEZ*#n zt{xpeRF1O%3ZONLTyHXJ69v)O`~vZj8-aDM`daTz+`(<3jOym@_pySUymB~fg088OlzRR$!I-^T=@rt j?vGz*uC`0mYL(`@|7*3V*k;-q^*ReJGt&}qGvn@W8rOge From 9abca2788f21eff04ae6e0b4bb0647aaff5846b4 Mon Sep 17 00:00:00 2001 From: tfylee98 <56703109+tfylee98@users.noreply.github.com> Date: Tue, 22 Oct 2019 15:41:29 -0700 Subject: [PATCH 12/32] Delete IsDivisible.class --- ch06/IsDivisible.class | Bin 1133 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 ch06/IsDivisible.class diff --git a/ch06/IsDivisible.class b/ch06/IsDivisible.class deleted file mode 100644 index 0da48e8096c0b9afb11e79d0a23d2110235dab44..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1133 zcmZuw+fv$46kR6-f*7r$;9XQ59n|7H=IuQ37~Ptm$S3azOA*_$)A5eegjD0T>uh13S<>t_!znl^VC)-~W@@~u?eb$@<@utaBO+XH5L#M9;tYYC#0SOVUJO?8QwZmGXDYh+40B# From 9a14c2a670fd96a9ea0076598f0d09c8c1a86bb9 Mon Sep 17 00:00:00 2001 From: tfylee98 <56703109+tfylee98@users.noreply.github.com> Date: Tue, 22 Oct 2019 15:41:36 -0700 Subject: [PATCH 13/32] Delete IsTriangle.class --- ch06/IsTriangle.class | Bin 1306 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 ch06/IsTriangle.class diff --git a/ch06/IsTriangle.class b/ch06/IsTriangle.class deleted file mode 100644 index 2180c7f75e26867bcd65c78ca7d856ed958ff2cf..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1306 zcmZuxTT|0O7(GkUCe$eRDlJG5(H1II6ugv+ilS96j&<<*U|JT4wkgx5UjB;DKJuau z)zQ%(;H!VfaXg#Gv8c^7yZv_0Ip6ud-G2M|=_`PXxD!JMGy}SY2%-Yr&zu)dw(NM@ z+4bTxS@H#G1lt?FTh10rj_1jmKy1gUugO<_-XoZp zM+$SuLKnIPbdM_n{i*cIAEkm{bG_|cCwkFmpx?p(;`>r5ysrDQLN-~Wz(5P?RJ@KzzJzyLH>E`nKcQT$J0gHWiB@fuw;U3&S`n&=*MW$J6JoV%rj!OZ}VM zyLx^KpSAp&psqx1={zK~7poscLA| zhHqj*AhSegFQvUztyOHtX6e|hvb0~i{*GOi-nPF}x1Ee#%-E$xWjtfy6s81>z+YLV z^dE!i4HKs+<1E?=G;QIm0!0E)3^SNDaNfcNTx5sy^?RYLfLYp+rRPDj;~{VRdC0Z; zpR+KBc_yLyA8h8y$eUQCWO30pafOqT(w@PRg=@G@8MjR)n#$+%iYtK|%Fs=orPQPJ z28X5UrWEK}aXq=#s1#-Go>MF{aRC_bSv!{q+g=(W#lFP0F zcm44=rH%_bI>W1?J~~(zMETD1*Dy!HF*5N1;vFXfxA<1efPqfsg>$v_0W>~@B$7i< z-y)*zB@^LfD3NSM^gV9q2q=yc4jkgUi!|MQdUzmuF^E1Sc}H$@H3F^EJ)d54Fic6NC4)y*8ydc>tSAqp)y{p2jeO@jyX?7$N@( zRzv>p^bqBC`5ETJ_ZazrG18ytO*b*A#%vR3CO_ib8|d#Qo47Quf(w5I7gX@_U%^>@ zXm~*Xh^w;^E)PVSSXKpXRb!d%fi(YjGW0*i3S^n-X=Xaj8*+}b8Jx!~3vmJSxWuC8 lnDiXeUO)kt@dQ_}iK~I9ZfHL+X2AS`exbg!wiYO@{{r323xxmx From 34f75f8762770c5a2fa0e383c551231f3c6de0d9 Mon Sep 17 00:00:00 2001 From: tfylee98 <56703109+tfylee98@users.noreply.github.com> Date: Tue, 22 Oct 2019 15:41:44 -0700 Subject: [PATCH 14/32] Delete Multadd.class --- ch06/Multadd.class | Bin 1325 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 ch06/Multadd.class diff --git a/ch06/Multadd.class b/ch06/Multadd.class deleted file mode 100644 index aac237968653ebd33bead1dc7b7aee20c21cf07f..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1325 zcmaJ>+fEZv6kP{~8CnL)rNBYtrU)$x^{zvK0CeCC-vJnS6Gj6XH7Giopfa={nWtvL zG2Mg2*8Y)|6AbE%?b>3Fp)nTU4Wk($4PhNE&>7k;;TxtnB#iZ;$e_eB@r;DF>4-?2 z5}f!Vj1F{a=+Y5IH-olOa)g=BQ&hN!)L14%rRqG1lOJ`yxfY~;T?D^J{_JEXxuhS` zF)ZmDb6z0xJ38)G^1yc0`O#{HJQ&vzs~kAqfs`?!{%eJ0^Q)1$cpauO24+3*!FE#WQA{;g=8n)^F+r}JY(oBn8#Myb91KHv&A7rfiPVW zFmTygCSGNz7)<51dyov{1zu_}bW9`3&~?KVWKmIG=(waIcAX-=OBScSyu}b%w_R(q zRM@xt9dqBICrZJzsjesX_U6KH)+_lrYsr>iz4oI_NfqS8qUVV~_-1j#5{F(sh^U|+ z_7#>iEX$Tx7)CE=z;;i)V=GZ@tm?v&nG>FW#_+LTcMVu2T`}FfV+Et@o_Aa-CagC(+iMhQ({Zx4u#(MKBY)X&F+xMwP?=8!Oul-w&QLx;JEOg6;v3j!3K(W-mB(@o$ybMB2_1q$ zPXKK!cFdLBCkpGqtpuhSuYpqpm9J9&*y`B(GBiVpaOI$kRzr<(g{x(>UlMc@Gtff< zdx?aj6MeMLAyp&$LD>Ky{K!faJ!?^LqiH&n#+VVIMD88Dl}C7oJnxGbUA(J|xY7Rw4|q54<$b*W9FKvocz)@~BHBrT zK^mv2wIux=&5$> Date: Tue, 22 Oct 2019 15:41:52 -0700 Subject: [PATCH 15/32] Delete OddSum.class --- ch06/OddSum.class | Bin 1208 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 ch06/OddSum.class diff --git a/ch06/OddSum.class b/ch06/OddSum.class deleted file mode 100644 index 33bd5e6b7e1e79097da9b747e4aa810a0229619d..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1208 zcmZuw+foxj6zoYhYzWI$MMyvg6->Mk?+O7?Q8bEZ84GU@x{x8PCcCN4hLT_L!SVxq zfd{a(^aCuv3GLY=8moAj+nMRp-Dl3vy{|t2OkpvB2%;to3o&#E^u4t=>}=U~OW8*& zZ`Eob&@tn=%C6)R=*FOCd01d5z3-LG zvd%DUA&C^}dUdk@2lm)^+!k0IqXN(FIvYw>l(c2lt2u$*QHJC-RZ_lmrR^4F{$#l< zOFFjc)n%}*WUXG2-dg+Bnq2d}iaaj^Pr8!{9ECJ7X5ko)3mj;vX(J$DRyCcnmfI8) znohBfTgqjY;~1v|cTQ@wlNQn%Di%J{PMorE8fOF&>vnBPy$|v(wX#4jb#T%`7Uu*E zml1)3=}g0}_6*vo3l=VhPAT7y3RXBw|tmPXbM*?T*DL#9a2~mnAwN+ ztF}Ci?~`k$W-;63hsDfUn87Ta&@5a0^Kr}xq@S*nMyn27Du>3iBC2FJ%H&J6p&C}- z)IQ&$TK>FcPV-(-3G^;Hu3D;BR+RtLUMcgWyAar`?;hIK=H95-`nL_H+gbnh-$b6J z+b2ZN3trt{RSS+r?P_$uq%JbX*c}n}6%Ylhg$|DM+>LS;oMWeUA-1>>xXn?A_1LMK ziEDjziU9hwFKK*2%=ny)6~DktzWL0vNcgIU;6M-Idtss)qURGkm^izG%m<8cIy-G_ Date: Tue, 22 Oct 2019 15:42:02 -0700 Subject: [PATCH 16/32] Delete Power.class --- ch06/Power.class | Bin 1388 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 ch06/Power.class diff --git a/ch06/Power.class b/ch06/Power.class deleted file mode 100644 index 8b358113d7d729f6cb5325e6dc82d0d68d94a013..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1388 zcmZuwO;^)E6ur|nO^K;|7DWq&uhIZg{6Yl;p+zkgL<>b^70Q5-Ht7keqD$Sm()hjY7U$FkG(fXs)ff&$;Hw(CiJ(8d7ixnv6~r zUFc?LJ|JHOqE2 zLtFPyhqR^nsbq3yVR33YGt;REMmJU5!fhI{$7q9L{1g?dH9e2+#8{OEji|;AZ$x7% z#&L&15sYi(q(Yb^U6ybnj42hJ+elIGOcF`P*N`=pmt6^&| z7K;YfDY3Ojl|B!vmD+(O5x`kOs3*JzMA3u=$_C&IMyShUJUQyZu2M~ic0PVZc;x`~ zhlq>@4{*LIT0w`1Jr%^-f)(hyXczJFsC5caB1qc-xrZc$}FMi6+9H~94UH&7FxHFk_)uDNNS?!Au9*afjczz z39>tdZe%FCh+eEBh9df4K}Q+=cte$MF^G5c`8DIhEW From 265c757633c687ede9944eb902806813b0e2d150 Mon Sep 17 00:00:00 2001 From: tfylee98 <56703109+tfylee98@users.noreply.github.com> Date: Tue, 22 Oct 2019 15:42:10 -0700 Subject: [PATCH 17/32] Delete Recursive.class --- ch06/Recursive.class | Bin 505 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 ch06/Recursive.class diff --git a/ch06/Recursive.class b/ch06/Recursive.class deleted file mode 100644 index 22bcb18c7e22fe3621e8cd9992bee9d9d30bfdb5..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 505 zcmZvZ%TB^T7=_P3%h+0OBB<2suDFo3V%(URG{H-(VdJWlMh9t2N=xF~_yBBlp~i&| z;6oYzsYGMqX8yUH@64HhK0e>x0qkR2M-F)o#ej+eLuKer-S)^0Z`$Ymq3 zducooQ=dT@$I*a6wQRd(>sUseqhVkLs|>Y&ycqacI*&qPExXmDavTlFsoWKzf0hP) zKfZGNBk3Kuf@BTr`a4zjJc=a3n~nsFPU3oZr|x*J*PSShJ^w^VxbzcpPsYFwy&*@v z1M;A}DA2e@s|~7*s=E6E_DBx!GGuq5$mzBsE^g|NlC{m^@B`1f?Otkd{QV?2+ From cc319165ecb48e4d7b45060b0890d5b5549a29bf Mon Sep 17 00:00:00 2001 From: tfylee98 <56703109+tfylee98@users.noreply.github.com> Date: Tue, 22 Oct 2019 15:42:18 -0700 Subject: [PATCH 18/32] Delete Series.class --- ch06/Series.class | Bin 2887 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 ch06/Series.class diff --git a/ch06/Series.class b/ch06/Series.class deleted file mode 100644 index 7846524529787b0e0d50180ba30e8fd30577711d..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2887 zcmaKt-)|IE6vw}}-R{nAr`u&|%d!+)eyv-OR?6jTkcBkyj z7K*=6`~m)mMtuNc;*Xf{LP9hK8)A$PKKbIae}FOZ%@w^V z5RD+FqY?Uw<)ibiXU%YxQ=wDqK_6s0T}R4x$s6^`mNC<-AubRdC>pNkOiXNyA%Rs9 zBz3Gti@@r;xClgMC7@U$GpC?_bR^oP$=;5!7}~HVf|QQ6NHf||t87~?{Y=smO#7QC>_BDf%x({4;kK6xIen_&at5#sU%g|q+>I-2&|bg3f7=gG7ayz?M?B` z^^B57c57~^qc)Z#1U4n9=cX9eBd4PS+qk=Xrc6OXbQzMd-lt;+It8@6EpevBP;*24 zQ|9}1JRsegOrvO4iiT(Hqjb{oK^@)LMg1lW({swUQB+48md1y4JgkiNxKlDr)7J0^ z^Yer;XJw2`$u_M_-k9&y@Ibg<<01JcC3#dz(yziB(=b3~R&2ae!iRJWV4H^h0x{Dr zn?*mSaKBFh!u<*L7Vb}}7wL3Z$9{0XBLeL!keRa-Gt-^PJC*UG<;t~B%0qMQF>Y^+ zyH2sar-PAM^7%o|VYcRfY#8WL(E- zbjr894hs{M+IB}-OGRtQp0xc`4R@T7;!H_#Y$?tORc8eqMd=Y=;jvQ#t21^!W4jr5 z#wZpwu8yIo4~f* z$=Vw07~@W(PNi&G`)%pmsOr5_)-&@x;5eS^m5td$mN(_(-R3Y}jNv7`9KkEHtS<;` zSuTCMH0KnoE_IhwrSJEPYhK_=^=%6lD(DkNDbK`hIp{cr%4~0KkX17)9FNVtOSPF@fUT6jF30Qn6nr*p`xfFWz6f~y zm1ZD>sBBt%mrF+okhAO4*AV|2kz~^?G+##|9m+4Dl@sY(SSJy6KBA4g0PNiC$j!VS zt?bC{XhMavA=EYNgtLBMImSXq8=Xb9L-1=qY^x_x8k7 zHQ;W#?jm?M!4DzBJ|2~wGXU>mTBIngS;~?MFJL>B(H79v!>E@PPy+8^4eUh{j}pO# z8X&e3AzOaa5`yl_t}2;BbYV9PTzZ%{S&NBu;?FP9m`=pLKtt$8{SD4lXY?>*8=N)#2h$@jYO+VwYO+^7ThK?vZ(*;r?W>v_4CWqF zbImPyyamH8IIw_2foY`HbTlxHE|Q*F!0}-2MD6nJf$3ze>AApks@7yEQ^NwxTbN9& zTEO%*sND4>qI=poe^s@q89HA_qdc3VILR~WNjY}1XGu$WX=e9|E;h#w2~0C{1qwWa z7L<4eW|6}g7J-XC_PP;DeVk%XV;*Ik$IEyTZ}OXV6|dlPT);PY4d3A+e#RU4g_hrN z3BThq{=nP#3-5{$-WNJP5N-HSY`{k%hmZY4HX(EezxIp2(JDlQ89c{O>bS{yK3h0` Yf%$#a|Gnt{zJa%BiE;K4(eGmIzsG4Qz5oCK From 01e3d4d71faa1a7f178202e6e6a996110c4e3083 Mon Sep 17 00:00:00 2001 From: tfylee98 <56703109+tfylee98@users.noreply.github.com> Date: Tue, 22 Oct 2019 15:42:26 -0700 Subject: [PATCH 19/32] Delete TestLegal.class --- ch06/TestLegal.class | Bin 339 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 ch06/TestLegal.class diff --git a/ch06/TestLegal.class b/ch06/TestLegal.class deleted file mode 100644 index 2cf59a5d184016aeee8301135876007338cc12d8..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 339 zcmZ9Ize)o^5XQf`zux9FQNcp6NS9ccS`-^W5DqPJ#KLMXF2{z;9;|!%QZ`nKg%99E ziL-|ou$lRG<~K7R`}O_t3E&j_0s+DlQH~f1VYHG@a@I&w&u*)gS~@~yCGyXLsfuOrUHIX->^y|Um@j=l{< s$h>3L9zE=9KoGzD;}YhE82xf%&i%@Fq<5Q@{?7oxO9$NEWgTGe2PMrk Date: Tue, 22 Oct 2019 15:45:24 -0700 Subject: [PATCH 20/32] ch01 --- ch01/Goodbye.java | 28 ++++++++++++++-------------- ch01/Hello.java | 16 ++++++++-------- ch01/HelloWorld.java | 12 ++++++------ 3 files changed, 28 insertions(+), 28 deletions(-) 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 index fac8cbe..ba2b85d 100644 --- a/ch01/HelloWorld.java +++ b/ch01/HelloWorld.java @@ -1,6 +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?"); - } -} +public class HelloWorld{ + public static void main(String[] args){ + System.out.println("Hello World!"); //prints Hello World! + System.out.println("What's up?"); + } +} From db868acc4c9eb044afc869ecf8f67ced28806caa Mon Sep 17 00:00:00 2001 From: tfylee98 <56703109+tfylee98@users.noreply.github.com> Date: Tue, 22 Oct 2019 15:46:02 -0700 Subject: [PATCH 21/32] ch02 --- ch02/Date.java | 30 ++++---- ch02/Time.java | 50 ++++++------- ch02/Variables.java | 166 ++++++++++++++++++++++---------------------- 3 files changed, 123 insertions(+), 123 deletions(-) diff --git a/ch02/Date.java b/ch02/Date.java index 7b2bc4d..d6ba496 100644 --- a/ch02/Date.java +++ b/ch02/Date.java @@ -1,16 +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); - } +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 index 05f1741..f328b1c 100644 --- a/ch02/Time.java +++ b/ch02/Time.java @@ -1,26 +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); - } +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 + } + +} From 4c08e85f8da4e9e2185e7d5b2171d85d0aaa19b6 Mon Sep 17 00:00:00 2001 From: tfylee98 <56703109+tfylee98@users.noreply.github.com> Date: Tue, 22 Oct 2019 15:46:46 -0700 Subject: [PATCH 22/32] ch03 --- ch03/CelsToFahr.java | 28 +++++++++++----------- ch03/Convert.java | 54 +++++++++++++++++++++--------------------- ch03/Echo.java | 36 ++++++++++++++-------------- ch03/GuessStarter.java | 50 +++++++++++++++++++------------------- ch03/Input.java | 32 ++++++++++++------------- ch03/ScannerBug.java | 52 ++++++++++++++++++++-------------------- ch03/SecondsTo.java | 32 ++++++++++++------------- 7 files changed, 142 insertions(+), 142 deletions(-) diff --git a/ch03/CelsToFahr.java b/ch03/CelsToFahr.java index 132b980..c6560bf 100644 --- a/ch03/CelsToFahr.java +++ b/ch03/CelsToFahr.java @@ -1,15 +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); - } +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 233dd4c..5c9af65 100644 --- a/ch03/GuessStarter.java +++ b/ch03/GuessStarter.java @@ -1,25 +1,25 @@ -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); - } -} +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 index ed82d33..353bd0f 100644 --- a/ch03/SecondsTo.java +++ b/ch03/SecondsTo.java @@ -1,17 +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); - } +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 From 9aed07c61e76bc78d528ede6b88352510240b34b Mon Sep 17 00:00:00 2001 From: tfylee98 <56703109+tfylee98@users.noreply.github.com> Date: Tue, 22 Oct 2019 15:47:49 -0700 Subject: [PATCH 23/32] ch04 --- ch04/DateParam.java | 46 ++++++++++++++++++++-------------------- ch04/Exercise.java | 50 ++++++++++++++++++++++---------------------- ch04/Methods.java | 44 +++++++++++++++++++------------------- ch04/NewLine.java | 38 ++++++++++++++++----------------- ch04/PrintTime.java | 30 +++++++++++++------------- ch04/PrintTwice.java | 24 ++++++++++----------- ch04/Zool.java | 16 +++++++------- 7 files changed, 124 insertions(+), 124 deletions(-) diff --git a/ch04/DateParam.java b/ch04/DateParam.java index 19d2b5c..5d87a8e 100644 --- a/ch04/DateParam.java +++ b/ch04/DateParam.java @@ -1,24 +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); - } +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 index 16b3c0e..78f355a 100644 --- a/ch04/Zool.java +++ b/ch04/Zool.java @@ -1,9 +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"); - } +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 From 0a72d6db53150908ec5f27a2303f3c91e7b1ce90 Mon Sep 17 00:00:00 2001 From: tfylee98 <56703109+tfylee98@users.noreply.github.com> Date: Tue, 22 Oct 2019 15:48:34 -0700 Subject: [PATCH 24/32] ch05 --- ch05/BottlesOfBeer.java | 104 ++++++++++++++-------------- ch05/Buzz.java | 44 ++++++------ ch05/CheckFermat.java | 58 ++++++++-------- ch05/Conditional.java | 108 ++++++++++++++--------------- ch05/Exercise.java | 56 +++++++-------- ch05/GuessRecursive.java | 80 +++++++++++----------- ch05/Logarithm.java | 88 ++++++++++++------------ ch05/Recursion.java | 142 +++++++++++++++++++-------------------- 8 files changed, 340 insertions(+), 340 deletions(-) diff --git a/ch05/BottlesOfBeer.java b/ch05/BottlesOfBeer.java index 576b197..263d6fd 100644 --- a/ch05/BottlesOfBeer.java +++ b/ch05/BottlesOfBeer.java @@ -1,53 +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 - } +/** + * 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 index 0ab5ddb..b30f7ed 100644 --- a/ch05/CheckFermat.java +++ b/ch05/CheckFermat.java @@ -1,30 +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); - } +/** + * 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 index a477199..9ccca9b 100644 --- a/ch05/GuessRecursive.java +++ b/ch05/GuessRecursive.java @@ -1,41 +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); - } +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); + } + } + +} From fb835af1ed4309594c05a3b39a4d1d80406284c5 Mon Sep 17 00:00:00 2001 From: Tiffany <56703109+tfylee98@users.noreply.github.com> Date: Wed, 23 Oct 2019 16:28:22 -0700 Subject: [PATCH 25/32] ch07 --- ch07/Exercise.java | 38 ++--- ch07/FactorialIter.java | 22 +++ ch07/Gauss.java | 58 ++++++++ ch07/Loops.java | 66 ++++----- ch07/MyExp.java | 82 +++++++++++ ch07/PowerIter.java | 51 +++++++ ch07/SquareRoot.java | 59 ++++++++ ch07/Tables.java | 314 ++++++++++++++++++++-------------------- ch07/Validate.java | 108 +++++++------- 9 files changed, 535 insertions(+), 263 deletions(-) create mode 100644 ch07/FactorialIter.java create mode 100644 ch07/Gauss.java create mode 100644 ch07/MyExp.java create mode 100644 ch07/PowerIter.java create mode 100644 ch07/SquareRoot.java 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; + } + +} From 290d0df034dc03fdd3867cce4e5f6d5e47a8aab4 Mon Sep 17 00:00:00 2001 From: Tiffany <56703109+tfylee98@users.noreply.github.com> Date: Fri, 25 Oct 2019 11:13:24 -0700 Subject: [PATCH 26/32] ch08 --- ch08/AreFactors.java | 27 +++++ ch08/ArePrimeFactors.java | 84 ++++++++++++++++ ch08/ArrayExamples.java | 200 +++++++++++++++++++------------------- ch08/Fruit.java | 80 ++++++++------- ch08/Histogram.java | 118 +++++++++++----------- ch08/IndexOfMax.java | 41 ++++++++ ch08/MakeDubMus.java | 68 ++++++------- ch08/MaxInRange.java | 99 +++++++++++++++++++ ch08/PowArrayAndHist.java | 76 +++++++++++++++ ch08/Sieve.java | 55 +++++++++++ 10 files changed, 620 insertions(+), 228 deletions(-) create mode 100644 ch08/AreFactors.java create mode 100644 ch08/ArePrimeFactors.java create mode 100644 ch08/IndexOfMax.java create mode 100644 ch08/MaxInRange.java create mode 100644 ch08/PowArrayAndHist.java create mode 100644 ch08/Sieve.java 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 From 4bf0fed12b5670d815f8dd9570d53d631e2ffe9a Mon Sep 17 00:00:00 2001 From: Tiffany <56703109+tfylee98@users.noreply.github.com> Date: Tue, 29 Oct 2019 10:59:47 -0700 Subject: [PATCH 27/32] ch09 --- ch09/Exercise.java | 58 ++++++----- ch09/Format.java | 66 ++++++------- ch09/IsAbecedarian.java | 34 +++++++ ch09/IsAnagram.java | 50 ++++++++++ ch09/IsDoubloon.java | 37 +++++++ ch09/LetterHist.java | 33 +++++++ ch09/Max.java | 48 ++++----- ch09/Recurse.java | 148 +++++++++++++++++++++------- ch09/Scrabble.java | 46 +++++++++ ch09/StringsThings.java | 210 ++++++++++++++++++++-------------------- ch09/Test.java | 10 ++ 11 files changed, 522 insertions(+), 218 deletions(-) create mode 100644 ch09/IsAbecedarian.java create mode 100644 ch09/IsAnagram.java create mode 100644 ch09/IsDoubloon.java create mode 100644 ch09/LetterHist.java create mode 100644 ch09/Scrabble.java create mode 100644 ch09/Test.java 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 From 90cab32156469681d4f30b97367aa1ebbb4b863a Mon Sep 17 00:00:00 2001 From: Tiffany <56703109+tfylee98@users.noreply.github.com> Date: Tue, 29 Oct 2019 16:57:08 -0700 Subject: [PATCH 28/32] ch10 --- ch10/Big.java | 21 ++++++ ch10/PointRect.java | 180 ++++++++++++++++++++++---------------------- ch10/Pow.java | 50 ++++++------ ch10/Riddle.java | 46 +++++------ 4 files changed, 160 insertions(+), 137 deletions(-) create mode 100644 ch10/Big.java 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); + } + +} From cb645cb3a26f46437a4c710adb9ab4cde4f71d1b Mon Sep 17 00:00:00 2001 From: Tiffany <56703109+tfylee98@users.noreply.github.com> Date: Mon, 4 Nov 2019 16:42:32 -0800 Subject: [PATCH 29/32] ch11 --- ch11/Date.java | 33 +++++++ ch11/Rational.java | 81 +++++++++++++++++ ch11/Tile.java | 52 +++++++++++ ch11/Time.java | 204 +++++++++++++++++++++---------------------- ch11/TimeClient.java | 66 +++++++------- 5 files changed, 301 insertions(+), 135 deletions(-) create mode 100644 ch11/Date.java create mode 100644 ch11/Rational.java create mode 100644 ch11/Tile.java 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); + } + +} From 3481d26555e4d3f0095c2a2d70eb058a0307f602 Mon Sep 17 00:00:00 2001 From: Tiffany <56703109+tfylee98@users.noreply.github.com> Date: Thu, 7 Nov 2019 09:09:26 -0800 Subject: [PATCH 30/32] ch12 --- ch12/Card.java | 174 +++++++++++++++--------------- ch12/CardTable.java | 186 ++++++++++++++++---------------- ch12/Search.java | 253 ++++++++++++++++++++++++-------------------- 3 files changed, 325 insertions(+), 288 deletions(-) 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(); + } + +} From 73d70a7dbb852c0dfbbda16aed47c79c421e3177 Mon Sep 17 00:00:00 2001 From: Tiffany <56703109+tfylee98@users.noreply.github.com> Date: Thu, 7 Nov 2019 12:59:28 -0800 Subject: [PATCH 31/32] ch13 --- ch13/Card.java | 92 ++++++++++++++- ch13/Deck.java | 301 ++++++++++++++++++++++++++++++------------------- ch13/Test.java | 86 +++++++------- 3 files changed, 316 insertions(+), 163 deletions(-) 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); + } + +} From 4d64a444bf9803903244adb08592b1bf3bd88de6 Mon Sep 17 00:00:00 2001 From: Tiffany <56703109+tfylee98@users.noreply.github.com> Date: Mon, 18 Nov 2019 08:42:55 -0800 Subject: [PATCH 32/32] ch14 --- ch14/Card.java | 92 +++++++++++- ch14/CardCollection.java | 246 +++++++++++++++---------------- ch14/Deck.java | 38 ++--- ch14/Eights.java | 308 +++++++++++++++++++++------------------ ch14/Genius.java | 66 +++++++++ ch14/Hand.java | 48 +++--- ch14/Player.java | 236 +++++++++++++++--------------- ch14/Test.java | 40 ++--- 8 files changed, 624 insertions(+), 450 deletions(-) create mode 100644 ch14/Genius.java 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()); + } + +}