diff --git a/.github/workflows/java.yml b/.github/java.yml similarity index 100% rename from .github/workflows/java.yml rename to .github/java.yml diff --git a/.gitignore b/.gitignore index 1dbb98b..0ec6afc 100644 --- a/.gitignore +++ b/.gitignore @@ -3,4 +3,5 @@ # ignore files c4t-java.iml -.DS_Store \ No newline at end of file +.DS_Store + diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..77b1cea --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Code 4 Tomorrow + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/out/production/c4t-java/com/codefortomorrow/advanced/chapter13/examples/IterToRecursive.class b/out/production/c4t-java/com/codefortomorrow/advanced/chapter13/examples/IterToRecursive.class new file mode 100644 index 0000000..cec7621 Binary files /dev/null and b/out/production/c4t-java/com/codefortomorrow/advanced/chapter13/examples/IterToRecursive.class differ diff --git a/out/production/c4t-java/com/codefortomorrow/advanced/chapter13/practice/NegativeSum.class b/out/production/c4t-java/com/codefortomorrow/advanced/chapter13/practice/NegativeSum.class new file mode 100644 index 0000000..da16c90 Binary files /dev/null and b/out/production/c4t-java/com/codefortomorrow/advanced/chapter13/practice/NegativeSum.class differ diff --git a/out/production/c4t-java/com/codefortomorrow/advanced/chapter13/solutions/NegativeSum.class b/out/production/c4t-java/com/codefortomorrow/advanced/chapter13/solutions/NegativeSum.class new file mode 100644 index 0000000..e215d4c Binary files /dev/null and b/out/production/c4t-java/com/codefortomorrow/advanced/chapter13/solutions/NegativeSum.class differ diff --git a/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/examples/FileIO.class b/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/examples/FileIO.class new file mode 100644 index 0000000..b059c40 Binary files /dev/null and b/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/examples/FileIO.class differ diff --git a/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/examples/MyException.class b/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/examples/MyException.class new file mode 100644 index 0000000..4f62fd5 Binary files /dev/null and b/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/examples/MyException.class differ diff --git a/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/examples/Throw.class b/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/examples/Throw.class new file mode 100644 index 0000000..1cfdffd Binary files /dev/null and b/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/examples/Throw.class differ diff --git a/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/examples/Throws.class b/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/examples/Throws.class new file mode 100644 index 0000000..10fdb92 Binary files /dev/null and b/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/examples/Throws.class differ diff --git a/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/examples/TryWithResources.class b/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/examples/TryWithResources.class new file mode 100644 index 0000000..a68a77d Binary files /dev/null and b/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/examples/TryWithResources.class differ diff --git a/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/examples/UserExceptions.class b/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/examples/UserExceptions.class new file mode 100644 index 0000000..9768edc Binary files /dev/null and b/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/examples/UserExceptions.class differ diff --git a/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/examples/names.txt b/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/examples/names.txt new file mode 100644 index 0000000..0351a47 --- /dev/null +++ b/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/examples/names.txt @@ -0,0 +1,6 @@ +Susan +Jeremiah +Josh +Kati +Sher +Lin diff --git a/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/examples/names_upper.txt b/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/examples/names_upper.txt new file mode 100644 index 0000000..5e2ad34 --- /dev/null +++ b/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/examples/names_upper.txt @@ -0,0 +1,6 @@ +SUSAN +JEREMIAH +JOSH +KATI +SHER +LIN diff --git a/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/practice/Average.class b/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/practice/Average.class new file mode 100644 index 0000000..6f5f5ce Binary files /dev/null and b/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/practice/Average.class differ diff --git a/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/practice/Bank.class b/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/practice/Bank.class new file mode 100644 index 0000000..72b028b Binary files /dev/null and b/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/practice/Bank.class differ diff --git a/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/practice/numbers.txt b/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/practice/numbers.txt new file mode 100644 index 0000000..54aac38 --- /dev/null +++ b/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/practice/numbers.txt @@ -0,0 +1,100 @@ +35 +94 +16 +38 +82 +87 +52 +60 +86 +59 +72 +7 +60 +56 +63 +11 +67 +77 +67 +82 +28 +13 +100 +92 +85 +69 +75 +6 +83 +100 +76 +51 +13 +84 +59 +30 +21 +72 +15 +28 +15 +95 +87 +61 +80 +22 +45 +9 +73 +85 +85 +2 +90 +75 +60 +80 +91 +21 +80 +41 +82 +27 +48 +43 +37 +52 +78 +21 +54 +20 +15 +49 +42 +89 +63 +24 +10 +62 +44 +63 +51 +34 +36 +21 +2 +49 +64 +77 +34 +80 +7 +83 +51 +46 +11 +25 +59 +96 +21 +65 diff --git a/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/solutions/Average.class b/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/solutions/Average.class new file mode 100644 index 0000000..1513154 Binary files /dev/null and b/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/solutions/Average.class differ diff --git a/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/solutions/Bank.class b/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/solutions/Bank.class new file mode 100644 index 0000000..dc05dcc Binary files /dev/null and b/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/solutions/Bank.class differ diff --git a/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/solutions/BankAccount.class b/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/solutions/BankAccount.class new file mode 100644 index 0000000..740fa65 Binary files /dev/null and b/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/solutions/BankAccount.class differ diff --git a/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/solutions/NotEnoughMoneyException.class b/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/solutions/NotEnoughMoneyException.class new file mode 100644 index 0000000..97c1471 Binary files /dev/null and b/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/solutions/NotEnoughMoneyException.class differ diff --git a/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/solutions/numbers.txt b/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/solutions/numbers.txt new file mode 100644 index 0000000..54aac38 --- /dev/null +++ b/out/production/c4t-java/com/codefortomorrow/advanced/chapter14/solutions/numbers.txt @@ -0,0 +1,100 @@ +35 +94 +16 +38 +82 +87 +52 +60 +86 +59 +72 +7 +60 +56 +63 +11 +67 +77 +67 +82 +28 +13 +100 +92 +85 +69 +75 +6 +83 +100 +76 +51 +13 +84 +59 +30 +21 +72 +15 +28 +15 +95 +87 +61 +80 +22 +45 +9 +73 +85 +85 +2 +90 +75 +60 +80 +91 +21 +80 +41 +82 +27 +48 +43 +37 +52 +78 +21 +54 +20 +15 +49 +42 +89 +63 +24 +10 +62 +44 +63 +51 +34 +36 +21 +2 +49 +64 +77 +34 +80 +7 +83 +51 +46 +11 +25 +59 +96 +21 +65 diff --git a/src/com/codefortomorrow/advanced/chapter13/examples/IterToRecursive.java b/src/com/codefortomorrow/advanced/chapter13/examples/IterToRecursive.java new file mode 100644 index 0000000..8c9fef1 --- /dev/null +++ b/src/com/codefortomorrow/advanced/chapter13/examples/IterToRecursive.java @@ -0,0 +1,36 @@ +package com.codefortomorrow.advanced.chapter13.examples; + +// Convert the iterative gcd algorithm to a recursive algorithm. + +public class IterToRecursive { + + public static void main(String[] args) { + System.out.println("With iterative function:"); + + int a = 72, b = 20; + while (a != b) { + if (a > b) a -= b; else if (b > a) b -= a; + } + System.out.println("GCD:" + a); + + System.out.println("With recursive function:"); + System.out.println("GCD:" + gcd(72, 20)); + } + + // Recursive function + public static int power(int base, int exp) { + // Base case: exp = 0, so the result is 1. + if (exp == 0) return 1; + + // Multiply once by the previous power. + return power(base, exp - 1) * base; + } + + public static int gcd(int a, int b) { + // Base case + if (a == b) return a; else if (a > b) return gcd( + a - b, + b + ); else return gcd(a, b - a); + } +} diff --git a/src/com/codefortomorrow/advanced/chapter13/practice/NegativeSum.java b/src/com/codefortomorrow/advanced/chapter13/practice/NegativeSum.java new file mode 100644 index 0000000..aa25480 --- /dev/null +++ b/src/com/codefortomorrow/advanced/chapter13/practice/NegativeSum.java @@ -0,0 +1,32 @@ +package com.codefortomorrow.advanced.chapter13.practice; + +/* +Implement the iterative code as a recursive +function to clarify what the algorithm does. +*/ + +public class NegativeSum { + + public static void main(String[] args) { + System.out.println("Iterative:"); + int a = 50, b = 40; + while (a + b > 0) { + if (Math.pow(a, 2) + Math.pow(b, 2) > 10000) { + a *= 8; + b *= -4; + } else { + a *= 3; + b /= 2; + } + } + System.out.println("a + b: " + (a + b)); + + System.out.println("Recursive:"); + System.out.println(negSum(50, 40)); + } + + public static int negSum(int a, int b) { + // Insert code here and change return statement. + return 0; + } +} diff --git a/src/com/codefortomorrow/advanced/chapter13/solutions/NegativeSum.java b/src/com/codefortomorrow/advanced/chapter13/solutions/NegativeSum.java new file mode 100644 index 0000000..e0f2b71 --- /dev/null +++ b/src/com/codefortomorrow/advanced/chapter13/solutions/NegativeSum.java @@ -0,0 +1,35 @@ +package com.codefortomorrow.advanced.chapter13.solutions; + +/* +Implement the iterative code as a recursive +function to clarify what the algorithm does. +*/ + +public class NegativeSum { + + public static void main(String[] args) { + System.out.println("Iterative:"); + int a = 50, b = 40; + while (a + b > 0) { + if (Math.pow(a, 2) + Math.pow(b, 2) > 10000) { + a *= 8; + b *= -4; + } else { + a *= 3; + b /= 2; + } + } + System.out.println("a + b: " + (a + b)); + + System.out.println("Recursive:"); + System.out.println(negSum(50, 40)); + } + + public static int negSum(int a, int b) { + if (a + b <= 0) return a + b; + if (Math.pow(a, 2) + Math.pow(b, 2) > 10000) return negSum( + a * 8, + b * -4 + ); else return negSum(a * 3, b / 2); + } +} diff --git a/src/com/codefortomorrow/advanced/chapter14/examples/FileIO.java b/src/com/codefortomorrow/advanced/chapter14/examples/FileIO.java new file mode 100644 index 0000000..bdf5379 --- /dev/null +++ b/src/com/codefortomorrow/advanced/chapter14/examples/FileIO.java @@ -0,0 +1,27 @@ +package com.codefortomorrow.advanced.chapter14.examples; + +import java.io.*; + +public class FileIO { + + public static void main(String[] args) throws IOException { + FileInputStream in = null; + FileOutputStream out = null; + File file = new File("names.txt"); + + try { + in = new FileInputStream(file); + out = new FileOutputStream("names_upper.txt"); + int c; + while ((c = in.read()) != -1) out.write( + Character.toUpperCase((char) c) + ); + } catch (IOException e) { + System.out.println("An IO Exception occurred."); + e.printStackTrace(); // Prints error output stream. + } finally { + if (in != null) in.close(); + if (out != null) out.close(); + } + } +} diff --git a/src/com/codefortomorrow/advanced/chapter14/examples/MyException.java b/src/com/codefortomorrow/advanced/chapter14/examples/MyException.java new file mode 100644 index 0000000..f45ee55 --- /dev/null +++ b/src/com/codefortomorrow/advanced/chapter14/examples/MyException.java @@ -0,0 +1,10 @@ +package com.codefortomorrow.advanced.chapter14.examples; + +public class MyException extends Exception { + + public MyException() {} + + public MyException(String message) { + super(message); + } +} diff --git a/src/com/codefortomorrow/advanced/chapter14/examples/Throw.java b/src/com/codefortomorrow/advanced/chapter14/examples/Throw.java new file mode 100644 index 0000000..66c645f --- /dev/null +++ b/src/com/codefortomorrow/advanced/chapter14/examples/Throw.java @@ -0,0 +1,19 @@ +package com.codefortomorrow.advanced.chapter14.examples; + +public class Throw { + + public static void main(String[] args) { + try { + System.out.println(divide(7, 2)); + } catch (ArithmeticException e) { + System.out.println("There was an arithmetic exception."); + } + } + + public static int divide(int a, int b) { + int result = a / b; + if (result != (double) a / (double) b) throw new ArithmeticException(); + System.out.println("Got to end of divide()"); + return a / b; + } +} diff --git a/src/com/codefortomorrow/advanced/chapter14/examples/Throws.java b/src/com/codefortomorrow/advanced/chapter14/examples/Throws.java new file mode 100644 index 0000000..0178da9 --- /dev/null +++ b/src/com/codefortomorrow/advanced/chapter14/examples/Throws.java @@ -0,0 +1,19 @@ +package com.codefortomorrow.advanced.chapter14.examples; + +import java.io.*; + +public class Throws { + + public static void main(String[] args) { + try { + File file = null; + access(file); + } catch (IOException e) { + System.out.println("There was an IOException."); + } + } + + public static void access(File file) throws IOException { + if (file == null) throw new IOException(); + } +} diff --git a/src/com/codefortomorrow/advanced/chapter14/examples/TryWithResources.java b/src/com/codefortomorrow/advanced/chapter14/examples/TryWithResources.java new file mode 100644 index 0000000..d58d994 --- /dev/null +++ b/src/com/codefortomorrow/advanced/chapter14/examples/TryWithResources.java @@ -0,0 +1,23 @@ +package com.codefortomorrow.advanced.chapter14.examples; + +import java.io.*; + +public class TryWithResources { + + public static void main(String[] args) throws IOException { + File file = new File("names.txt"); + + try ( + FileInputStream in = new FileInputStream(file); + FileOutputStream out = new FileOutputStream("names_upper.txt") + ) { + int c; + while ((c = in.read()) != -1) out.write( + Character.toUpperCase((char) c) + ); + } catch (IOException e) { + System.out.println("An IO Exception occurred."); + e.printStackTrace(); // Prints error output stream. + } + } +} diff --git a/src/com/codefortomorrow/advanced/chapter14/examples/UserExceptions.java b/src/com/codefortomorrow/advanced/chapter14/examples/UserExceptions.java new file mode 100644 index 0000000..088fa10 --- /dev/null +++ b/src/com/codefortomorrow/advanced/chapter14/examples/UserExceptions.java @@ -0,0 +1,18 @@ +package com.codefortomorrow.advanced.chapter14.examples; + +public class UserExceptions { + + public static void main(String[] args) { + try { + call(null); + } catch (MyException e) { + System.out.println("Caught MyException"); + } + + throw new ArithmeticException("divide by zero error"); + } + + public static void call(String s) throws MyException { + if (s == null) throw new MyException(); + } +} diff --git a/src/com/codefortomorrow/advanced/chapter14/examples/names.txt b/src/com/codefortomorrow/advanced/chapter14/examples/names.txt new file mode 100644 index 0000000..0351a47 --- /dev/null +++ b/src/com/codefortomorrow/advanced/chapter14/examples/names.txt @@ -0,0 +1,6 @@ +Susan +Jeremiah +Josh +Kati +Sher +Lin diff --git a/src/com/codefortomorrow/advanced/chapter14/examples/names_upper.txt b/src/com/codefortomorrow/advanced/chapter14/examples/names_upper.txt new file mode 100644 index 0000000..5e2ad34 --- /dev/null +++ b/src/com/codefortomorrow/advanced/chapter14/examples/names_upper.txt @@ -0,0 +1,6 @@ +SUSAN +JEREMIAH +JOSH +KATI +SHER +LIN diff --git a/src/com/codefortomorrow/advanced/chapter14/practice/Account.java b/src/com/codefortomorrow/advanced/chapter14/practice/Account.java new file mode 100644 index 0000000..af685e7 --- /dev/null +++ b/src/com/codefortomorrow/advanced/chapter14/practice/Account.java @@ -0,0 +1,62 @@ +package com.codefortomorrow.advanced.chapter14.practice; + +/* +Create the following classes that simply extend the `Exception` class: + +- `InvalidUsernameException` +- `InvalidPasswordException` +- `InvalidAgeException` +- `PasswordMismatchException` + +In the `Account` class, code a method called `createAccount` that takes a `username`, `age`, +`password`, and `confirmPassword` as parameters. + +In `createAccount`, throw an: + +- `InvalidUsernameException` - if the given username is <4 or >10 characters. +- `InvalidPasswordException` - if the given password is <4 or >10 characters. +- `InvalidAgeException` - if the given age is <18. +- `PasswordMismatchException` - if the given password does not match the given confirm password. + +In your `main` method (within the `Account` class): + +- To simulate the creation of an account online, prompt the user to enter their username, age, + password, and their password again (to confirm). +- Call the `createAccount` method continuously with the user's input and use `try`/`catch` to + handle the possible exceptions and print the appropriate error message. (You can assume that + the user input will only throw at most 1 exception.) +- Keep asking the user for input until the account is created successfully. + +Example output: + +``` +Welcome to Account Creation! +Enter username (4 to 10 characters): hi +Enter age: 18 +Enter password (4 to 10 characters): thisislong +Confirm password (4 to 10 characters): thisislong +Invalid username. +Enter username (4 to 10 characters): four +Enter age: 18 +Enter password (4 to 10 characters): thisislong +Confirm password (4 to 10 characters): thisislong +Account created successfully! +``` +*/ + +public class Account { + + public static void main(String[] args) { + // Write your code here + } + + public static void createAccount( + String username, + int age, + String password, + String confirmPassword + ) { + // Write your code here + } +} +// Write exception classes here diff --git a/src/com/codefortomorrow/advanced/chapter14/practice/Average.java b/src/com/codefortomorrow/advanced/chapter14/practice/Average.java new file mode 100644 index 0000000..0309e0c --- /dev/null +++ b/src/com/codefortomorrow/advanced/chapter14/practice/Average.java @@ -0,0 +1,30 @@ +package com.codefortomorrow.advanced.chapter14.practice; + +/* +The file “numbers.txt” has 100 random numbers +(one on each line). Use file i/o to find the +average of these numbers. Write “Average: ” +and display the average on the next (101st) +line of the file. + +Hint: Just like BufferedReader and FileReader, +there are BufferedWriter and FileWriter classes +that allow you to add full words to files, +instead of just bytes. You should do a quick +Google search to explore these classes first, +but just to get you started: + +new FileWriter(“fileName.txt”, true) + +will create an instance of FileWriter, and +the “true” puts it in append mode, so you +start writing to the end of the file instead +of writing over the existing content from the beginning. +*/ + +public class Average { + + public static void main(String[] args) { + // Add code here. + } +} diff --git a/src/com/codefortomorrow/advanced/chapter14/practice/Bank.java b/src/com/codefortomorrow/advanced/chapter14/practice/Bank.java new file mode 100644 index 0000000..12ddc90 --- /dev/null +++ b/src/com/codefortomorrow/advanced/chapter14/practice/Bank.java @@ -0,0 +1,35 @@ +package com.codefortomorrow.advanced.chapter14.practice; + +/* +Create a class called BankAccount (a separate +class from your main program) that contains a +private “balance” attribute for the amount of +money in the account. + +The user should be able to set the original +balance upon initialization (through the constructor). +The class should have deposit and withdraw methods +that add and subtract money from the account. +There should also be a getter method to access +the balance, since the attribute is private. + +Create at least 2 instances of BankAccount. +Deposit, withdraw, and display the final balance of each. + +Create a NotEnoughMoneyException class that is a +checked exception. The withdraw method should throw +this exception if the user tries to withdraw an +amount that is greater than their current balance. +Handle this exception by displaying the difference +between the balance and the amount to be withdrawn, +and do this exception handling in the main program +where you have created instances of BankAccount. +*/ + +public class Bank { + + public static void main(String[] args) { + // Your code here. + } +} +// Add other classes here. diff --git a/src/com/codefortomorrow/advanced/chapter14/practice/Lexico.java b/src/com/codefortomorrow/advanced/chapter14/practice/Lexico.java new file mode 100644 index 0000000..38d9efe --- /dev/null +++ b/src/com/codefortomorrow/advanced/chapter14/practice/Lexico.java @@ -0,0 +1,19 @@ +package com.codefortomorrow.advanced.chapter14.practice; + +/* +Practice: Use File I/O to compare two files lexicographically. +Lexicographical order is very similar to alphabetical order, +except that it includes more than just lowercase alphabets. +Given two text files f1 and f2, write a program that will +compare their contents and output to the console the +title of the file which comes first lexicographically. + +Hint: Java’s String.compareTo method may be of use to you. +*/ + +public class Lexico { + + public static void main(String[] args) { + // Add code here + } +} diff --git a/src/com/codefortomorrow/advanced/chapter14/practice/account/InvalidAgeException.java b/src/com/codefortomorrow/advanced/chapter14/practice/account/InvalidAgeException.java deleted file mode 100644 index 0842368..0000000 --- a/src/com/codefortomorrow/advanced/chapter14/practice/account/InvalidAgeException.java +++ /dev/null @@ -1,3 +0,0 @@ -package com.codefortomorrow.advanced.chapter14.practice.account; - -public class InvalidAgeException {} diff --git a/src/com/codefortomorrow/advanced/chapter14/practice/account/InvalidPasswordException.java b/src/com/codefortomorrow/advanced/chapter14/practice/account/InvalidPasswordException.java deleted file mode 100644 index f6f6029..0000000 --- a/src/com/codefortomorrow/advanced/chapter14/practice/account/InvalidPasswordException.java +++ /dev/null @@ -1,3 +0,0 @@ -package com.codefortomorrow.advanced.chapter14.practice.account; - -public class InvalidPasswordException {} diff --git a/src/com/codefortomorrow/advanced/chapter14/practice/account/InvalidUsernameException.java b/src/com/codefortomorrow/advanced/chapter14/practice/account/InvalidUsernameException.java deleted file mode 100644 index 677b349..0000000 --- a/src/com/codefortomorrow/advanced/chapter14/practice/account/InvalidUsernameException.java +++ /dev/null @@ -1,3 +0,0 @@ -package com.codefortomorrow.advanced.chapter14.practice.account; - -public class InvalidUsernameException {} diff --git a/src/com/codefortomorrow/advanced/chapter14/practice/account/Main.java b/src/com/codefortomorrow/advanced/chapter14/practice/account/Main.java deleted file mode 100644 index 5dcaf7a..0000000 --- a/src/com/codefortomorrow/advanced/chapter14/practice/account/Main.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.codefortomorrow.advanced.chapter14.practice.account; - -import java.util.Scanner; - -public class Main { - - public static void main(String[] args) { - Scanner sc = new Scanner(System.in); - - System.out.println("Welcome to Account Creation!"); - while (true) { - System.out.print("Enter username (4 to 10 characters): "); - String username = sc.next(); - System.out.print("Enter age: "); - int age = sc.nextInt(); - System.out.print("Enter password (4 to 10 characters): "); - String password = sc.next(); - System.out.print("Confirm password (4 to 10 characters): "); - String confirmPassword = sc.next(); - - // TODO: try and catch to handle exceptions - createAccount(username, password, age, confirmPassword); - System.out.println("Account created successfully!"); - } - } - - public static void createAccount( - String username, - String password, - int age, - String confirmPassword - ) - throws InvalidAgeException, InvalidPasswordException, InvalidUsernameException, PasswordMismatchException { - // TODO: complete - } -} diff --git a/src/com/codefortomorrow/advanced/chapter14/practice/account/PasswordMismatchException.java b/src/com/codefortomorrow/advanced/chapter14/practice/account/PasswordMismatchException.java deleted file mode 100644 index e2f7c98..0000000 --- a/src/com/codefortomorrow/advanced/chapter14/practice/account/PasswordMismatchException.java +++ /dev/null @@ -1,3 +0,0 @@ -package com.codefortomorrow.advanced.chapter14.practice.account; - -public class PasswordMismatchException {} diff --git a/src/com/codefortomorrow/advanced/chapter14/practice/f1.txt b/src/com/codefortomorrow/advanced/chapter14/practice/f1.txt new file mode 100644 index 0000000..684900a --- /dev/null +++ b/src/com/codefortomorrow/advanced/chapter14/practice/f1.txt @@ -0,0 +1,28 @@ +All the world's a stage, +And all the men and women merely players; +They have their exits and their entrances, +And one man in his time plays many parts, +His acts being seven ages. At first, the infant, +Mewling and puking in the nurse's arms. +Then the whining schoolboy, with his satchel +And shining morning face, creeping like snail +Unwillingly to school. And then the lover, +Sighing like furnace, with a woeful ballad +Made to his mistress' eyebrow. Then a soldier, +Full of strange oaths and bearded like the pard, +Jealous in honor, sudden and quick in quarrel, +Seeking the bubble reputation +Even in the cannon's mouth. And then the justice, +In fair round belly with good capon lined, +With eyes severe and beard of formal cut, +Full of wise saws and modern instances; +And so he plays his part. The sixth age shifts +Into the lean and slippered pantaloon, +With spectacles on nose and pouch on side; +His youthful hose, well saved, a world too wide +For his shrunk shank, and his big manly voice, +Turning again toward childish treble, pipes +And whistles in his sound. Last scene of all, +That ends this strange eventful history, +Is second childishness and mere oblivion, +Sans teeth, sans eyes, sans taste, sans everything. diff --git a/src/com/codefortomorrow/advanced/chapter14/practice/f2.txt b/src/com/codefortomorrow/advanced/chapter14/practice/f2.txt new file mode 100644 index 0000000..31cf35c --- /dev/null +++ b/src/com/codefortomorrow/advanced/chapter14/practice/f2.txt @@ -0,0 +1,28 @@ +All the world's a stage, +And all the men and women merely players; +They have their exits and their entrances, +And one man in his time plays many parts, +His acts being seven ages. At first, the infant, +Mewling and puking in the nurse's arms. +Then the whining schoolboy, with his satchel +And shining morning face, creeping like snail +Unwillingly to school. And then the lover, +Sighing like furnace, with a woeful ballad +Made to his mistress' eyebrow. Then a soldier, +Full of strange oaths and bearded like the pard, +Jealous in honor, sudden and quick in quarrel, +Seeking the bubble reputation +Even in the cannon's mouth. And than the justice, +In fair round belly with good capon lined, +With eyes severe and beard of formal cut, +Full of wise saws and modern instances; +And so he plays his part. The sixth age shifts +Into the lean and slippered pantaloon, +With spectacles on nose and pouch on side; +His youthful hose, well saved, a world too wide +For his shrunk shank, and his big manly voice, +Turning again toward childish treble, pipes +And whistles in his sound. Last scene of all, +That ends this strange eventful history, +Is second childishness and mere oblivion, +Sans teeth, sans eyes, sans taste, sans everything. diff --git a/src/com/codefortomorrow/advanced/chapter14/practice/numbers.txt b/src/com/codefortomorrow/advanced/chapter14/practice/numbers.txt new file mode 100644 index 0000000..54aac38 --- /dev/null +++ b/src/com/codefortomorrow/advanced/chapter14/practice/numbers.txt @@ -0,0 +1,100 @@ +35 +94 +16 +38 +82 +87 +52 +60 +86 +59 +72 +7 +60 +56 +63 +11 +67 +77 +67 +82 +28 +13 +100 +92 +85 +69 +75 +6 +83 +100 +76 +51 +13 +84 +59 +30 +21 +72 +15 +28 +15 +95 +87 +61 +80 +22 +45 +9 +73 +85 +85 +2 +90 +75 +60 +80 +91 +21 +80 +41 +82 +27 +48 +43 +37 +52 +78 +21 +54 +20 +15 +49 +42 +89 +63 +24 +10 +62 +44 +63 +51 +34 +36 +21 +2 +49 +64 +77 +34 +80 +7 +83 +51 +46 +11 +25 +59 +96 +21 +65 diff --git a/src/com/codefortomorrow/advanced/chapter14/solutions/Account.java b/src/com/codefortomorrow/advanced/chapter14/solutions/Account.java new file mode 100644 index 0000000..2bba577 --- /dev/null +++ b/src/com/codefortomorrow/advanced/chapter14/solutions/Account.java @@ -0,0 +1,108 @@ +package com.codefortomorrow.advanced.chapter14.solutions; + +import java.util.Scanner; + +/* +Create the following classes that simply extend the `Exception` class: + +- `InvalidUsernameException` +- `InvalidPasswordException` +- `InvalidAgeException` +- `PasswordMismatchException` + +In the `Account` class, code a method called `createAccount` that takes a `username`, `age`, +`password`, and `confirmPassword` as parameters. + +In `createAccount`, throw an: + +- `InvalidUsernameException` - if the given username is <4 or >10 characters. +- `InvalidPasswordException` - if the given password is <4 or >10 characters. +- `InvalidAgeException` - if the given age is <18. +- `PasswordMismatchException` - if the given password does not match the given confirm password. + +In your `main` method (within the `Account` class): + +- To simulate the creation of an account online, prompt the user to enter their username, age, + password, and their password again (to confirm). +- Call the `createAccount` method continuously with the user's input and use `try`/`catch` to + handle the possible exceptions and print the appropriate error message. (You can assume that + the user input will only throw at most 1 exception.) +- Keep asking the user for input until the account is created successfully. + +Example output: + +``` +Welcome to Account Creation! +Enter username (4 to 10 characters): hi +Enter age: 18 +Enter password (4 to 10 characters): thisislong +Confirm password (4 to 10 characters): thisislong +Invalid username. +Enter username (4 to 10 characters): four +Enter age: 18 +Enter password (4 to 10 characters): thisislong +Confirm password (4 to 10 characters): thisislong +Account created successfully! +``` +*/ + +public class Account { + + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + + System.out.println("Welcome to Account Creation!"); + while (true) { + System.out.print("Enter username (4 to 10 characters): "); + String username = sc.next(); + System.out.print("Enter age: "); + int age = sc.nextInt(); + System.out.print("Enter password (4 to 10 characters): "); + String password = sc.next(); + System.out.print("Confirm password (4 to 10 characters): "); + String confirmPassword = sc.next(); + + try { + createAccount(username, age, password, confirmPassword); + System.out.println("Account created successfully!"); + sc.close(); + break; + } catch (InvalidUsernameException e) { + System.out.println("Invalid username."); + } catch (InvalidPasswordException e) { + System.out.println("Invalid password."); + } catch (InvalidAgeException e) { + System.out.println("Must be 18 or older to create an account."); + } catch (PasswordMismatchException e) { + System.out.println("Passwords don't match!"); + } + } + } + + public static void createAccount(String username, int age, String password, String confirmPassword) + throws InvalidAgeException, InvalidPasswordException, InvalidUsernameException, PasswordMismatchException { + if (username.length() < 4 || username.length() > 10) { + throw new InvalidUsernameException(); + } + + if (age < 18) { + throw new InvalidAgeException(); + } + + if (password.length() < 4 || password.length() > 10) { + throw new InvalidPasswordException(); + } + + if (!password.equals(confirmPassword)) { + throw new PasswordMismatchException(); + } + } +} + +class InvalidUsernameException extends Exception {} + +class InvalidPasswordException extends Exception {} + +class InvalidAgeException extends Exception {} + +class PasswordMismatchException extends Exception {} diff --git a/src/com/codefortomorrow/advanced/chapter14/solutions/Average.java b/src/com/codefortomorrow/advanced/chapter14/solutions/Average.java new file mode 100644 index 0000000..ea3e6ae --- /dev/null +++ b/src/com/codefortomorrow/advanced/chapter14/solutions/Average.java @@ -0,0 +1,52 @@ +package com.codefortomorrow.advanced.chapter14.solutions; + +import java.io.*; + +/* +The file “numbers.txt” has 100 random numbers +(one on each line). Use file i/o to find the +average of these numbers. Write “Average: ” +and display the average on the next (101st) +line of the file. + +Hint: Just like BufferedReader and FileReader, +there are BufferedWriter and FileWriter classes +that allow you to add full words to files, +instead of just bytes. You should do a quick +Google search to explore these classes first, +but just to get you started: + +new FileWriter(“fileName.txt”, true) + +will create an instance of FileWriter, and +the “true” puts it in append mode, so you +start writing to the end of the file instead +of writing over the existing content from the beginning. +*/ + +public class Average { + + public static void main(String[] args) { + File file = new File("numbers.txt"); + + // try with resources block, which closes streams automatically + try ( + BufferedReader in = new BufferedReader(new FileReader(file)); + BufferedWriter out = new BufferedWriter(new FileWriter(file, true)) + ) { + // read the numbers (String input) and find average + double average = 0; + String contentLine = in.readLine(); + while (contentLine != null) { + average += Integer.parseInt(contentLine); + contentLine = in.readLine(); + } + average /= 100.; + + // append average to end of file + out.write("Average: " + average); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/src/com/codefortomorrow/advanced/chapter14/solutions/Bank.java b/src/com/codefortomorrow/advanced/chapter14/solutions/Bank.java new file mode 100644 index 0000000..5c6079f --- /dev/null +++ b/src/com/codefortomorrow/advanced/chapter14/solutions/Bank.java @@ -0,0 +1,86 @@ +package com.codefortomorrow.advanced.chapter14.solutions; + +/* +Create a class called BankAccount (a separate +class from your main program) that contains a +private “balance” attribute for the amount of +money in the account. + +The user should be able to set the original +balance upon initialization (through the constructor). +The class should have deposit and withdraw methods +that add and subtract money from the account. +There should also be a getter method to access +the balance, since the attribute is private. + +Create at least 2 instances of BankAccount. +Deposit, withdraw, and display the final balance of each. + +Create a NotEnoughMoneyException class that is a +checked exception. The withdraw method should throw +this exception if the user tries to withdraw an +amount that is greater than their current balance. +Handle this exception by displaying the difference +between the balance and the amount to be withdrawn, +and do this exception handling in the main program +where you have created instances of BankAccount. +*/ + +public class Bank { + + public static void main(String[] args) { + BankAccount account1 = new BankAccount(500); + BankAccount account2 = new BankAccount(1000); + + account1.deposit(200); + withdraw(account1, 300); + System.out.printf("Account 1 Balance: $%.2f\n", account1.getBalance()); + + account2.deposit(200); + withdraw(account2, 1500); + System.out.printf("Account 2 Balance: $%.2f\n", account2.getBalance()); + } + + public static void withdraw(BankAccount account, double amount) { + try { + account.withdraw(amount); + } catch (NotEnoughMoneyException e) { + System.out.println(e.getMessage()); + } + } +} + +class BankAccount { + + private double balance; + + public BankAccount(double balance) { + this.balance = balance; + } + + public void deposit(double amount) { + if (amount > 0) { + balance += amount; + } + } + + public void withdraw(double amount) throws NotEnoughMoneyException { + if (amount > balance) { + throw new NotEnoughMoneyException(String.format("Bank balance is short $%.2f", Math.abs(balance - amount))); + } + balance -= amount; + } + + public double getBalance() { + return balance; + } +} + +class NotEnoughMoneyException extends Exception { + + public NotEnoughMoneyException() {} + + public NotEnoughMoneyException(String message) { + super(message); + } +} diff --git a/src/com/codefortomorrow/advanced/chapter14/solutions/Lexico.java b/src/com/codefortomorrow/advanced/chapter14/solutions/Lexico.java new file mode 100644 index 0000000..0800c8a --- /dev/null +++ b/src/com/codefortomorrow/advanced/chapter14/solutions/Lexico.java @@ -0,0 +1,38 @@ +package com.codefortomorrow.advanced.chapter14.solutions; + +import java.io.*; + +/* +Practice: Use File I/O to compare two files lexicographically. +Lexicographical order is very similar to alphabetical order, +except that it includes more than just lowercase alphabets. +Given two text files f1 and f2, write a program that will +compare their contents and output to the console the +title of the file which comes first lexicographically. + +Hint: Java’s String.compareTo method may be of use to you. +*/ + +public class Lexico { + + public static void main(String[] args) { + try ( + BufferedReader br = new BufferedReader(new FileReader("f1.txt")); + BufferedReader br2 = new BufferedReader(new FileReader("f2.txt")); + ) { + String line1 = br.readLine(); + String line2 = br2.readLine(); + int c = line1.compareTo(line2); + while (c == 0) { + line1 = br.readLine(); + line2 = br2.readLine(); + c = line1.compareTo(line2); + } + if (c > 0) System.out.println("File 2"); else System.out.println( + "File 1" + ); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/src/com/codefortomorrow/advanced/chapter14/solutions/account/InvalidAgeException.java b/src/com/codefortomorrow/advanced/chapter14/solutions/account/InvalidAgeException.java deleted file mode 100644 index 17084ef..0000000 --- a/src/com/codefortomorrow/advanced/chapter14/solutions/account/InvalidAgeException.java +++ /dev/null @@ -1,3 +0,0 @@ -package com.codefortomorrow.advanced.chapter14.solutions.account; - -public class InvalidAgeException extends Exception {} diff --git a/src/com/codefortomorrow/advanced/chapter14/solutions/account/InvalidPasswordException.java b/src/com/codefortomorrow/advanced/chapter14/solutions/account/InvalidPasswordException.java deleted file mode 100644 index 8f65f31..0000000 --- a/src/com/codefortomorrow/advanced/chapter14/solutions/account/InvalidPasswordException.java +++ /dev/null @@ -1,3 +0,0 @@ -package com.codefortomorrow.advanced.chapter14.solutions.account; - -public class InvalidPasswordException extends Exception {} diff --git a/src/com/codefortomorrow/advanced/chapter14/solutions/account/InvalidUsernameException.java b/src/com/codefortomorrow/advanced/chapter14/solutions/account/InvalidUsernameException.java deleted file mode 100644 index 68ccbc2..0000000 --- a/src/com/codefortomorrow/advanced/chapter14/solutions/account/InvalidUsernameException.java +++ /dev/null @@ -1,3 +0,0 @@ -package com.codefortomorrow.advanced.chapter14.solutions.account; - -public class InvalidUsernameException extends Exception {} diff --git a/src/com/codefortomorrow/advanced/chapter14/solutions/account/Main.java b/src/com/codefortomorrow/advanced/chapter14/solutions/account/Main.java deleted file mode 100644 index 2000e41..0000000 --- a/src/com/codefortomorrow/advanced/chapter14/solutions/account/Main.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.codefortomorrow.advanced.chapter14.solutions.account; - -import java.util.Scanner; - -public class Main { - - public static void main(String[] args) { - Scanner sc = new Scanner(System.in); - - System.out.println("Welcome to Account Creation!"); - while (true) { - System.out.print("Enter username (4 to 10 characters): "); - String username = sc.next(); - System.out.print("Enter age: "); - int age = sc.nextInt(); - System.out.print("Enter password (4 to 10 characters): "); - String password = sc.next(); - System.out.print("Confirm password (4 to 10 characters): "); - String confirmPassword = sc.next(); - - try { - createAccount(username, password, age, confirmPassword); - System.out.println("Account created successfully!"); - break; - } catch (InvalidUsernameException e) { - System.out.println("Invalid username."); - } catch (InvalidPasswordException e) { - System.out.println("Invalid password."); - } catch (InvalidAgeException e) { - System.out.println("Must be 18 or older to create an account."); - } catch (PasswordMismatchException e) { - System.out.println("Passwords don't match!"); - } - } - } - - public static void createAccount( - String username, - String password, - int age, - String confirmPassword - ) - throws InvalidAgeException, InvalidPasswordException, InvalidUsernameException, PasswordMismatchException { - if (username.length() < 4 || username.length() > 10) { - throw new InvalidUsernameException(); - } - if (password.length() < 4 || password.length() > 10) { - throw new InvalidPasswordException(); - } - if (age < 18) { - throw new InvalidAgeException(); - } - if (!password.equals(confirmPassword)) { - throw new PasswordMismatchException(); - } - } -} diff --git a/src/com/codefortomorrow/advanced/chapter14/solutions/account/PasswordMismatchException.java b/src/com/codefortomorrow/advanced/chapter14/solutions/account/PasswordMismatchException.java deleted file mode 100644 index 248d178..0000000 --- a/src/com/codefortomorrow/advanced/chapter14/solutions/account/PasswordMismatchException.java +++ /dev/null @@ -1,3 +0,0 @@ -package com.codefortomorrow.advanced.chapter14.solutions.account; - -public class PasswordMismatchException extends Exception {} diff --git a/src/com/codefortomorrow/advanced/chapter14/solutions/f1.txt b/src/com/codefortomorrow/advanced/chapter14/solutions/f1.txt new file mode 100644 index 0000000..684900a --- /dev/null +++ b/src/com/codefortomorrow/advanced/chapter14/solutions/f1.txt @@ -0,0 +1,28 @@ +All the world's a stage, +And all the men and women merely players; +They have their exits and their entrances, +And one man in his time plays many parts, +His acts being seven ages. At first, the infant, +Mewling and puking in the nurse's arms. +Then the whining schoolboy, with his satchel +And shining morning face, creeping like snail +Unwillingly to school. And then the lover, +Sighing like furnace, with a woeful ballad +Made to his mistress' eyebrow. Then a soldier, +Full of strange oaths and bearded like the pard, +Jealous in honor, sudden and quick in quarrel, +Seeking the bubble reputation +Even in the cannon's mouth. And then the justice, +In fair round belly with good capon lined, +With eyes severe and beard of formal cut, +Full of wise saws and modern instances; +And so he plays his part. The sixth age shifts +Into the lean and slippered pantaloon, +With spectacles on nose and pouch on side; +His youthful hose, well saved, a world too wide +For his shrunk shank, and his big manly voice, +Turning again toward childish treble, pipes +And whistles in his sound. Last scene of all, +That ends this strange eventful history, +Is second childishness and mere oblivion, +Sans teeth, sans eyes, sans taste, sans everything. diff --git a/src/com/codefortomorrow/advanced/chapter14/solutions/f2.txt b/src/com/codefortomorrow/advanced/chapter14/solutions/f2.txt new file mode 100644 index 0000000..31cf35c --- /dev/null +++ b/src/com/codefortomorrow/advanced/chapter14/solutions/f2.txt @@ -0,0 +1,28 @@ +All the world's a stage, +And all the men and women merely players; +They have their exits and their entrances, +And one man in his time plays many parts, +His acts being seven ages. At first, the infant, +Mewling and puking in the nurse's arms. +Then the whining schoolboy, with his satchel +And shining morning face, creeping like snail +Unwillingly to school. And then the lover, +Sighing like furnace, with a woeful ballad +Made to his mistress' eyebrow. Then a soldier, +Full of strange oaths and bearded like the pard, +Jealous in honor, sudden and quick in quarrel, +Seeking the bubble reputation +Even in the cannon's mouth. And than the justice, +In fair round belly with good capon lined, +With eyes severe and beard of formal cut, +Full of wise saws and modern instances; +And so he plays his part. The sixth age shifts +Into the lean and slippered pantaloon, +With spectacles on nose and pouch on side; +His youthful hose, well saved, a world too wide +For his shrunk shank, and his big manly voice, +Turning again toward childish treble, pipes +And whistles in his sound. Last scene of all, +That ends this strange eventful history, +Is second childishness and mere oblivion, +Sans teeth, sans eyes, sans taste, sans everything. diff --git a/src/com/codefortomorrow/advanced/chapter14/solutions/numbers.txt b/src/com/codefortomorrow/advanced/chapter14/solutions/numbers.txt new file mode 100644 index 0000000..54aac38 --- /dev/null +++ b/src/com/codefortomorrow/advanced/chapter14/solutions/numbers.txt @@ -0,0 +1,100 @@ +35 +94 +16 +38 +82 +87 +52 +60 +86 +59 +72 +7 +60 +56 +63 +11 +67 +77 +67 +82 +28 +13 +100 +92 +85 +69 +75 +6 +83 +100 +76 +51 +13 +84 +59 +30 +21 +72 +15 +28 +15 +95 +87 +61 +80 +22 +45 +9 +73 +85 +85 +2 +90 +75 +60 +80 +91 +21 +80 +41 +82 +27 +48 +43 +37 +52 +78 +21 +54 +20 +15 +49 +42 +89 +63 +24 +10 +62 +44 +63 +51 +34 +36 +21 +2 +49 +64 +77 +34 +80 +7 +83 +51 +46 +11 +25 +59 +96 +21 +65 diff --git a/src/com/codefortomorrow/advanced/chapter15/practice/MeasurableProblem.java b/src/com/codefortomorrow/advanced/chapter15/practice/MeasurableProblem.java new file mode 100644 index 0000000..03c5f00 --- /dev/null +++ b/src/com/codefortomorrow/advanced/chapter15/practice/MeasurableProblem.java @@ -0,0 +1,28 @@ +package com.codefortomorrow.advanced.chapter15.practice; + +/* +Create a Measurable interface +that is used to “measure” anything. Add necessary methods. +Required Methods: double average(Measurable[] items), +largest(Measurable[] items) or smallest(Measurable[] items). +Create a Student class that implements Measurable and +it’s methods(you can compare whatever you measure, i.e. GPA). +Note: for the largest/smallest methods don’t worry +about the case if they are equal. + +Problem adapted from Java SE 9 Textbook +*/ +public class MeasurableProblem { + + public static void main(String[] args) { + //Add testing code + } +} + +interface Measurable { + //add interface code here +} + +class Student implements Measurable { + //Add student code here +} diff --git a/src/com/codefortomorrow/advanced/chapter15/solutions/MeasurableProblem.java b/src/com/codefortomorrow/advanced/chapter15/solutions/MeasurableProblem.java new file mode 100644 index 0000000..3c57162 --- /dev/null +++ b/src/com/codefortomorrow/advanced/chapter15/solutions/MeasurableProblem.java @@ -0,0 +1,89 @@ +package com.codefortomorrow.advanced.chapter15.solutions; + +import java.util.Arrays; + +/* +Create a Measurable interface +that is used to “measure” anything. Add necessary methods. +Required Methods: double average(Measurable[] items), +largest(Measurable[] items) or smallest(Measurable[] items). +Create a Student class that implements Measurable and +it’s methods(you can compare whatever you measure, i.e. GPA). +Note: for the largest/smallest methods don’t worry +about the case if they are equal. + +Problem adapted from Java SE 9 Textbook +*/ +public class MeasurableProblem { + + public static void main(String[] args) { + Object[] students = { + new Student("John", 2.7), + new Student("Josh", 1.2), + new Student("Jacob", 3.4), + new Student("Rebecca", 3.5), + new Student("Arnav", 4.0), + }; + Student test = new Student(); + System.out.println("Average: " + test.average(students)); + System.out.println("Largest: " + test.largest(students)); + System.out.println("Smallest: " + test.smallest(students)); + } +} + +interface Measurable { + abstract double average(Object[] students); + + abstract String largest(Object[] students); + + abstract String smallest(Object[] students); +} + +class Student implements Measurable { + + private double GPA; + private String name; + + public Student(String name, double GPA) { + this.name = name; + this.GPA = GPA; + } + + public Student() { + name = ""; + GPA = 0.0; + } + + public double average(Object[] orig) { + Student[] students = Arrays.copyOf(orig, orig.length, Student[].class); //Casting + double sum = 0; + for (Student s : students) sum += s.getGPA(); + return sum / students.length; + } + + public String largest(Object[] orig) { + Student[] students = Arrays.copyOf(orig, orig.length, Student[].class); //Casting + Student curr = students[0]; + for (Student s : students) { + if (s.getGPA() > curr.getGPA()) curr = s; + } + return curr.getName(); + } + + public String smallest(Object[] orig) { + Student[] students = Arrays.copyOf(orig, orig.length, Student[].class); //Casting + Student curr = students[0]; + for (Student s : students) { + if (s.getGPA() < curr.getGPA()) curr = s; + } + return curr.getName(); + } + + public double getGPA() { + return GPA; + } + + public String getName() { + return name; + } +} diff --git a/src/com/codefortomorrow/advanced/chapter16/practice/Access.java b/src/com/codefortomorrow/advanced/chapter16/practice/Access.java new file mode 100644 index 0000000..917e424 --- /dev/null +++ b/src/com/codefortomorrow/advanced/chapter16/practice/Access.java @@ -0,0 +1,11 @@ +package com.codefortomorrow.advanced.chapter16.practice; +/* +Using the methods outlined in the “Benefits of LinkedLists” section, +fill both a LinkedList and an ArrayList with 10,000 elements. +Then, find the time it takes to access the last element of each list. + +Determine which type of list can access elements more efficiently. + +Hint: You can use the get(int position) method +to access the element at a given position of a list. +*/ diff --git a/src/com/codefortomorrow/advanced/chapter16/practice/LinkedList.java b/src/com/codefortomorrow/advanced/chapter16/practice/LinkedList.java new file mode 100644 index 0000000..04fd4f5 --- /dev/null +++ b/src/com/codefortomorrow/advanced/chapter16/practice/LinkedList.java @@ -0,0 +1,27 @@ +package com.codefortomorrow.advanced.chapter16.practice; + +/** + * @author ArmeetJatyani + * March 2021 + * + * Implement a simple LinkedList + * You will need to create a LinkedListNode class, which represents each item/node in the linked list + * Assume that the elements in the linked list are all of type int + * Required functionality... + * - head(): get head of list + * - tail(): get tail of list + * - add(): add to tail of list + * - push(): push to head of list + * - pop(): remove head of list + * - toString(): return a String representation of the list + */ + +public class LinkedList { + + public static void main(String[] args) { + // write your code here + + } +} + +class LinkedListNode {} diff --git a/src/com/codefortomorrow/advanced/chapter16/practice/Names.java b/src/com/codefortomorrow/advanced/chapter16/practice/Names.java new file mode 100644 index 0000000..3d9a449 --- /dev/null +++ b/src/com/codefortomorrow/advanced/chapter16/practice/Names.java @@ -0,0 +1,17 @@ +package com.codefortomorrow.advanced.chapter16.practice; +/* +Create a LinkedList of Strings, and ask the user to +input 10 names one by one into the list. + +Output this list. + +Remove each name that has 5 or fewer letters, and output the new list. + +Add the word “Apple” to the beginning of the list. + +Add the word “Peanut” to the second-to-last position of the list. + +(Hint: Make sure to take advantage of LinkedList methods!) + +Output the new list. +*/ diff --git a/src/com/codefortomorrow/advanced/chapter16/practice/SinglyLinkedListInsert.java b/src/com/codefortomorrow/advanced/chapter16/practice/SinglyLinkedListInsert.java new file mode 100644 index 0000000..1b8ec1b --- /dev/null +++ b/src/com/codefortomorrow/advanced/chapter16/practice/SinglyLinkedListInsert.java @@ -0,0 +1,30 @@ +package com.codefortomorrow.advanced.chapter16.practice; +/* +Adding an insert method to a SinglyLinkedList +(details in SinglyLinkedList DIY section). + +Hint: It might be necessary to have a separate case for +inserting at position 0, because that’s when you want to +insert BEFORE the head. For all other positions (1, 2, etc.), +you can simply traverse down the list, keeping track of the +current node, and when you reach the position you want, +add the node AFTER the current node. + +Alternatively, you can always add BEFORE the current node +for all position cases (insert before the head to place the +new node at pos 0, insert before node 1 to place the new +node at pos 1, etc.), but then your exception case would +be when the user wants to insert a node at the very end of the list. +In this case, you’d have to write separate code to insert AFTER +the last node. + +Make sure you have a toString() method defined! + +The following code should output “{2, 3, 4, 7}”: +SinglyLinkedList lst = new SinglyLinkedList(); +lst.add(3); +lst.add(7); +lst.insert(4, 1); +lst.insert(2, 0); +System.out.println(lst); +*/ diff --git a/src/com/codefortomorrow/advanced/chapter16/practice/Sort.java b/src/com/codefortomorrow/advanced/chapter16/practice/Sort.java new file mode 100644 index 0000000..4b783e5 --- /dev/null +++ b/src/com/codefortomorrow/advanced/chapter16/practice/Sort.java @@ -0,0 +1,7 @@ +package com.codefortomorrow.advanced.chapter16.practice; +/* +Write a method which takes in a LinkedList of Strings +and rearranges the elements (without creating a new list) +so it is sorted in ascending order of String length. +Don’t use any pre-existing sort methods… write your own. :) +*/ diff --git a/src/com/codefortomorrow/advanced/chapter16/solutions/Access.java b/src/com/codefortomorrow/advanced/chapter16/solutions/Access.java new file mode 100644 index 0000000..5a4889d --- /dev/null +++ b/src/com/codefortomorrow/advanced/chapter16/solutions/Access.java @@ -0,0 +1,42 @@ +package com.codefortomorrow.advanced.chapter16.solutions; + +import java.util.ArrayList; +import java.util.LinkedList; + +/* +Using the methods outlined in the “Benefits of LinkedLists” section, +fill both a LinkedList and an ArrayList with 10,000 elements. +Then, find the time it takes to access the last element of each list. + +Determine which type of list can access elements more efficiently. + +Hint: You can use the get(int position) method +to access the element at a given position of a list. +*/ + +public class Access { + + @SuppressWarnings("unused") + public static void main(String[] args) { + long a, b; + + // Define lists with 10,000 elements. + LinkedList list1 = new LinkedList(); + for (int i = 0; i < 10000; i++) list1.add(1); + + ArrayList list2 = new ArrayList(); + for (int i = 0; i < 10000; i++) list2.add(1); + + // Get time for each operation and output the difference. + a = System.nanoTime(); + int c = list1.get(9999); + b = System.nanoTime(); + System.out.println("\nLinked: " + (b - a) + " ns"); + + a = System.nanoTime(); + int d = list2.get(9999); + b = System.nanoTime(); + System.out.println("ArrayList: " + (b - a) + " ns"); + // Note that the ArrayList takes less time. + } +} diff --git a/src/com/codefortomorrow/advanced/chapter16/solutions/LinkedList.java b/src/com/codefortomorrow/advanced/chapter16/solutions/LinkedList.java new file mode 100644 index 0000000..a73917e --- /dev/null +++ b/src/com/codefortomorrow/advanced/chapter16/solutions/LinkedList.java @@ -0,0 +1,164 @@ +package com.codefortomorrow.advanced.chapter16.solutions; + +/** + * @author ArmeetJatyani + * March 2021 + * + * Implement a simple LinkedList + * You will need to create a LinkedListNode class, which represents each item/node in the linked list + * Assume that the elements in the linked list are all of type int + * Required functionality... + * - head(): get head of list + * - tail(): get tail of list + * - add(): add to tail of list + * - push(): push to head of list + * - pop(): remove head of list + * - toString(): return a String representation of the list + */ + +public class LinkedList { + + private LinkedListNode head; + + /** + * default constructor + */ + public LinkedList() { + head = null; + } + + /** + * constructor with first value + * @param value first element in the linked list + */ + public LinkedList(int value) { + // create first node + head = new LinkedListNode(value, null); + } + + /** + * get head of Linked List + * @return first element of the linked list + */ + public LinkedListNode head() { + return this.head; + } + + /** + * traverse and get tail of linked list + * @return last element of the linked list + */ + public LinkedListNode tail() { + LinkedListNode current = head; + if (current == null) return null; + + while (current.next() != null) { + current = current.next(); + } + + return current; + } + + /** + * add new element (node) to linked list + * @param value element to add to the end of the linked list + */ + public void add(int value) { + LinkedListNode tail = tail(); + if (tail == null) { + head = new LinkedListNode(value, null); + } else { + tail.setNext(new LinkedListNode(value, null)); + } + } + + /** + * push (add element to head of linkedlist) + */ + public void push(int value) { + LinkedListNode newHead = new LinkedListNode(value, head); + head = newHead; + } + + /** + * pop (remove and return head of linkedlist) + * @return the node that was removed + */ + public LinkedListNode pop() { + LinkedListNode popped = head; + head = head.next(); + return popped; + } + + /** + * Returns a String version of the LinkedList + * @return a String version of the LinkedList + */ + @Override + public String toString() { + String list = "["; + LinkedListNode current = head; + if (current == null) return null; + do { + list += Integer.toString(current.value()) + ", "; + current = current.next(); + } while (current != null); + + // Remove trailing comma and space after last list element + list = list.substring(0, list.length() - 2); + return list + "]"; + } +} + +class Node { + + private int value; + + /** + * Constructs a list node with the given value + * @param value the value stored in this Node + */ + public Node(int value) { + this.value = value; + } + + /** + * Returns the value of this Node + * @return the value of this Node + */ + public int value() { + return this.value; + } +} + +class LinkedListNode extends Node { + + private LinkedListNode next; + + /** + * Constructs a LinkedListNode + * @param value the value stored in this node + * @param next the next node + */ + public LinkedListNode(int value, LinkedListNode next) { + super(value); + this.next = next; + } + + /** + * Returns the next node + * @return the next node + */ + public LinkedListNode next() { + return this.next; + } + + /** + * Sets the next node + * @param next the next node + */ + public void setNext(LinkedListNode next) { + this.next = next; + return; + } +} diff --git a/src/com/codefortomorrow/advanced/chapter16/solutions/Names.java b/src/com/codefortomorrow/advanced/chapter16/solutions/Names.java new file mode 100644 index 0000000..c862fdf --- /dev/null +++ b/src/com/codefortomorrow/advanced/chapter16/solutions/Names.java @@ -0,0 +1,45 @@ +package com.codefortomorrow.advanced.chapter16.solutions; + +import java.util.LinkedList; +import java.util.Scanner; + +/* +Create a LinkedList of Strings, and ask the user to +input 10 names one by one into the list. + +Output this list. + +Remove each name that has 5 or fewer letters, and output the new list. + +Add the word “Apple” to the beginning of the list. + +Add the word “Peanut” to the second-to-last position of the list. + +(Hint: Make sure to take advantage of LinkedList methods!) + +Output the new list. +*/ + +public class Names { + + public static void main(String[] args) { + LinkedList list = new LinkedList(); + Scanner sc = new Scanner(System.in); + for (int i = 0; i < 10; i++) { + System.out.print("Enter name " + (i + 1) + ": "); + list.add(sc.nextLine()); + } + System.out.println(list); + + for (int i = 0; i < list.size(); i++) if ( + list.get(i).length() <= 5 + ) list.remove(i--); + System.out.println(list); + + list.add(0, "Apple"); + list.add(list.size() - 1, "Peanut"); + System.out.println(list); + + sc.close(); + } +} diff --git a/src/com/codefortomorrow/advanced/chapter16/solutions/SinglyLinkedListInsert.java b/src/com/codefortomorrow/advanced/chapter16/solutions/SinglyLinkedListInsert.java new file mode 100644 index 0000000..7fb84c1 --- /dev/null +++ b/src/com/codefortomorrow/advanced/chapter16/solutions/SinglyLinkedListInsert.java @@ -0,0 +1,111 @@ +package com.codefortomorrow.advanced.chapter16.solutions; + +import java.util.*; + +/* +Adding an insert method to a SinglyLinkedList +(details in SinglyLinkedList DIY section). + +Hint: It might be necessary to have a separate case for +inserting at position 0, because that’s when you want to +insert BEFORE the head. For all other positions (1, 2, etc.), +you can simply traverse down the list, keeping track of the +current node, and when you reach the position you want, +add the node AFTER the current node. + +Alternatively, you can always add BEFORE the current node +for all position cases (insert before the head to place the +new node at pos 0, insert before node 1 to place the new +node at pos 1, etc.), but then your exception case would +be when the user wants to insert a node at the very end of the list. +In this case, you’d have to write separate code to insert AFTER +the last node. + +Make sure you have a toString() method defined! + +The following code should output “{2, 3, 4, 7}”: +SinglyLinkedList lst = new SinglyLinkedList(); +lst.add(3); +lst.add(7); +lst.insert(4, 1); +lst.insert(2, 0); +System.out.println(lst); +*/ + +// NOTE: You need to make a separate class with a main() +// method to use this List object. This is simply the object +// definition. + +public class SinglyLinkedListInsert { + + Node head; + + // add() method from SinglyLinkedList DIY section, adds to end of list + public void add(int data) { + // Create a new node with given data + Node new_node = new Node(data); + + // If the Linked List is empty, + // then make the new node as head + if (head == null) { + head = new_node; + } else { + // Else traverse till the last node + // and insert the new_node there + Node last = head; + while (last.next != null) { + last = last.next; + } + + // Insert the new_node at last node + last.next = new_node; + } + } + + public void insert(int data, int pos) { + // Verify valid pos number + if (pos < 0) System.out.print("Invalid position"); + + // Create new node and keep track of current node + Node new_node = new Node(data); + Node current = head; + + // If pos is 0, set new node as head + if (pos == 0) { + new_node.next = head; + head = new_node; + } else { + while (pos-- >= 0) { + if (pos == 0) { + // Add new node after current position + new_node.next = current.next; + current.next = new_node; + break; + } + // Check if pos is out of bounds (reaches end) + if (current.next == null) { + System.out.println("Out of bounds"); + break; + } + current = current.next; + } + } + } + + @Override + public String toString() { + // For empty lists + if (head == null) return "{}"; + + String str = "{"; + + // Traverse the list until the last node + Node current = head; + while (current.next != null) { + str += "" + current.data + ", "; + current = current.next; + } + str += current.data + "}"; + return str; + } +} diff --git a/src/com/codefortomorrow/advanced/chapter16/solutions/Sort.java b/src/com/codefortomorrow/advanced/chapter16/solutions/Sort.java new file mode 100644 index 0000000..acbd9d0 --- /dev/null +++ b/src/com/codefortomorrow/advanced/chapter16/solutions/Sort.java @@ -0,0 +1,52 @@ +package com.codefortomorrow.advanced.chapter16.solutions; + +import java.util.Arrays; +import java.util.LinkedList; + +/* +Write a method which takes in a LinkedList of Strings +and rearranges the elements (without creating a new list) +so it is sorted in ascending order of String length. +Don’t use any pre-existing sort methods… write your own. :) +*/ + +public class Sort { + + public static void main(String[] args) { + LinkedList list = new LinkedList(); + list.addAll( + Arrays.asList( + "Jeannette", + "Sophia", + "Computer", + "Boots", + "Lava", + "Lasagna", + "Dirty", + "Cleanie" + ) + ); + sort(list); + System.out.println(list); + } + + public static void sort(LinkedList list) { + if (list.size() < 2) return; + for (int i = 1; i < list.size(); i++) { + String current = list.get(i); + // Check if current word is smaller than previous word + if (current.length() < list.get(i - 1).length()) { + // Add current word before the node with + // same or greater word size + for (int j = 0; j < i; j++) { + if (list.get(j).length() >= current.length()) { + list.add(j, current); + // Remove duplicate current + list.remove(i + 1); + break; + } + } + } + } + } +} diff --git a/src/com/codefortomorrow/beginner/chapter1/practice/Comments.java b/src/com/codefortomorrow/beginner/chapter1/practice/Comments.java new file mode 100644 index 0000000..cb032a4 --- /dev/null +++ b/src/com/codefortomorrow/beginner/chapter1/practice/Comments.java @@ -0,0 +1,33 @@ +package com.codefortomorrow.beginner.chapter1.practice; + +/** + * @author ArmeetJatyani + * March 2021 + * + * You'll be writing your first ever comment today! + * What we'll go over: + * - single line comments + * - multi line comments + */ + +// a class is an "object" where we will place all our code inside +public class Comments { + + // the main method (below) is the first thing that runs when your program is run + public static void main(String[] args) { + // this is a single line comment, I can write anything here + // single line comments aren't run by Java! + // they can be used to annotate your code! + + /** + * this is a multi + * line + * comment + * + * It can span across multiple lines! + */ + + // YOUR ASSIGNMENT: write 1 single-line comment and 1 multi-line comment on the lines below... + + } +} diff --git a/src/com/codefortomorrow/beginner/chapter1/practice/HelloWorld.java b/src/com/codefortomorrow/beginner/chapter1/practice/HelloWorld.java new file mode 100644 index 0000000..4fd1294 --- /dev/null +++ b/src/com/codefortomorrow/beginner/chapter1/practice/HelloWorld.java @@ -0,0 +1,20 @@ +package com.codefortomorrow.beginner.chapter1.practice; + +/** + * @author ArmeetJatyani + * March 2021 + * + * Welcome to Java! + * This may be your first ever java program! + * We'll begin your journey with the infamous Hello World program! + */ + +// a class is an "object" where we will place all our code inside +public class HelloWorld { + + // the main method (below) is the first thing that runs when your program is run + public static void main(String[] args) { + // write code here (replace the "" with "Hello World!") + System.out.println(""); + } +} diff --git a/src/com/codefortomorrow/beginner/chapter1/solutions/Comments.java b/src/com/codefortomorrow/beginner/chapter1/solutions/Comments.java new file mode 100644 index 0000000..faaa644 --- /dev/null +++ b/src/com/codefortomorrow/beginner/chapter1/solutions/Comments.java @@ -0,0 +1,39 @@ +package com.codefortomorrow.beginner.chapter1.solutions; + +/** + * @author ArmeetJatyani + * March 2021 + * + * You'll be writing your first ever comment today! + * What we'll go over: + * - single line comments + * - multi line comments + */ + +// a class is an "object" where we will place all our code inside +public class Comments { + + // the main method (below) is the first thing that runs when your program is run + public static void main(String[] args) { + // this is a single line comment, I can write anything here + // single line comments aren't run by Java! + // they can be used to annotate your code! + + /** + * this is a multi + * line + * comment + * + * It can span across multiple lines! + */ + + // YOUR ASSIGNMENT: write 1 single-line comment and 1 multi-line comment on the lines below... + + // Hi my name is Armeet! + + /** + * I like teaching Java, and + * good luck on your journey! + */ + } +} diff --git a/src/com/codefortomorrow/beginner/chapter1/solutions/HelloWorld.java b/src/com/codefortomorrow/beginner/chapter1/solutions/HelloWorld.java new file mode 100644 index 0000000..e645eff --- /dev/null +++ b/src/com/codefortomorrow/beginner/chapter1/solutions/HelloWorld.java @@ -0,0 +1,20 @@ +package com.codefortomorrow.beginner.chapter1.solutions; + +/** + * @author ArmeetJatyani + * March 2021 + * + * Welcome to Java! + * This may be your first ever java program! + * We'll begin your journey with the infamous Hello World program! + */ + +// a class is an "object" where we will place all our code inside +public class HelloWorld { + + // the main method (below) is the first thing that runs when your program is run + public static void main(String[] args) { + // write code here (replace the "" with "Hello World!") + System.out.println("Hello World!"); + } +} diff --git a/src/com/codefortomorrow/beginner/chapter2/examples/Variables.java b/src/com/codefortomorrow/beginner/chapter2/examples/Variables.java index 41bf623..3adc394 100644 --- a/src/com/codefortomorrow/beginner/chapter2/examples/Variables.java +++ b/src/com/codefortomorrow/beginner/chapter2/examples/Variables.java @@ -21,9 +21,11 @@ public static void main(String[] args) { // scope class A { + String message = "World"; } class B { + String word = "Java"; } diff --git a/src/com/codefortomorrow/beginner/chapter2/practice/ApplesOranges.java b/src/com/codefortomorrow/beginner/chapter2/practice/ApplesOranges.java new file mode 100644 index 0000000..5c91b50 --- /dev/null +++ b/src/com/codefortomorrow/beginner/chapter2/practice/ApplesOranges.java @@ -0,0 +1,24 @@ +package com.codefortomorrow.beginner.chapter2.practice; + +/** + * @author ArmeetJatyani + * March 2021 + * + * Print out the number of apples and oranges! + */ + +public class ApplesOranges { + + public static void main(String[] args) { + // write your code here + + // define an integer variable called numOranges with value 10 (line 15) + + // define an integer variable called numApples with value 24 (line 18) + + // print out number of oranges using variables, output: "I have 10 oranges." (line 21) + + // print out number of apples using variables, output: "I have 24 apples." (line 24) + + } +} diff --git a/src/com/codefortomorrow/beginner/chapter2/practice/VariableTypes.java b/src/com/codefortomorrow/beginner/chapter2/practice/VariableTypes.java new file mode 100644 index 0000000..b0848ac --- /dev/null +++ b/src/com/codefortomorrow/beginner/chapter2/practice/VariableTypes.java @@ -0,0 +1,28 @@ +package com.codefortomorrow.beginner.chapter2.practice; + +/** + * @author ArmeetJatyani + * March 2021 + * + * Define different types of variables + */ + +public class VariableTypes { + + public static void main(String[] args) { + // write your code here + + // define an integer variable on line 15 + + // define a float variable on line 18 + + // define a double variable on line 21 + + // define a boolean variable on line 24 (Hint: true/false) + + // define a character variable on line 27 + + // define a string variable on line 30 + + } +} diff --git a/src/com/codefortomorrow/beginner/chapter2/solutions/ApplesOranges.java b/src/com/codefortomorrow/beginner/chapter2/solutions/ApplesOranges.java new file mode 100644 index 0000000..e45b29a --- /dev/null +++ b/src/com/codefortomorrow/beginner/chapter2/solutions/ApplesOranges.java @@ -0,0 +1,27 @@ +package com.codefortomorrow.beginner.chapter2.solutions; + +/** + * @author ArmeetJatyani + * March 2021 + * + * Print out the number of apples and oranges! + */ + +public class ApplesOranges { + + public static void main(String[] args) { + // write your code here + + // define an integer variable called numOranges with value 10 (line 15) + int numOranges = 10; + + // define an integer variable called numApples with value 24 (line 18) + int numApples = 24; + + // print out number of oranges using variables, output: "I have 10 oranges." (line 21) + System.out.println("I have " + numOranges + " oranges."); + + // print out number of apples using variables, output: "I have 24 apples." (line 24) + System.out.println("I have " + numApples + " apples."); + } +} diff --git a/src/com/codefortomorrow/beginner/chapter2/solutions/VariableTypes.java b/src/com/codefortomorrow/beginner/chapter2/solutions/VariableTypes.java new file mode 100644 index 0000000..f9946b0 --- /dev/null +++ b/src/com/codefortomorrow/beginner/chapter2/solutions/VariableTypes.java @@ -0,0 +1,34 @@ +package com.codefortomorrow.beginner.chapter2.solutions; + +/** + * @author ArmeetJatyani + * March 2021 + * + * Define different types of variables + */ + +public class VariableTypes { + + @SuppressWarnings("unused") + public static void main(String[] args) { + // write your code here + + // define an integer variable on line 15 + int age = 23; + + // define a float variable on line 18 + float decimal = 23.32544f; + + // define a double variable on line 21 + double number = 23.2352536; + + // define a boolean variable on line 24 (Hint: true/false) + boolean dogsOut = true; // the dogs are out :) + + // define a character variable on line 27 + char letter = 'A'; + + // define a string variable on line 30 + String name = "Jeff"; + } +} diff --git a/src/com/codefortomorrow/beginner/chapter4/practice/CarDealership.java b/src/com/codefortomorrow/beginner/chapter4/practice/CarDealership.java new file mode 100644 index 0000000..27c3110 --- /dev/null +++ b/src/com/codefortomorrow/beginner/chapter4/practice/CarDealership.java @@ -0,0 +1,22 @@ +package com.codefortomorrow.beginner.chapter4.practice; + +/** + * @author ArmeetJatyani + * March 2021 + * + * Manage a car dealership and take inventory of all cars sold! + */ + +public class CarDealership { + + public static void main(String[] args) { + // write your code here + + // define 3 integer constants, representing the prices of 3 cars sold in USD (line 15-17) + + // define an integer variable, which represents the sum of the prices of these 3 cars (line 20) + + // print out the formatted revenue after selling these 3 cars, output: "I sold 3 cars for $XXXXXX." (line 23) + + } +} diff --git a/src/com/codefortomorrow/beginner/chapter4/solutions/CarDealership.java b/src/com/codefortomorrow/beginner/chapter4/solutions/CarDealership.java new file mode 100644 index 0000000..98f48fb --- /dev/null +++ b/src/com/codefortomorrow/beginner/chapter4/solutions/CarDealership.java @@ -0,0 +1,26 @@ +package com.codefortomorrow.beginner.chapter4.solutions; + +/** + * @author ArmeetJatyani + * March 2021 + * + * Manage a car dealership and take inventory of all cars sold! + */ + +public class CarDealership { + + public static void main(String[] args) { + // write your code here + + // define 3 integer constants, representing the prices of 3 cars sold in USD (line 15-17) + final int car1 = 30000; + final int car2 = 24650; + final int car3 = 253630; + + // define an integer variable, which represents the sum of the prices of these 3 cars (line 20) + int revenue = car1 + car2 + car3; + + // print out the formatted revenue after selling these 3 cars, output: "I sold 3 cars for $XXXXXX." (line 23) + System.out.println("I sold 3 cars for $" + revenue + "."); + } +} diff --git a/src/com/codefortomorrow/intermediate/chapter10/solutions/TestSelectionSort.java b/src/com/codefortomorrow/intermediate/chapter10/solutions/TestSelectionSort.java index d95b1a5..f7ddd4b 100644 --- a/src/com/codefortomorrow/intermediate/chapter10/solutions/TestSelectionSort.java +++ b/src/com/codefortomorrow/intermediate/chapter10/solutions/TestSelectionSort.java @@ -1,32 +1,68 @@ package com.codefortomorrow.intermediate.chapter10.solutions; +import java.util.Scanner; + /* - * Adapted from Exercise 8.5, - * Introduction to Java Programming (Comprehensive) - * by Y. Daniel Liang, 10th ed. - * - * Create a program called AddMatrices which - * adds two 3x3 matrices and prints the result. - * The program should prompt the user to enter - * data for 2 matrices and then displays those - * 2 matrices and the sum matrix. + * Create a driver class called TestSelectionSort + * which prompts the user to enter the length of + * an array and the elements (doubles) in the array. + * Then, your program should use selection sort to + * sort the array in place, and then print the resulting array. * * Example output: * - * Enter matrix1: 1 2 3 4 5 6 7 8 9 - * Enter matrix2: 0 2 4 1 4.5 2.2 1.1 4.3 5.2 - * The matrices are added as follows - * 1.0 2.0 3.0 0.0 2.0 4.0 1.0 4.0 7.0 - * 4.0 5.0 6.0 + 1.0 4.5 2.2 = 5.0 9.5 8.2 - * 7.0 8.0 9.0 1.1 4.3 5.2 8.1 12.3 14.2 - * - * Hint: You may need to use the Double.parseDouble("a string") - * to convert the user input to doubles. + * Enter the length of the array: 5 + * Enter the elements in the array: -1 236.3 2 6 0 + * -1.0 0.0 2.0 6.0 236.3 */ public class TestSelectionSort { public static void main(String[] args) { - // write code here + // Prompt user for length of array + System.out.print("Enter the length of the array: "); + Scanner input = new Scanner(System.in); + int arrayLength = input.nextInt(); + + // Initialize array + double[] list = new double[arrayLength]; + + // Prompt user for elements of the array + System.out.print("Enter the elements in the array: "); + for (int i = 0; i < arrayLength; i++) { + list[i] = input.nextDouble(); + } + + // goes up to index list.length - 1 + // because you don't need to check last element + // since it will be sorted already + for (int i = 0; i < list.length - 1; i++) { + double min = list[i]; + int minIndex = i; + + // find the current smallest element + for (int j = i + 1; j < list.length; j++) { + if (list[j] < min) { + min = list[j]; + minIndex = j; + } + } + + // swap it with whatever is in the + // first position of unsorted array if needed + if (minIndex != i) { + double temp = list[i]; + list[i] = min; + list[minIndex] = temp; + } + } + + // print the sorted array + for (double n : list) { + System.out.print(n + " "); + } + System.out.println(); // move cursor to next line + + input.close(); } } diff --git a/src/com/codefortomorrow/intermediate/chapter12/examples/Person.java b/src/com/codefortomorrow/intermediate/chapter12/examples/Person.java index f57e9b5..ba50d7e 100644 --- a/src/com/codefortomorrow/intermediate/chapter12/examples/Person.java +++ b/src/com/codefortomorrow/intermediate/chapter12/examples/Person.java @@ -1,6 +1,7 @@ package com.codefortomorrow.intermediate.chapter12.examples; public class Person { + private String name; private int age; private String address; diff --git a/src/com/codefortomorrow/intermediate/chapter12/examples/TestInstrument.java b/src/com/codefortomorrow/intermediate/chapter12/examples/TestInstrument.java index a5d070e..daaeff0 100644 --- a/src/com/codefortomorrow/intermediate/chapter12/examples/TestInstrument.java +++ b/src/com/codefortomorrow/intermediate/chapter12/examples/TestInstrument.java @@ -15,6 +15,7 @@ public static void main(String[] args) { } class Instrument { + private String name; public Instrument() { @@ -36,6 +37,7 @@ public String toString() { } class Guitar extends Instrument { + private String type; private String stringType; diff --git a/src/com/codefortomorrow/intermediate/chapter12/examples/TestPoint.java b/src/com/codefortomorrow/intermediate/chapter12/examples/TestPoint.java index 8268423..c741010 100644 --- a/src/com/codefortomorrow/intermediate/chapter12/examples/TestPoint.java +++ b/src/com/codefortomorrow/intermediate/chapter12/examples/TestPoint.java @@ -17,6 +17,7 @@ public static void main(String[] args) { } class Point { + public double x; public double y; diff --git a/src/com/codefortomorrow/intermediate/chapter12/practice/Account.java b/src/com/codefortomorrow/intermediate/chapter12/practice/Account.java index b52b57a..d87f957 100644 --- a/src/com/codefortomorrow/intermediate/chapter12/practice/Account.java +++ b/src/com/codefortomorrow/intermediate/chapter12/practice/Account.java @@ -5,6 +5,7 @@ */ public class Account { + private String name; private long number; private double balance; diff --git a/src/com/codefortomorrow/intermediate/chapter12/practice/TestPiano.java b/src/com/codefortomorrow/intermediate/chapter12/practice/TestPiano.java index d5f74bc..793d373 100644 --- a/src/com/codefortomorrow/intermediate/chapter12/practice/TestPiano.java +++ b/src/com/codefortomorrow/intermediate/chapter12/practice/TestPiano.java @@ -43,6 +43,7 @@ class Piano extends Instrument { } class Instrument { + private String name; public Instrument() { diff --git a/src/com/codefortomorrow/intermediate/chapter12/practice/pokemon/Battle.java b/src/com/codefortomorrow/intermediate/chapter12/practice/pokemon/Battle.java index 961e20b..1e855bf 100644 --- a/src/com/codefortomorrow/intermediate/chapter12/practice/pokemon/Battle.java +++ b/src/com/codefortomorrow/intermediate/chapter12/practice/pokemon/Battle.java @@ -3,6 +3,7 @@ import java.util.Scanner; public class Battle { + private Scanner sc = new Scanner(System.in); private Pokemon pokemonOne; private Pokemon pokemonTwo; diff --git a/src/com/codefortomorrow/intermediate/chapter12/practice/pokemon/Move.java b/src/com/codefortomorrow/intermediate/chapter12/practice/pokemon/Move.java index 7e2559f..4ac5e77 100644 --- a/src/com/codefortomorrow/intermediate/chapter12/practice/pokemon/Move.java +++ b/src/com/codefortomorrow/intermediate/chapter12/practice/pokemon/Move.java @@ -4,6 +4,7 @@ * represents a Pokemon's move */ public class Move { + private String name; private boolean poisoning; private boolean sleeping; diff --git a/src/com/codefortomorrow/intermediate/chapter12/practice/pokemon/Pokemon.java b/src/com/codefortomorrow/intermediate/chapter12/practice/pokemon/Pokemon.java index 277ffd6..784d22b 100644 --- a/src/com/codefortomorrow/intermediate/chapter12/practice/pokemon/Pokemon.java +++ b/src/com/codefortomorrow/intermediate/chapter12/practice/pokemon/Pokemon.java @@ -4,6 +4,7 @@ * represents a Pokemon object */ public class Pokemon { + private Move[] moveList; private int maxHP; private int currentHP; diff --git a/src/com/codefortomorrow/intermediate/chapter12/solutions/Book.java b/src/com/codefortomorrow/intermediate/chapter12/solutions/Book.java index 12092b9..f91012b 100644 --- a/src/com/codefortomorrow/intermediate/chapter12/solutions/Book.java +++ b/src/com/codefortomorrow/intermediate/chapter12/solutions/Book.java @@ -10,6 +10,7 @@ */ public class Book { + private String title; private String author; private String genre; diff --git a/src/com/codefortomorrow/intermediate/chapter12/solutions/Circle.java b/src/com/codefortomorrow/intermediate/chapter12/solutions/Circle.java index cc5aacb..c9b3651 100644 --- a/src/com/codefortomorrow/intermediate/chapter12/solutions/Circle.java +++ b/src/com/codefortomorrow/intermediate/chapter12/solutions/Circle.java @@ -5,6 +5,7 @@ */ public class Circle { + private double radius; private String color; diff --git a/src/com/codefortomorrow/intermediate/chapter12/solutions/TestPiano.java b/src/com/codefortomorrow/intermediate/chapter12/solutions/TestPiano.java index d2c7d2f..3d6b32a 100644 --- a/src/com/codefortomorrow/intermediate/chapter12/solutions/TestPiano.java +++ b/src/com/codefortomorrow/intermediate/chapter12/solutions/TestPiano.java @@ -38,6 +38,7 @@ public static void main(String[] args) { } class Piano extends Instrument { + private double hammerWeight; private String backPostMaterial; @@ -72,6 +73,7 @@ public String toString() { } class Instrument { + private String name; public Instrument() { diff --git a/src/com/codefortomorrow/intermediate/chapter12/solutions/TestTriangle.java b/src/com/codefortomorrow/intermediate/chapter12/solutions/TestTriangle.java index 855b809..a3d6241 100644 --- a/src/com/codefortomorrow/intermediate/chapter12/solutions/TestTriangle.java +++ b/src/com/codefortomorrow/intermediate/chapter12/solutions/TestTriangle.java @@ -44,6 +44,7 @@ public static void main(String[] args) { } class Triangle { + private double side1; private double side2; private double side3; diff --git a/src/com/codefortomorrow/intermediate/chapter12/solutions/TimeAndDate.java b/src/com/codefortomorrow/intermediate/chapter12/solutions/TimeAndDate.java index 8323ae6..f38238f 100644 --- a/src/com/codefortomorrow/intermediate/chapter12/solutions/TimeAndDate.java +++ b/src/com/codefortomorrow/intermediate/chapter12/solutions/TimeAndDate.java @@ -47,6 +47,7 @@ public static void main(String[] args) { } class MyTime { + public int hours; public int minutes; public int seconds; @@ -70,6 +71,7 @@ public String toString() { } class MyDate { + public int month; public int day; public int year; diff --git a/src/com/codefortomorrow/intermediate/chapter12/solutions/geometric/Circle.java b/src/com/codefortomorrow/intermediate/chapter12/solutions/geometric/Circle.java index 11523ed..40b158a 100644 --- a/src/com/codefortomorrow/intermediate/chapter12/solutions/geometric/Circle.java +++ b/src/com/codefortomorrow/intermediate/chapter12/solutions/geometric/Circle.java @@ -62,6 +62,7 @@ The getDistance() method returns the distance between this Shape and another Sha */ public class Circle extends Shape { + private double radius; /** Constructs a default Circle with radius 0 */ diff --git a/src/com/codefortomorrow/intermediate/chapter12/solutions/geometric/Rectangle.java b/src/com/codefortomorrow/intermediate/chapter12/solutions/geometric/Rectangle.java index f0277b5..9a3a040 100644 --- a/src/com/codefortomorrow/intermediate/chapter12/solutions/geometric/Rectangle.java +++ b/src/com/codefortomorrow/intermediate/chapter12/solutions/geometric/Rectangle.java @@ -62,6 +62,7 @@ The getDistance() method returns the distance between this Shape and another Sha */ public class Rectangle extends Shape { + private double length; private double width; diff --git a/src/com/codefortomorrow/intermediate/chapter12/solutions/geometric/Shape.java b/src/com/codefortomorrow/intermediate/chapter12/solutions/geometric/Shape.java index 095b8a0..edd5a8d 100644 --- a/src/com/codefortomorrow/intermediate/chapter12/solutions/geometric/Shape.java +++ b/src/com/codefortomorrow/intermediate/chapter12/solutions/geometric/Shape.java @@ -62,6 +62,7 @@ The getDistance() method returns the distance between this Shape and another Sha */ public class Shape { + public double x; // x coordinate of center of the shape public double y; // y coordinate of center of the shape diff --git a/src/com/codefortomorrow/intermediate/chapter12/solutions/pokemon/Battle.java b/src/com/codefortomorrow/intermediate/chapter12/solutions/pokemon/Battle.java index 9689388..8f94701 100644 --- a/src/com/codefortomorrow/intermediate/chapter12/solutions/pokemon/Battle.java +++ b/src/com/codefortomorrow/intermediate/chapter12/solutions/pokemon/Battle.java @@ -3,6 +3,7 @@ import java.util.Scanner; public class Battle { + private Scanner sc = new Scanner(System.in); private Pokemon pokemonOne; private Pokemon pokemonTwo; diff --git a/src/com/codefortomorrow/intermediate/chapter12/solutions/pokemon/Move.java b/src/com/codefortomorrow/intermediate/chapter12/solutions/pokemon/Move.java index 257c231..1f7f35a 100644 --- a/src/com/codefortomorrow/intermediate/chapter12/solutions/pokemon/Move.java +++ b/src/com/codefortomorrow/intermediate/chapter12/solutions/pokemon/Move.java @@ -4,6 +4,7 @@ * represents a Pokemon's move */ public class Move { + private String name; private boolean poisoning; private boolean sleeping; diff --git a/src/com/codefortomorrow/intermediate/chapter12/solutions/pokemon/Pokemon.java b/src/com/codefortomorrow/intermediate/chapter12/solutions/pokemon/Pokemon.java index 2050900..74fad5b 100644 --- a/src/com/codefortomorrow/intermediate/chapter12/solutions/pokemon/Pokemon.java +++ b/src/com/codefortomorrow/intermediate/chapter12/solutions/pokemon/Pokemon.java @@ -4,6 +4,7 @@ * represents a Pokemon object */ public class Pokemon { + private Move[] moveList; private int maxHP; private int currentHP;