├── .gitignore ├── README.md ├── Section 04 ├── Area Calculator │ └── src │ │ └── AreaCalculator.java ├── Barking Dog │ └── src │ │ └── BarkingDog.java ├── DecimalComparator │ └── src │ │ └── DecimalComparator.java ├── Equal Sum Checker │ └── src │ │ └── EqualSumChecker.java ├── Equality Printer │ └── src │ │ └── IntEqualityPrinter.java ├── Leap Year Calculator │ └── src │ │ └── LeapYear.java ├── MegaBytes Converter │ └── src │ │ └── MegaBytesConverter.java ├── Minutes To Years and Days Calculator │ └── src │ │ └── MinutesToYearsDaysCalculator.java ├── Playing Cat │ └── src │ │ └── PlayingCat.java ├── Speed Converter │ └── src │ │ └── SpeedConverter.java └── Teen Number Checker │ └── src │ └── TeenNumberChecker.java ├── Section 05 ├── All Factors │ └── src │ │ └── FactorPrinter.java ├── Diagonal Star │ └── src │ │ └── DiagonalStar.java ├── Even Digit Sum │ └── src │ │ └── EvenDigitSum.java ├── First And Last Digit Sum │ └── src │ │ └── FirstLastDigitSum.java ├── Flour Pack Problem │ └── src │ │ └── FlourPacker.java ├── Greatest Common Divisor │ └── src │ │ └── GreatestCommonDivisor.java ├── Input Calculator │ └── src │ │ └── InputCalculator.java ├── Largest Prime │ └── src │ │ └── LargestPrime.java ├── Last Digit Checker │ └── src │ │ └── LastDigitChecker.java ├── Number In Word │ └── src │ │ └── NumberInWord.java ├── Number Of Days In Month │ └── src │ │ └── NumberOfDaysInMonth.java ├── Number Palindrome │ └── src │ │ └── NumberPalindrome.java ├── Number To Words │ └── src │ │ └── NumberToWords.java ├── Paint Job │ └── src │ │ └── PaintJob.java ├── Perfect Number │ └── src │ │ └── PerfectNumber.java ├── Shared Digit │ └── src │ │ └── SharedDigit.java └── Sum Odd │ └── src │ └── SumOddRange.java ├── Section 06 ├── Carpet Cost Calculator │ └── src │ │ ├── Calculator.java │ │ ├── Carpet.java │ │ ├── Floor.java │ │ └── Main.java ├── Complex Operations │ └── src │ │ └── ComplexNumber.java ├── Constructor Challenge │ └── src │ │ ├── Account.java │ │ ├── Main.java │ │ └── VipCustomer.java ├── Cylinder │ └── src │ │ ├── Circle.java │ │ ├── Cylinder.java │ │ └── Main.java ├── Inheritance Challenge │ └── src │ │ ├── Car.java │ │ ├── Main.java │ │ ├── Outlander.java │ │ └── Vehicle.java ├── Person │ └── src │ │ └── Person.java ├── Point │ └── src │ │ └── Point.java ├── Pool Area │ └── src │ │ ├── Cuboid.java │ │ ├── Main.java │ │ └── Rectangle.java ├── Sum Calculator │ └── src │ │ └── SimpleCalculator.java └── Wall Area │ └── src │ └── Wall.java ├── Section 07 ├── Composition Challenge │ └── src │ │ ├── Bed.java │ │ ├── Bedroom.java │ │ ├── Ceiling.java │ │ ├── Lamp.java │ │ ├── Main.java │ │ └── Wall.java ├── Encapsulation Challenge │ └── src │ │ ├── Main.java │ │ └── Printer.java ├── OOP Master Challenge │ └── src │ │ ├── DeluxeBurger.java │ │ ├── Hamburger.java │ │ ├── HealthyBurger.java │ │ └── Main.java └── Polymorphism Challenge │ └── src │ ├── Bugatti.java │ ├── Car.java │ ├── Ferrari.java │ ├── Lamborghini.java │ └── Main.java ├── Section 08 ├── Array Challenge │ └── src │ │ └── Main.java ├── ArrayList Challenge │ └── src │ │ ├── Contact.java │ │ ├── Main.java │ │ └── MobilePhone.java ├── Autoboxing & Unboxing Challenge │ └── src │ │ ├── Bank.java │ │ ├── Branch.java │ │ ├── Customer.java │ │ └── Main.java ├── LinkedList Challenge │ └── src │ │ ├── Album.java │ │ ├── Main.java │ │ └── Song.java ├── Minimum Element Challenge │ └── src │ │ └── Main.java └── Reverse Array Challenge │ └── src │ └── Main.java ├── Section 09 ├── Abstract Class Challenge │ └── src │ │ ├── ListItem.java │ │ ├── Main.java │ │ ├── MyLinkedList.java │ │ ├── Node.java │ │ ├── NodeList.java │ │ └── SearchTree.java ├── Inner Class Challenge │ └── src │ │ ├── Album.java │ │ ├── Main.java │ │ └── Song.java └── Interfaces Challenge │ └── src │ ├── ISaveable.java │ ├── Main.java │ ├── Monster.java │ └── Player.java ├── Section 10 └── Generics Challenge │ └── src │ ├── BaseballTeam.java │ ├── FootballTeam.java │ ├── League.java │ ├── Main.java │ ├── SoccerTeam.java │ └── Team.java ├── Section 11 ├── Package Challenge │ ├── Package Challenge │ │ └── src │ │ │ └── com │ │ │ └── example │ │ │ └── Series.java │ └── SeriesTest │ │ └── src │ │ └── com │ │ └── example │ │ └── test │ │ └── Main.java └── Scope Challenge │ └── src │ ├── Main.java │ └── X.java ├── Section 12 ├── Adventure Game Challenge │ └── src │ │ ├── Location.java │ │ └── Main.java ├── Collections Challenge │ └── src │ │ ├── Basket.java │ │ ├── Main.java │ │ ├── StockItem.java │ │ └── StockList.java ├── Immutable Class Challenge │ └── src │ │ ├── Location.java │ │ └── Main.java └── Set Challenge │ └── src │ ├── DwarfPlanet.java │ ├── HeavenlyBody.java │ ├── Main.java │ ├── Moon.java │ ├── Planet.java │ └── Star.java ├── Section 13 └── JavaFX Challenge │ └── src │ ├── module-info.java │ └── sample │ ├── ContactController.java │ ├── Controller.java │ ├── Main.java │ ├── contactdialog.fxml │ ├── datamodel │ ├── Contact.java │ └── ContactData.java │ └── main.fxml ├── Section 14 ├── Input and Output Challenge 1 │ ├── directions.txt │ ├── directions_big.txt │ ├── locations.txt │ ├── locations_big.txt │ └── src │ │ ├── Location.java │ │ ├── Locations.java │ │ └── Main.java └── Input and Output Challenge 2 │ ├── directions.txt │ ├── directions_big.txt │ ├── locations.txt │ ├── locations_big.txt │ └── src │ ├── Location.java │ ├── Locations.java │ └── Main.java ├── Section 15 ├── Concurrency Challenge 1 │ └── src │ │ ├── BankAccount.java │ │ └── Main.java ├── Concurrency Challenge 2 │ └── src │ │ ├── BankAccount.java │ │ └── Main.java ├── Concurrency Challenge 3 │ └── src │ │ ├── BankAccount.java │ │ └── Main.java ├── Concurrency Challenge 4 │ └── src │ │ ├── BankAccount.java │ │ └── Main.java ├── Concurrency Challenge 5 │ └── src │ │ ├── BankAccount.java │ │ └── Main.java ├── Concurrency Challenge 6 │ └── src │ │ ├── BankAccount.java │ │ └── Main.java ├── Concurrency Challenge 7 │ └── src │ │ ├── BankAccount.java │ │ ├── Main.java │ │ └── Transfer.java ├── Concurrency Challenge 8 │ └── src │ │ ├── Main.java │ │ ├── Student.java │ │ └── Tutor.java └── Concurrency Challenge 9 │ └── src │ ├── Main.java │ ├── NewStudent.java │ └── NewTutor.java ├── Section 16 ├── Lambda Challenge 1 │ └── src │ │ └── Main.java ├── Lambda Challenge 10 │ └── src │ │ └── Main.java ├── Lambda Challenge 11 │ └── src │ │ └── Main.java ├── Lambda Challenge 12 │ └── src │ │ └── Main.java ├── Lambda Challenge 13 │ └── src │ │ └── Main.java ├── Lambda Challenge 2 │ └── src │ │ └── Main.java ├── Lambda Challenge 3 │ └── src │ │ └── Main.java ├── Lambda Challenge 4 │ └── src │ │ └── Main.java ├── Lambda Challenge 5 │ └── src │ │ └── Main.java ├── Lambda Challenge 6 │ └── src │ │ └── Main.java ├── Lambda Challenge 7 │ └── src │ │ └── Main.java ├── Lambda Challenge 8 │ └── src │ │ └── Main.java └── Lambda Challenge 9 │ └── src │ └── Main.java ├── Section 17 ├── Regular Expressions Challenge 1 │ └── src │ │ └── Main.java ├── Regular Expressions Challenge 10 │ └── src │ │ └── Main.java ├── Regular Expressions Challenge 11 │ └── src │ │ └── Main.java ├── Regular Expressions Challenge 12 │ └── src │ │ └── Main.java ├── Regular Expressions Challenge 13 │ └── src │ │ └── Main.java ├── Regular Expressions Challenge 14 │ └── src │ │ └── Main.java ├── Regular Expressions Challenge 2 │ └── src │ │ └── Main.java ├── Regular Expressions Challenge 3 │ └── src │ │ └── Main.java ├── Regular Expressions Challenge 4 │ └── src │ │ └── Main.java ├── Regular Expressions Challenge 5 │ └── src │ │ └── Main.java ├── Regular Expressions Challenge 6 │ └── src │ │ └── Main.java ├── Regular Expressions Challenge 7 │ └── src │ │ └── Main.java ├── Regular Expressions Challenge 8 │ └── src │ │ └── Main.java └── Regular Expressions Challenge 9 │ └── src │ └── Main.java ├── Section 18 ├── JUnit Challenge 1 │ └── src │ │ ├── Main.java │ │ ├── Utilities.java │ │ └── UtilitiesTest.java ├── JUnit Challenge 10 │ └── src │ │ ├── Main.java │ │ ├── Utilities.java │ │ ├── UtilitiesTest.java │ │ └── UtilitiesTestParameterized.java ├── JUnit Challenge 2 │ └── src │ │ ├── Main.java │ │ ├── Utilities.java │ │ └── UtilitiesTest.java ├── JUnit Challenge 3 │ └── src │ │ ├── Main.java │ │ ├── Utilities.java │ │ └── UtilitiesTest.java ├── JUnit Challenge 4 │ └── src │ │ ├── Main.java │ │ ├── Utilities.java │ │ └── UtilitiesTest.java ├── JUnit Challenge 5 │ └── src │ │ ├── Main.java │ │ ├── Utilities.java │ │ └── UtilitiesTest.java ├── JUnit Challenge 6 │ └── src │ │ ├── Main.java │ │ ├── Utilities.java │ │ └── UtilitiesTest.java ├── JUnit Challenge 7 │ └── src │ │ ├── Main.java │ │ ├── Utilities.java │ │ └── UtilitiesTest.java ├── JUnit Challenge 8 │ └── src │ │ ├── Main.java │ │ ├── Utilities.java │ │ └── UtilitiesTest.java └── JUnit Challenge 9 │ └── src │ ├── Main.java │ ├── Utilities.java │ └── UtilitiesTest.java ├── Section 19 ├── challenge.sql └── music.db ├── Section 22 └── Module Challenge │ ├── academy.learnprogramming.common │ └── src │ │ ├── academy │ │ └── learnprogramming │ │ │ └── common │ │ │ ├── Album.java │ │ │ └── Artist.java │ │ └── module-info.java │ ├── academy.learnprogramming.db │ └── src │ │ ├── academy │ │ └── learnprogramming │ │ │ └── db │ │ │ └── DataSource.java │ │ └── module-info.java │ ├── academy.learnprogramming.ui │ └── src │ │ ├── academy │ │ └── learnprogramming │ │ │ └── ui │ │ │ ├── Controller.java │ │ │ ├── Main.java │ │ │ └── main.fxml │ │ └── module-info.java │ ├── libs │ └── sqlite-jdbc-3.21.0.jar │ └── music.db └── certificate.jpg /.gitignore: -------------------------------------------------------------------------------- 1 | out/ 2 | *.xml 3 | *.iml 4 | .idea -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Java Programming Masterclass for Software Developers 2 | All coursework for the Java Programming Masterclass for Software Developers by Tim Buchalka (Learn Programming Academy teacher). 3 | 4 | [The Course at Udemy](https://www.udemy.com/java-the-complete-java-developer-course) 5 | [The Learn Programming Academy](http://learnprogramming.academy) 6 | 7 | ![Certificate](certificate.jpg) 8 | 9 | ## Curriculum 10 | 11 | - [x] Section 01 - Course Introduction 12 | - [x] Section 02 - Setup and First Steps 13 | - [x] Section 03 - Variables, Datatypes and Operators 14 | - [x] Section 04 - Expressions, Statements, Code blocks, Methods and more 15 | - [x] Section 05 - Control Flow Statements 16 | - [x] Section 06 - OOP Part 1 - Classes, Constructors and Inheritance 17 | - [x] Section 07 - OOP Part 2 - Composition, Encapsulation, and Polymorphism 18 | - [x] Section 08 - Arrays, Java inbuilt Lists, Autoboxing and Unboxing 19 | - [x] Section 09 - Inner and Abstract Classes & Interfaces 20 | - [x] Section 10 - Java Generics 21 | - [x] Section 11 - Naming Conventions and Packages static and final keywords 22 | - [x] Section 12 - Java Collections 23 | - [x] Section 13 - JavaFX 24 | - [x] Section 14 - Basic Input & Output including java.util 25 | - [x] Section 15 - Concurrency in Java 26 | - [x] Section 16 - Lambda Expressions 27 | - [x] Section 17 - Regular Expressions 28 | - [x] Section 18 - Debugging and Unit Testing 29 | - [x] Section 19 - Databases 30 | - [x] Section 20 - Java Networking Programming 31 | - [x] Section 21 - Java 9 Module System 32 | - [x] Section 22 - Migrating Java Projects to Java 9 33 | - [x] Section 23 - Archived Videos 34 | - [x] Section 24 - Bonus Material 35 | -------------------------------------------------------------------------------- /Section 04/Area Calculator/src/AreaCalculator.java: -------------------------------------------------------------------------------- 1 | public class AreaCalculator { 2 | public static double area(double radius) { 3 | if (radius < 0) { 4 | return -1.0; 5 | } 6 | return radius * radius * 3.14159; 7 | } 8 | 9 | public static double area(double x, double y) { 10 | if (x < 0 || y < 0) { 11 | return -1.0; 12 | } 13 | return x * y; 14 | } 15 | 16 | public static void main(String[] args) { 17 | /* 18 | Write a method named area with one double parameter named radios. 19 | The method need to return a double value that represents the area of a circle. 20 | If the parameter radius is negative then return -1.0 to represent an invalid value. 21 | 22 | Write another overloaded method with 2 parameters x and y (both doubles), 23 | where x and y represent the sides of a rectangle. 24 | The method need to return an area of an rectangle. 25 | If either or both parameters is/are a negative return -1.0 to indicate an invalid value. 26 | For formulas and PI value please check the tips below. 27 | 28 | Examples of input/output: 29 | * area(5.0); should return 78.53975 30 | * area(-1); should return -1 since the parameter is negative 31 | * area(5.0, 4.0); should return 20.0 (5 * 4 = 20) 32 | * area(-1.0, 4.0); should return -1 since the first parameter is negative. 33 | */ 34 | System.out.println(area(5.0)); 35 | System.out.println(area(-1)); 36 | System.out.println(area(5.0, 4.0)); 37 | System.out.println(area(-1.0, 4.0)); 38 | } 39 | } -------------------------------------------------------------------------------- /Section 04/Barking Dog/src/BarkingDog.java: -------------------------------------------------------------------------------- 1 | public class BarkingDog { 2 | public static boolean shouldWakeUp(boolean barking, int hourOfDay) { 3 | if (hourOfDay < 0 || hourOfDay > 23) { 4 | return false; 5 | } 6 | return barking && (hourOfDay < 8 || hourOfDay > 22); 7 | } 8 | 9 | public static void main(String[] args) { 10 | /* 11 | We have a dog that likes to bark. We need to wake up if the dog is barking at night! 12 | Write a method shouldWakeUp that has 2 parameters. 13 | 1st parameter should be of type boolean and be named barking it represents if our dog is currently barking. 14 | 2nd parameter represents the hour of the day and is of type int with the name hourOfDay and has a valid range of 0-23. 15 | We have to wake up if the dog is barking before 8 or after 22 hours so in that case return true. 16 | In all other cases return false. 17 | If the hourOfDay parameter is less than 0 or greater than 23 return false. 18 | 19 | Examples of input/output: 20 | * shouldWakeUp(true, 1); -> should return true 21 | * shouldWakeUp(false, 2); -> should return false since the dog is not barking. 22 | * shouldWakeUp(true, 8); -> should return false, since it's not before 8. 23 | * shouldWakeUp(true, 1); -> should return false since the hourOfDay parameter need to be in a range 0-23. 24 | */ 25 | System.out.println(shouldWakeUp(true, 1)); 26 | System.out.println(shouldWakeUp(false, 2)); 27 | System.out.println(shouldWakeUp(true, 8)); 28 | System.out.println(shouldWakeUp(true, -1)); 29 | } 30 | } -------------------------------------------------------------------------------- /Section 04/DecimalComparator/src/DecimalComparator.java: -------------------------------------------------------------------------------- 1 | public class DecimalComparator { 2 | public static boolean areEqualByThreeDecimalPlaces(double d1, double d2) { 3 | long first = (long) (d1 * 1000); 4 | long second = (long) (d2 * 1000); 5 | return first == second; 6 | } 7 | 8 | public static void main(String[] args) { 9 | /* 10 | Write a method areEqualByThreeDecimalPlaces with two parameters of type double. 11 | The method should return boolean and it needs to return true if two double numbers 12 | are the same up to three decimal places. Otherwise, return false. 13 | 14 | Examples of input/output: 15 | * areEqualByThreeDecimalPlaces(-3.1756, -3.175); -> should return true since numbers are equal up to 3 decimal places. 16 | * areEqualByThreeDecimalPlaces(3.175, 3.176); -> should return false since numbers are not equal up to 3 decimal places. 17 | * areEqualByThreeDecimalPlaces(3.0, 3.0); -> should return true since numbers are equal up to 3 decimal places. 18 | * areEqualByThreeDecimalPlaces(-3.123, 3.123); -> should return false since numbers are not equal up to 3 decimal places. 19 | */ 20 | System.out.println(areEqualByThreeDecimalPlaces(-3.1756, -3.175)); 21 | System.out.println(areEqualByThreeDecimalPlaces(3.175, 3.176)); 22 | System.out.println(areEqualByThreeDecimalPlaces(3.0, 3.0)); 23 | System.out.println(areEqualByThreeDecimalPlaces(-3.123, 3.123)); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Section 04/Equal Sum Checker/src/EqualSumChecker.java: -------------------------------------------------------------------------------- 1 | public class EqualSumChecker { 2 | public static boolean hasEqualSum(int n1, int n2, int n3) { 3 | int sum = n1 + n2; 4 | return sum == n3; 5 | } 6 | 7 | public static void main(String[] args) { 8 | /* 9 | Write a method hasEqualSum with 3 parameters of type int. 10 | The method should return boolean and it need to return true 11 | if the sum of the first and second parameter is equal to the third parameter. 12 | Otherwise, return false. 13 | 14 | Examples of input/output: 15 | * hasEqualSum(1, 1, 1); -> should return false since 1 + 1 is not equal to 1 16 | * hasEqualSum(1, 1, 2); -> should return true since 1 + 1 is equal to 2 17 | * hasEqualSum(1, -1, 0); -> should return true since 1 + (-1) is 1 - 1 and is equal to 0 18 | */ 19 | System.out.println(hasEqualSum(1, 1, 1)); 20 | System.out.println(hasEqualSum(1, 1, 2)); 21 | System.out.println(hasEqualSum(1, -1, 0)); 22 | } 23 | } -------------------------------------------------------------------------------- /Section 04/Equality Printer/src/IntEqualityPrinter.java: -------------------------------------------------------------------------------- 1 | public class IntEqualityPrinter { 2 | public static void printEqual(int n1, int n2, int n3) { 3 | if (n1 >= 0 && n2 >= 0 && n3 >= 0) { 4 | if (n1 == n2 && n1 == n3) { 5 | System.out.println("All numbers are equal"); 6 | } else if (n1 != n2 && n1 != n3 && n2 != n3) { 7 | System.out.println("All numbers are different"); 8 | } else { 9 | System.out.println("Neither all are equal or different"); 10 | } 11 | } else { 12 | System.out.println("Invalid Value"); 13 | } 14 | } 15 | 16 | public static void main(String[] args) { 17 | /* 18 | Write a method printEqual with 3 parameters of type int. The method should not return anything (void). 19 | If one of the parameters is less then 0, print text "Invalid Value". 20 | If all numbers are equal print text "All numbers are equal". 21 | If all numbers are different print text "All numbers are different". 22 | Otherwise, print "Neither all are equal or different". 23 | 24 | Examples of input/output: 25 | * printEqual(1, 1, 1); should print text All numbers are equal 26 | * printEqual(1, 1, 2); should print text Neither all are equal or different 27 | * printEqual(-1, -1, -1); should print text Invalid Value 28 | * printEqual(1, 2, 3); should print text All numbers are different 29 | */ 30 | printEqual(1, 1, 1); 31 | printEqual(1, 1, 2); 32 | printEqual(-1, -1, -1); 33 | printEqual(1, 2, 3); 34 | } 35 | } -------------------------------------------------------------------------------- /Section 04/Leap Year Calculator/src/LeapYear.java: -------------------------------------------------------------------------------- 1 | public class LeapYear { 2 | public static boolean isLeapYear(int year) { 3 | if (year >= 1 && year <= 9999) { 4 | return year % 4 == 0 && year % 100 != 0 || year % 400 == 0; 5 | } 6 | return false; 7 | } 8 | 9 | public static void main(String[] args) { 10 | /* 11 | Write a method isLeapYear with a parameter of type int named year. 12 | The parameter needs to be greater than or equal to 1 and less than or equal to 9999. 13 | If the parameter is not in that range return false. 14 | Otherwise, if it is in the valid range, calculate if the year is leap year and return true if it is a leap year, 15 | otherwise return false. 16 | 17 | To determine whether a year is a leap year, follow these steps: 18 | 1. If the year is evenly divisible by 4, go to step 2. Otherwise, go to step 5. 19 | 2. If the year is evenly divisible by 100, go to step 3. Otherwise, go to step 4. 20 | 3. If the year is evenly divisible by 400, go to step 4. Otherwise, go to step 5. 21 | 4. The year is a leap year (it has 366 days). The method isLeapYear need to return true. 22 | 5. The year is not a leap year (it has 365 days). The method isLeapYear needs to return false. 23 | 24 | The following years are not leap years: 25 | 1700, 1800, 1900, 2100, 2200, 2300, 2500, 2600 26 | This is because they are evenly divisible by 100 but not 400. 27 | 28 | The following years are leap years: 29 | 1600, 2000, 2400 30 | This is because they are evenly divisible by both 100 and 400. 31 | 32 | Examples of input/output: 33 | * isLeapYear(-1600); -> should return false since the parameter is not in range (1-9999) 34 | * isLeapYear(1600); -> should return true since 1600 is a leap year 35 | * isLeapYear(2017); -> should return false since 2017 is not a leap year 36 | * isLeapYear(2000); -> should return true because 2000 is a leap year 37 | */ 38 | System.out.println(isLeapYear(-1600)); 39 | System.out.println(isLeapYear(1600)); 40 | System.out.println(isLeapYear(2017)); 41 | System.out.println(isLeapYear(2000)); 42 | } 43 | } -------------------------------------------------------------------------------- /Section 04/MegaBytes Converter/src/MegaBytesConverter.java: -------------------------------------------------------------------------------- 1 | public class MegaBytesConverter { 2 | public static void printMegaBytesAndKiloBytes(int kiloBytes) { 3 | int megaBytes = kiloBytes / 1024; 4 | int remainder = kiloBytes % 1024; 5 | 6 | if (kiloBytes < 0) { 7 | System.out.println("Invalid Value"); 8 | } else { 9 | System.out.println(kiloBytes + " KB = " + megaBytes + " MB and " + remainder + " KB"); 10 | } 11 | } 12 | 13 | public static void main(String[] args) { 14 | /* 15 | Write a method called printMegaBytesAndKiloBytes that has 1 parameter of type int with the name kiloBytes. 16 | The method should not return anything (void) and it needs to calculate the megabytes and remaining kilobytes from 17 | the kilobytes parameter. 18 | Then it need to print a message in the format "XX KB = YY MB and ZZ KB". 19 | XX represents the original value kiloBytes. 20 | YY represents the calculated megabytes. 21 | ZZ represents the calculated remaining kilobytes. 22 | For example, when the parameter kiloBytes is 2500 it need to print "2500 KB = 2 MB and 452 KB" 23 | If the parameter kiloBytes is less than 0 then print the text "Invalid Value". 24 | 25 | Examples input/output 26 | * printMegabyesAndKiloBytes(2500); -> should print the following text: "2500 KB = 2 MB and 452 KB" 27 | * printMegabyesAndKiloBytes(-1024); -> should print the following text: "Invalid Value" because parameter is less than 0. 28 | * printMegabyesAndKiloBytes(5000); -> should print the following text: "5000 KB = 4 MB and 904 KB" 29 | */ 30 | printMegaBytesAndKiloBytes(2500); 31 | printMegaBytesAndKiloBytes(-1024); 32 | printMegaBytesAndKiloBytes(5000); 33 | } 34 | } -------------------------------------------------------------------------------- /Section 04/Minutes To Years and Days Calculator/src/MinutesToYearsDaysCalculator.java: -------------------------------------------------------------------------------- 1 | public class MinutesToYearsDaysCalculator { 2 | public static void printYearsAndDays(long minutes) { 3 | if (minutes < 0) { 4 | System.out.println("Invalid Value"); 5 | } else { 6 | long years = minutes / 525600, 7 | remainingMinutes = minutes % 525600, 8 | days = remainingMinutes / 1440; 9 | System.out.println(minutes + " min = " + years + " y and " + days + " d"); 10 | } 11 | } 12 | 13 | public static void main(String[] args) { 14 | /* 15 | Write a method printYearsAndDays with parameter of type long named minutes. 16 | The method should not return anything (void) and it need to calculate the years and days from the minutes parameter. 17 | If the parameter is less than 0, print text "Invalid Value". 18 | Otherwise, if the parameter is valid then it need to print a message in the format "XX min = YY y and ZZ d". 19 | XX represents the original value minutes. 20 | YY represents the calculated years. 21 | ZZ represents the calculated days. 22 | 23 | Examples of input/output: 24 | * printYearsAndDays(525600); -> should print "525600 min = 1 y and 0 d" 25 | * printYearsAndDays(1051200); -> should print "1051200 min = 2 y and 0 d" 26 | * printYearsAndDays(561600); -> should print "561600 min = 1 y and 25 d" 27 | */ 28 | printYearsAndDays(525600); 29 | printYearsAndDays(1051200); 30 | printYearsAndDays(561600); 31 | } 32 | } -------------------------------------------------------------------------------- /Section 04/Playing Cat/src/PlayingCat.java: -------------------------------------------------------------------------------- 1 | public class PlayingCat { 2 | public static boolean isCatPlaying(boolean summer, int temperature) { 3 | if (summer) { 4 | return temperature > 24 && temperature < 46; 5 | } else { 6 | return temperature > 24 && temperature < 36; 7 | } 8 | } 9 | 10 | public static void main(String[] args) { 11 | /* 12 | The cats spend most of the day playing. 13 | In particular, they play if the temperature is between 25 and 35 (inclusive). 14 | Unless it is summer, then the upper limit is 45 (inclusive) instead of 35. 15 | Write a method isCatPlaying that has 2 parameters. 16 | Method need to return true if the cat is playing, otherwise return false. 17 | 1st parameter should be of type boolean and be named summer it represents if it is summer. 18 | 2nd parameter represents the temperature and is of type int with the name temperature. 19 | 20 | Examples of input/output: 21 | * isCatPlaying(true, 10); should return false since temperature is not in range 25 - 45 22 | * isCatPlaying(false, 36); should return false since temperature is not in range 25 - 35 (summer parameter is false) 23 | * isCatPlaying(false, 35); should return true since temperature is in range 25 - 35 24 | */ 25 | System.out.println(isCatPlaying(true, 10)); 26 | System.out.println(isCatPlaying(false, 36)); 27 | System.out.println(isCatPlaying(false, 35)); 28 | } 29 | } -------------------------------------------------------------------------------- /Section 04/Teen Number Checker/src/TeenNumberChecker.java: -------------------------------------------------------------------------------- 1 | public class TeenNumberChecker { 2 | public static boolean hasTeen(int a, int b, int c) { 3 | return isTeen(a) || isTeen(b) || isTeen(c); 4 | } 5 | 6 | public static boolean isTeen(int age) { 7 | return age >= 13 && age <= 19; 8 | } 9 | 10 | public static void main(String[] args) { 11 | /* 12 | We'll say that a number is "teen" if it is in the range 13-19 (inclusive). 13 | Write a method named hasTeen with 3 parameters of type int. 14 | The method should return boolean and it need to return true 15 | if one of the parameters is in range 13 (inclusive) - 19. 16 | Otherwise return false. 17 | 18 | Examples of input/output: 19 | * hasTeen(9, 99, 19); should return true since 19 is in range 13 - 19 20 | * hasTeen(23, 15, 42); should return true since 15 is in range 13 - 19 21 | * hasTeen(22, 23, 34); should return false since numbers 22, 23, 34 are not in range 13-19 22 | 23 | Write a method named isTeen with 1 parameter of type int. 24 | The method should return boolean and it need to return true 25 | if the parameter is in range 13 (inclusive) - 19 (inclusive). 26 | Otherwise return false. 27 | */ 28 | System.out.println(hasTeen(9, 99, 999)); 29 | System.out.println(hasTeen(23, 15, 42)); 30 | System.out.println(hasTeen(22, 23, 34)); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Section 05/All Factors/src/FactorPrinter.java: -------------------------------------------------------------------------------- 1 | public class FactorPrinter { 2 | public static void printFactors(int number) { 3 | if (number >= 0) { 4 | for (int i = 1; i <= number; i++) { 5 | if (number % i == 0) { 6 | System.out.println(i); 7 | } 8 | } 9 | } else { 10 | System.out.println("Invalid Value"); 11 | } 12 | } 13 | 14 | public static void main(String[] args) { 15 | /* 16 | Write a method named printFactors with one parameter of type int named number. 17 | If number is < 1, the method should print "Invalid Value". 18 | The method should print all factors of the number. 19 | A factor of a number is an integer which divides that number wholly (i.e. without leaving a remainder). 20 | For example, 3 is a factor of 6 because 3 fully divides 6 without leaving a remainder. In other words 6 / 3 = 2. 21 | 22 | EXAMPLE INPUT/OUTPUT: 23 | * printFactors(6); → should print 1 2 3 6 24 | * printFactors(32); → should print 1 2 4 8 16 32 25 | * printFactors(10); → should print 1 2 5 10 26 | * printFactors(-1); → should print "Invalid Value" since number is < 1 27 | 28 | HINT: Use a while or for loop. 29 | 30 | NOTE: When printing numbers, each number can be in its own line. They don't have to be separated by a space. 31 | 32 | For example, the printout for printFactors(10); can be: 33 | 34 | 1 35 | 2 36 | 5 37 | 10 38 | */ 39 | printFactors(6); 40 | printFactors(32); 41 | printFactors(10); 42 | printFactors(-1); 43 | } 44 | } -------------------------------------------------------------------------------- /Section 05/Even Digit Sum/src/EvenDigitSum.java: -------------------------------------------------------------------------------- 1 | public class EvenDigitSum { 2 | public static int getEvenDigitSum(int number) { 3 | if (number < 0) { 4 | return -1; 5 | } 6 | 7 | int sum = 0; 8 | while (number > 0) { 9 | int digit = number % 10; 10 | if (digit % 2 == 0) { 11 | sum += digit; 12 | } 13 | number /= 10; 14 | } 15 | return sum; 16 | } 17 | 18 | public static void main(String[] args) { 19 | /* 20 | Write a method named getEvenDigitSum with one parameter of type int called number. 21 | The method should return the sum of the even digits within the number. 22 | If the number is negative, the method should return -1 to indicate an invalid value. 23 | 24 | Example input/output: 25 | * getEvenDigitSum(123456789); -> should return 20 since 2 + 4 + 6 + 8 = 20 26 | * getEvenDigitSum(252); -> should return 4 since 2 + 2 = 4 27 | * getEvenDigitSum(252); -> should return -1 since the number is negative 28 | */ 29 | System.out.println(getEvenDigitSum(123456789)); 30 | System.out.println(getEvenDigitSum(252)); 31 | System.out.println(getEvenDigitSum(-22)); 32 | } 33 | } -------------------------------------------------------------------------------- /Section 05/First And Last Digit Sum/src/FirstLastDigitSum.java: -------------------------------------------------------------------------------- 1 | public class FirstLastDigitSum { 2 | public static int sumFirstAndLastDigit(int number) { 3 | int result = -1; 4 | if (number >= 0) { 5 | int temp = number; 6 | while (temp > 9) { 7 | temp = temp / 10; 8 | } 9 | result = temp + number % 10; 10 | } 11 | return result; 12 | } 13 | 14 | public static void main(String[] args) { 15 | /* 16 | Write a method named sumFirstAndLastDigit with one parameter of type int called number. 17 | The method need to find the first and the last digit of the parameter number passed to the method, 18 | using a loop and return the sum of the first and the last digit of that number. 19 | If the number is negative then the method needs to return -1 to indicate an invalid value. 20 | 21 | Example input/output: 22 | * sumFirstAndLastDigit(252); -> should return 4, the first digit is 2 and the last is 2 which gives us 2+2 and the sum is 4. 23 | * sumFirstAndLastDigit(257); -> should return 9, the first digit is 2 and the last is 7 which gives us 2+7 and the sum is 9. 24 | * sumFirstAndLastDigit(0); -> should return 0, the first digit and the last is 0 since we only have 1 digit, which gives us 0+0 and the sum is 0. 25 | * sumFirstAndLastDigit(5); -> should return 10, the first digit and the last is 5 since we only have 1 digit, which gives us 5+5 and the sum is 10. 26 | */ 27 | System.out.println(sumFirstAndLastDigit(252)); 28 | System.out.println(sumFirstAndLastDigit(257)); 29 | System.out.println(sumFirstAndLastDigit(0)); 30 | System.out.println(sumFirstAndLastDigit(5)); 31 | } 32 | } -------------------------------------------------------------------------------- /Section 05/Greatest Common Divisor/src/GreatestCommonDivisor.java: -------------------------------------------------------------------------------- 1 | public class GreatestCommonDivisor { 2 | public static int getGreatestCommonDivisor(int first, int second) { 3 | if (first < 10 || second < 10) { 4 | return -1; 5 | } 6 | for (int i = first; i > 0; i--) { 7 | if (first % i == 0 && second % i == 0) { 8 | return i; 9 | } 10 | } 11 | return 0; 12 | } 13 | 14 | public static void main(String[] args) { 15 | /* 16 | Write a method named getGreatestCommonDivisor with two parameters of type int named first and second. 17 | If one of the parameters is < 10, the method should return -1 to indicate an invalid value. 18 | The method should return the greatest common divisor of the two numbers (int). 19 | The greatest common divisor is the largest positive integer that can fully divide each of the integers (i.e. without leaving a remainder). 20 | 21 | For example 12 and 30: 22 | 12 can be divided by 1, 2, 3, 4, 6, 12 23 | 30 can be divided by 1, 2, 3, 5, 6, 10, 15, 30 24 | The greatest common divisor is 6 since both 12 and 30 can be divided by 6, and there is no resulting remainder. 25 | 26 | EXAMPLE INPUT/OUTPUT: 27 | * getGreatestCommonDivisor(25, 15); should return 5 since both can be divided by 5 without a remainder 28 | * getGreatestCommonDivisor(12, 30); should return 6 since both can be divided by 6 without a remainder 29 | * getGreatestCommonDivisor(9, 18); should return -1 since the first parameter is < 10 30 | * getGreatestCommonDivisor(81, 153); should return 9 since both can be divided by 9 without a remainder 31 | */ 32 | System.out.println(getGreatestCommonDivisor(25, 15)); 33 | System.out.println(getGreatestCommonDivisor(12, 30)); 34 | System.out.println(getGreatestCommonDivisor(9, 18)); 35 | System.out.println(getGreatestCommonDivisor(81, 153)); 36 | } 37 | } -------------------------------------------------------------------------------- /Section 05/Input Calculator/src/InputCalculator.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class InputCalculator { 4 | public static void inputThenPrintSumAndAverage() { 5 | int counter = 0, number = 0; 6 | Scanner scanner = new Scanner(System.in); 7 | if (scanner.hasNextInt()) { 8 | while (scanner.hasNextInt()) { 9 | number += scanner.nextInt(); 10 | counter++; 11 | } 12 | scanner.close(); 13 | System.out.format("SUM = %d AVG = %d", number, Math.round((double) number / counter)); 14 | } else { 15 | System.out.println("SUM = 0 AVG = 0"); 16 | } 17 | } 18 | 19 | public static void main(String[] args) { 20 | /* 21 | Write a method called inputThenPrintSumAndAverage that does not have any parameters. 22 | The method should not return anything (void) and it needs to keep reading int numbers from the keyboard. 23 | When the user enters something that is not an int then it needs to print a message in the format "SUM = XX AVG = YY". 24 | 25 | XX represents the sum of all entered numbers of type int. 26 | YY represents the calculated average of all numbers of type long. 27 | 28 | EXAMPLES OF INPUT/OUTPUT: 29 | 30 | EXAMPLE 1: 31 | 32 | INPUT: 33 | 34 | 1 35 | 2 36 | 3 37 | 4 38 | 5 39 | a 40 | 41 | OUTPUT 42 | 43 | SUM = 15 AVG = 3 44 | 45 | 46 | EXAMPLE 2: 47 | 48 | INPUT: 49 | 50 | hello 51 | 52 | OUTPUT: 53 | 54 | SUM = 0 AVG = 0 55 | */ 56 | inputThenPrintSumAndAverage(); 57 | } 58 | } -------------------------------------------------------------------------------- /Section 05/Largest Prime/src/LargestPrime.java: -------------------------------------------------------------------------------- 1 | public class LargestPrime { 2 | public static int getLargestPrime(int number) { 3 | if (number >= 2) { 4 | for (int i = 2; i < number; i++) { 5 | if (number % i == 0) { 6 | number /= i; 7 | i--; 8 | } 9 | } 10 | return number; 11 | } 12 | return -1; 13 | } 14 | 15 | public static void main(String[] args) { 16 | /* 17 | Write a method named getLargestPrime with one parameter of type int named number. 18 | If the number is negative or does not have any prime numbers, the method should return -1 to indicate an invalid value. 19 | The method should calculate the largest prime factor of a given number and return it. 20 | 21 | EXAMPLE INPUT/OUTPUT: 22 | * getLargestPrime (21); should return 7 since 7 is the largest prime (3 * 7 = 21) 23 | * getLargestPrime (217); should return 31 since 31 is the largest prime (7 * 31 = 217) 24 | * getLargestPrime (0); should return -1 since 0 does not have any prime numbers 25 | * getLargestPrime (45); should return 5 since 5 is the largest prime (3 * 3 * 5 = 45) 26 | * getLargestPrime (-1); should return -1 since the parameter is negative 27 | */ 28 | System.out.println(getLargestPrime(21)); 29 | System.out.println(getLargestPrime(217)); 30 | System.out.println(getLargestPrime(0)); 31 | System.out.println(getLargestPrime(45)); 32 | System.out.println(getLargestPrime(-1)); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Section 05/Last Digit Checker/src/LastDigitChecker.java: -------------------------------------------------------------------------------- 1 | public class LastDigitChecker { 2 | public static boolean isValid(int n) { 3 | return n >= 10 && n <= 1000; 4 | } 5 | 6 | public static boolean hasSameLastDigit(int n1, int n2, int n3) { 7 | if (isValid(n1) && isValid(n2) && isValid(n3)) { 8 | return n1 % 10 == n2 % 10 || n3 % 10 == n1 % 10 || n2 % 10 == n3 % 10; 9 | } 10 | return false; 11 | } 12 | 13 | public static void main(String[] args) { 14 | /* 15 | Write a method named hasSameLastDigit with three parameters of type int. 16 | Each number should be within the range of 10 (inclusive) - 1000 (inclusive). 17 | If one of the numbers is not within the range, the method should return false. 18 | The method should return true if at least two of the numbers share the same rightmost digit; 19 | otherwise, it should return false. 20 | 21 | EXAMPLE INPUT/OUTPUT: 22 | * hasSameLastDigit (41, 22, 71); → should return true since 1 is the rightmost digit in numbers 41 and 71 23 | * hasSameLastDigit (23, 32, 42); → should return true since 2 is the rightmost digit in numbers 32 and 42 24 | * hasSameLastDigit (9, 99, 999); → should return false since 9 is not within the range of 10-1000 25 | 26 | Write another method named isValid with one parameter of type int. 27 | The method needs to return true if the number parameter is in range of 10(inclusive) - 1000(inclusive), otherwise return false. 28 | 29 | EXAMPLE INPUT/OUTPUT 30 | * isValid(10); → should return true since 10 is within the range of 10-1000 31 | * isValid(468); → should return true since 10 is within the range of 10-1000 32 | * isValid(1051); → should return false since 10 is not within the range of 10-1000 33 | */ 34 | System.out.println(hasSameLastDigit(41, 22, 71)); 35 | System.out.println(hasSameLastDigit(23, 32, 42)); 36 | System.out.println(hasSameLastDigit(9, 99, 99)); 37 | System.out.println(); 38 | System.out.println(isValid(10)); 39 | System.out.println(isValid(468)); 40 | System.out.println(isValid(1051)); 41 | } 42 | } -------------------------------------------------------------------------------- /Section 05/Number In Word/src/NumberInWord.java: -------------------------------------------------------------------------------- 1 | public class NumberInWord { 2 | public static void printNumberInWord(int number) { 3 | switch (number) { 4 | case 0: 5 | System.out.println("ZERO"); 6 | break; 7 | case 1: 8 | System.out.println("ONE"); 9 | break; 10 | case 2: 11 | System.out.println("TWO"); 12 | break; 13 | case 3: 14 | System.out.println("THREE"); 15 | break; 16 | case 4: 17 | System.out.println("FOUR"); 18 | break; 19 | case 5: 20 | System.out.println("FIVE"); 21 | break; 22 | case 6: 23 | System.out.println("SIX"); 24 | break; 25 | case 7: 26 | System.out.println("SEVEN"); 27 | break; 28 | case 8: 29 | System.out.println("EIGHT"); 30 | break; 31 | case 9: 32 | System.out.println("NINE"); 33 | break; 34 | default: 35 | System.out.println("OTHER"); 36 | } 37 | } 38 | 39 | public static void main(String[] args) { 40 | /* 41 | Write a method called printNumberInWord. The method has one parameter number which is the whole number. 42 | The method needs to print "ZERO", "ONE", "TWO", ... "NINE", "OTHER" if the int parameter number is 43 | 0, 1, 2, .... 9 or other for any other number including negative numbers. 44 | You can use if-else statement or switch statement whatever is easier for you. 45 | */ 46 | printNumberInWord(0); 47 | printNumberInWord(1); 48 | printNumberInWord(2); 49 | printNumberInWord(3); 50 | printNumberInWord(4); 51 | printNumberInWord(5); 52 | printNumberInWord(6); 53 | printNumberInWord(7); 54 | printNumberInWord(8); 55 | printNumberInWord(9); 56 | printNumberInWord(10); 57 | } 58 | } -------------------------------------------------------------------------------- /Section 05/Number Palindrome/src/NumberPalindrome.java: -------------------------------------------------------------------------------- 1 | public class NumberPalindrome { 2 | public static boolean isPalindrome(int number) { 3 | int reverse = 0, lastDigit, original = number; 4 | while (number != 0) { 5 | lastDigit = number % 10; 6 | reverse = reverse * 10 + lastDigit; 7 | number = number / 10; 8 | } 9 | return original == reverse; 10 | } 11 | 12 | public static void main(String[] args) { 13 | /* 14 | Write a method called isPalindrome with one int parameter called number. 15 | The method needs to return a boolean. 16 | It should return true if the number is a palindrome number otherwise it should return false. 17 | 18 | Example input/output: 19 | * isPalindrome(-1221); -> should return true 20 | * isPalindrome(707); -> should return true 21 | * isPalindrome(11212); -> should return false because reverse is 21211 and that is not equal to 11212. 22 | 23 | Find the reverse of the given number. Store in some variable say reverse. 24 | Compare the number with reverse. 25 | If both are the same then the number is a palindrome otherwise it is not. 26 | Declare and initialize another variable to store the reverse of a number, for example reverse = 0. 27 | Store the last digit to some variable say lastDigit = num % 10. 28 | Increase the place value of reverse by one. 29 | To increase place value multiply the reverse variable by 10 e.g. reverse = reverse * 10. 30 | Add lastDigit to reverse. 31 | Since the last digit of the number is processed, remove the last digit of num. 32 | To remove the last digit divide number by 10. 33 | Repeat steps until number is not equal to (or greater than) zero. 34 | A while loop would be a good for this coding exercise. 35 | */ 36 | System.out.println(isPalindrome(-1221)); 37 | System.out.println(isPalindrome(707)); 38 | System.out.println(isPalindrome(11212)); 39 | } 40 | } -------------------------------------------------------------------------------- /Section 05/Perfect Number/src/PerfectNumber.java: -------------------------------------------------------------------------------- 1 | public class PerfectNumber { 2 | public static boolean isPerfectNumber(int number) { 3 | if (number <= 0) { 4 | return false; 5 | } 6 | int sum = 0; 7 | for (int i = 1; i < number; i++) { 8 | if (number % i == 0) { 9 | sum += i; 10 | } 11 | } 12 | return sum == number; 13 | } 14 | 15 | public static void main(String[] args) { 16 | /* 17 | What is the perfect number? 18 | A perfect number is a positive integer which is equal to the sum of its proper positive divisors. 19 | Proper positive divisors are positive integers that fully divide the perfect number 20 | without leaving a remainder and exclude the perfect number itself. 21 | For example, take the number 6: 22 | Its proper divisors are 1, 2, and 3 (since 6 is the value of the perfect number, it is excluded), 23 | and the sum of its proper divisors is 1 + 2 + 3 = 6. 24 | 25 | Therefore, 6 is a perfect number (as well as the first perfect number). 26 | Write a method named isPerfectNumber with one parameter of type int named number. 27 | If number is < 1, the method should return false. 28 | The method must calculate if the number is perfect. If the number is perfect, the method should return true; otherwise, it should return false. 29 | 30 | EXAMPLE INPUT/OUTPUT: 31 | * isPerfectNumber(6); should return true since its proper divisors are 1, 2, 3 and the sum is 1 + 2 + 3 = 6 32 | * isPerfectNumber(28); should return true since its proper divisors are 1, 2, 4, 7, 14 and the sum is 1 + 2 + 4 + 7 + 14 = 28 33 | * isPerfectNumber(5); should return false since its only proper divisor is 1 and the sum is 1 not 5 34 | * isPerfectNumber(-1); should return false since the number is < 1 35 | */ 36 | System.out.println(isPerfectNumber(6)); 37 | System.out.println(isPerfectNumber(28)); 38 | System.out.println(isPerfectNumber(5)); 39 | System.out.println(isPerfectNumber(-1)); 40 | System.out.println(isPerfectNumber(0)); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Section 05/Shared Digit/src/SharedDigit.java: -------------------------------------------------------------------------------- 1 | public class SharedDigit { 2 | public static boolean hasSharedDigit(int x, int y) { 3 | int lx = x / 10, rx = x % 10; 4 | int ly = y / 10, ry = y % 10; 5 | if (x >= 10 && x <= 99 && y >= 10 && y <= 99) { 6 | return lx == ly || lx == ry || rx == ly || rx == ry; 7 | } 8 | return false; 9 | } 10 | 11 | public static void main(String[] args) { 12 | /* 13 | Write a method named hasSharedDigit with two parameters of type int. 14 | Each number should be within the range of 10 (inclusive) - 99 (inclusive). 15 | If one of the numbers is not within the range, the method should return false. 16 | The method should return true if there is a digit that appears in both numbers, 17 | such as 2 in 12 and 23; otherwise, the method should return false. 18 | 19 | Example input/output: 20 | * hasSharedDigit(12, 23); -> should return true since the digit 2 appears in both numbers 21 | * hasSharedDigit(9, 99); -> should return false since 9 is not within the range of 10-99 22 | * hasSharedDigit(9, 99); -> should return true since the digit 5 appears in both numbers 23 | */ 24 | System.out.println(hasSharedDigit(12, 23)); 25 | System.out.println(hasSharedDigit(9, 99)); 26 | System.out.println(hasSharedDigit(15, 55)); 27 | } 28 | } -------------------------------------------------------------------------------- /Section 05/Sum Odd/src/SumOddRange.java: -------------------------------------------------------------------------------- 1 | public class SumOddRange { 2 | public static boolean isOdd(int number) { 3 | if (number < 0) { 4 | return false; 5 | } 6 | return number % 2 != 0; 7 | } 8 | 9 | public static int sumOdd(int start, int end) { 10 | int sum = 0; 11 | if (end >= start && start >= 0) { 12 | for (int i = start; i <= end; i++) { 13 | if (isOdd(i)) { 14 | sum += i; 15 | } 16 | } 17 | return sum; 18 | } 19 | return -1; 20 | } 21 | 22 | public static void main(String[] args) { 23 | /* 24 | Write a method called isOdd with an int parameter and call it number. 25 | The method needs to return a boolean. 26 | Check that number is > 0, if it is not return false. 27 | If number is odd return true, otherwise return false. 28 | 29 | Write a second method called sumOdd that has 2 int parameters start and end, 30 | which represent a range of numbers. 31 | The method should use a for loop to sum all odd numbers in that range including the end and return the sum. 32 | It should call the method isOdd to check if each number is odd. 33 | The parameter end needs to be greater than or equal to start and both start and end parameters have to be greater than 0. 34 | If those conditions are not satisfied return -1 from the method to indicate invalid input. 35 | 36 | Example input/output: 37 | * sumOdd(1, 100); -> should return 2500 38 | * sumOdd(-1, 100); -> should return -1 39 | * sumOdd(100, 100); -> should return 0 40 | * sumOdd(100, -100); -> should return -1 41 | * sumOdd(100, 1000); -> should return 247500 42 | */ 43 | System.out.println(sumOdd(1, 100)); 44 | System.out.println(sumOdd(-1, 100)); 45 | System.out.println(sumOdd(100, 100)); 46 | System.out.println(sumOdd(100, -100)); 47 | System.out.println(sumOdd(100, 1000)); 48 | } 49 | } -------------------------------------------------------------------------------- /Section 06/Carpet Cost Calculator/src/Calculator.java: -------------------------------------------------------------------------------- 1 | public class Calculator { 2 | private Floor floor; 3 | private Carpet carpet; 4 | 5 | public Calculator(Floor floor, Carpet carpet) { 6 | this.floor = floor; 7 | this.carpet = carpet; 8 | } 9 | 10 | public double getTotalCost() { 11 | return floor.getArea() * carpet.getCost(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Section 06/Carpet Cost Calculator/src/Carpet.java: -------------------------------------------------------------------------------- 1 | public class Carpet { 2 | private double cost; 3 | 4 | public Carpet(double cost) { 5 | if (cost < 0) cost = 0; 6 | this.cost = cost; 7 | } 8 | 9 | public double getCost() { 10 | return cost; 11 | } 12 | } -------------------------------------------------------------------------------- /Section 06/Carpet Cost Calculator/src/Floor.java: -------------------------------------------------------------------------------- 1 | public class Floor { 2 | private double width; 3 | private double length; 4 | 5 | public Floor(double width, double length) { 6 | if (width < 0) width = 0; 7 | if (length < 0) length = 0; 8 | this.width = width; 9 | this.length = length; 10 | } 11 | 12 | public double getArea() { 13 | return width * length; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Section 06/Constructor Challenge/src/VipCustomer.java: -------------------------------------------------------------------------------- 1 | public class VipCustomer { 2 | private String name; 3 | private double creditLimit; 4 | private String emailAddress; 5 | 6 | public VipCustomer() { 7 | this("Default name", 1000.0, "default@email.com"); 8 | } 9 | 10 | public VipCustomer(String name, double creditLimit) { 11 | this(name, creditLimit, "email@default.com"); 12 | } 13 | 14 | public VipCustomer(String name, double creditLimit, String emailAddress) { 15 | this.name = name; 16 | this.creditLimit = creditLimit; 17 | this.emailAddress = emailAddress; 18 | } 19 | 20 | public String getName() { 21 | return name; 22 | } 23 | 24 | public double getCreditLimit() { 25 | return creditLimit; 26 | } 27 | 28 | public String getEmailAddress() { 29 | return emailAddress; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Section 06/Cylinder/src/Circle.java: -------------------------------------------------------------------------------- 1 | import static java.lang.Math.PI; 2 | 3 | public class Circle { 4 | private double radius; 5 | 6 | public Circle(double radius) { 7 | if (radius < 0) radius = 0; 8 | this.radius = radius; 9 | } 10 | 11 | public double getRadius() { 12 | return radius; 13 | } 14 | 15 | public double getArea() { 16 | return radius * radius * PI; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Section 06/Cylinder/src/Cylinder.java: -------------------------------------------------------------------------------- 1 | public class Cylinder extends Circle { 2 | private double height; 3 | 4 | public Cylinder(double radius, double height) { 5 | super(radius); 6 | if (height < 0) height = 0; 7 | this.height = height; 8 | } 9 | 10 | public double getHeight() { 11 | return height; 12 | } 13 | 14 | public double getVolume() { 15 | return getArea() * height; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Section 06/Inheritance Challenge/src/Car.java: -------------------------------------------------------------------------------- 1 | public class Car extends Vehicle { 2 | private int wheels; 3 | private int doors; 4 | private int gears; 5 | private boolean isManual; 6 | private int currentGear; 7 | 8 | public Car(String name, String size, int wheels, int doors, int gears, boolean isManual) { 9 | super(name, size); 10 | this.wheels = wheels; 11 | this.doors = doors; 12 | this.gears = gears; 13 | this.isManual = isManual; 14 | this.currentGear = 1; 15 | } 16 | 17 | public void changeGear(int currentGear) { 18 | this.currentGear = currentGear; 19 | System.out.println("Car.setCurrentGear(): Change to " + this.currentGear + " gear."); 20 | } 21 | 22 | public void changeVelocity(int speed, int direction) { 23 | System.out.println("Car.changeVelocity() : Velocity " + speed + " direction " + direction); 24 | move(speed, direction); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Section 06/Inheritance Challenge/src/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | /* 4 | Start with a base class of a Vehicle, then create a Car class that inherits from this base class. 5 | Finally, create another class, a specific type of Car that inherits from the Car class. 6 | You should be able to hand steering, changing gears, and moving (speed in other words). 7 | You will want to decide where to put the appropriate state and behaviours (fields and methods). 8 | As mentioned above, changing gears, increasing/decreasing speed should be included. 9 | For you specific type of vehicle you will want to add something specific for that type of car. 10 | */ 11 | Outlander outlander = new Outlander(36); 12 | outlander.steer(45); 13 | outlander.accelerate(30); 14 | outlander.accelerate(20); 15 | outlander.accelerate(-42); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Section 06/Inheritance Challenge/src/Outlander.java: -------------------------------------------------------------------------------- 1 | public class Outlander extends Car { 2 | private int roadServiceMonths; 3 | 4 | public Outlander(int roadServiceMonths) { 5 | super("Outlander", "4WD", 5, 5, 6, false); 6 | this.roadServiceMonths = roadServiceMonths; 7 | } 8 | 9 | public void accelerate(int rate) { 10 | int newVelocity = getCurrentVelocity() + rate; 11 | if (newVelocity == 0) { 12 | stop(); 13 | changeGear(1); 14 | } else if (newVelocity > 0 && newVelocity <= 10) { 15 | changeGear(1); 16 | } else if (newVelocity > 10 && newVelocity <= 20) { 17 | changeGear(2); 18 | } else if (newVelocity > 20 && newVelocity <= 30) { 19 | changeGear(3); 20 | } else { 21 | changeGear(4); 22 | } 23 | 24 | if (newVelocity > 0) { 25 | changeVelocity(newVelocity, getCurrentDirection()); 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /Section 06/Inheritance Challenge/src/Vehicle.java: -------------------------------------------------------------------------------- 1 | public class Vehicle { 2 | private String name; 3 | private String size; 4 | private int currentVelocity; 5 | private int currentDirection; 6 | 7 | public Vehicle(String name, String size) { 8 | this.name = name; 9 | this.size = size; 10 | this.currentVelocity = 0; 11 | this.currentDirection = 0; 12 | } 13 | 14 | public void steer(int direction) { 15 | this.currentDirection += direction; 16 | System.out.println("Vehicle.steer(): Steering at " + currentDirection + " degrees."); 17 | } 18 | 19 | public void move(int velocity, int direction) { 20 | currentVelocity = velocity; 21 | currentDirection = direction; 22 | System.out.println("Vehicle.move(): Moving at " + currentVelocity + " in direction " + currentDirection); 23 | } 24 | 25 | public String getName() { 26 | return name; 27 | } 28 | 29 | public String getSize() { 30 | return size; 31 | } 32 | 33 | public int getCurrentVelocity() { 34 | return currentVelocity; 35 | } 36 | 37 | public int getCurrentDirection() { 38 | return currentDirection; 39 | } 40 | 41 | public void stop() { 42 | this.currentVelocity = 0; 43 | } 44 | } -------------------------------------------------------------------------------- /Section 06/Pool Area/src/Cuboid.java: -------------------------------------------------------------------------------- 1 | public class Cuboid extends Rectangle { 2 | private double height; 3 | 4 | public Cuboid(double width, double length, double height) { 5 | super(width, length); 6 | if (height < 0) height = 0; 7 | this.height = height; 8 | } 9 | 10 | public double getHeight() { 11 | return height; 12 | } 13 | 14 | public double getVolume() { 15 | return getArea() * height; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Section 06/Pool Area/src/Rectangle.java: -------------------------------------------------------------------------------- 1 | public class Rectangle { 2 | private double width; 3 | private double length; 4 | 5 | public Rectangle(double width, double length) { 6 | if (width < 0) width = 0; 7 | if (length < 0) length = 0; 8 | this.width = width; 9 | this.length = length; 10 | } 11 | 12 | public double getWidth() { 13 | return width; 14 | } 15 | 16 | public double getLength() { 17 | return length; 18 | } 19 | 20 | public double getArea() { 21 | return width * length; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Section 07/Composition Challenge/src/Bed.java: -------------------------------------------------------------------------------- 1 | public class Bed { 2 | private String style; 3 | private int pillows; 4 | private int height; 5 | private int sheets; 6 | private int quilt; 7 | 8 | public Bed(String style, int pillows, int height, int sheets, int quilt) { 9 | this.style = style; 10 | this.pillows = pillows; 11 | this.height = height; 12 | this.sheets = sheets; 13 | this.quilt = quilt; 14 | } 15 | 16 | public void make() { 17 | System.out.println("Bed -> Making"); 18 | } 19 | 20 | public String getStyle() { 21 | return style; 22 | } 23 | 24 | public int getPillows() { 25 | return pillows; 26 | } 27 | 28 | public int getHeight() { 29 | return height; 30 | } 31 | 32 | public int getSheets() { 33 | return sheets; 34 | } 35 | 36 | public int getQuilt() { 37 | return quilt; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Section 07/Composition Challenge/src/Bedroom.java: -------------------------------------------------------------------------------- 1 | public class Bedroom { 2 | private String name; 3 | private Wall wall1; 4 | private Wall wall2; 5 | private Wall wall3; 6 | private Wall wall4; 7 | private Ceiling ceiling; 8 | private Bed bed; 9 | private Lamp lamp; 10 | 11 | public Bedroom(String name, Wall wall1, Wall wall2, Wall wall3, Wall wall4, Ceiling ceiling, Bed bed, Lamp lamp) { 12 | this.name = name; 13 | this.wall1 = wall1; 14 | this.wall2 = wall2; 15 | this.wall3 = wall3; 16 | this.wall4 = wall4; 17 | this.ceiling = ceiling; 18 | this.bed = bed; 19 | this.lamp = lamp; 20 | } 21 | 22 | public Lamp getLamp() { 23 | return this.lamp; 24 | } 25 | 26 | public void makeBed() { 27 | System.out.println("Bedroom -> Making bed"); 28 | bed.make(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Section 07/Composition Challenge/src/Ceiling.java: -------------------------------------------------------------------------------- 1 | public class Ceiling { 2 | private int height; 3 | private int paintedColor; 4 | 5 | public Ceiling(int height, int paintedColor) { 6 | this.height = height; 7 | this.paintedColor = paintedColor; 8 | } 9 | 10 | public int getHeight() { 11 | return height; 12 | } 13 | 14 | public int getPaintedColor() { 15 | return paintedColor; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Section 07/Composition Challenge/src/Lamp.java: -------------------------------------------------------------------------------- 1 | public class Lamp { 2 | private String style; 3 | private boolean battery; 4 | private int globRating; 5 | 6 | public Lamp(String style, boolean battery, int globRating) { 7 | this.style = style; 8 | this.battery = battery; 9 | this.globRating = globRating; 10 | } 11 | 12 | public void turnOn() { 13 | System.out.println("Lamp -> Turning on"); 14 | } 15 | 16 | public String getStyle() { 17 | return style; 18 | } 19 | 20 | public boolean isBattery() { 21 | return battery; 22 | } 23 | 24 | public int getGlobRating() { 25 | return globRating; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Section 07/Composition Challenge/src/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | /* 4 | Create a single room of a house using composition. 5 | Think about the things that should be included in the room. 6 | Maybe physical parts of the house but furniture as well 7 | Add at least one method to access an object via a getter and 8 | then that objects public method as you saw in the previous video 9 | then add at least one method to hide the object e.g. not using a getter 10 | but to access the object used in composition within the main class 11 | like you saw in this video. 12 | */ 13 | Wall wall1 = new Wall("West"); 14 | Wall wall2 = new Wall("East"); 15 | Wall wall3 = new Wall("South"); 16 | Wall wall4 = new Wall("North"); 17 | 18 | Ceiling ceiling = new Ceiling(12, 55); 19 | 20 | Bed bed = new Bed("Modern", 4, 3, 2, 1); 21 | 22 | Lamp lamp = new Lamp("Classic", false, 75); 23 | 24 | Bedroom bedroom = new Bedroom("Elvar's", wall1, wall2, wall3, wall4, ceiling, bed, lamp); 25 | bedroom.makeBed(); 26 | bedroom.getLamp().turnOn(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Section 07/Composition Challenge/src/Wall.java: -------------------------------------------------------------------------------- 1 | public class Wall { 2 | private String direction; 3 | 4 | public Wall(String direction) { 5 | this.direction = direction; 6 | } 7 | 8 | public String getDirection() { 9 | return direction; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Section 07/Encapsulation Challenge/src/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | /* 4 | Create a class and demonstrate proper encapsulation techniques 5 | the class will be called Printer 6 | It will simulate a real Computer Printer 7 | It should have fields for the toner Level, number of pages printed, and 8 | also whether its a duplex printer (capable of printing on both sides of the paper). 9 | Add methods to fill up the toner (up to a maximum of 100%), another method to 10 | simulate printing a page (which should increase the number of pages printed). 11 | Decide on the scope, whether to use constructors, and anything else you think is needed. 12 | */ 13 | Printer printer = new Printer(50, false); 14 | System.out.println("Initial page count = " + printer.getPagesPrinted()); 15 | int pagesPrinted = printer.printPages(4); 16 | System.out.println("Pages printed was " + pagesPrinted + " new total print count for printer = " + printer.getPagesPrinted()); 17 | pagesPrinted = printer.printPages(2); 18 | System.out.println("Pages printed was " + pagesPrinted + " new total print count for printer = " + printer.getPagesPrinted()); 19 | System.out.println("Adding 50% to tonerLevel with a new total of " + printer.addToner(50) + "% tonerLevel"); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Section 07/Encapsulation Challenge/src/Printer.java: -------------------------------------------------------------------------------- 1 | public class Printer { 2 | private int tonerLevel; 3 | private int pagesPrinted; 4 | private boolean duplex; 5 | 6 | public Printer(int tonerLevel, boolean duplex) { 7 | if (tonerLevel > -1 && tonerLevel <= 100) { 8 | this.tonerLevel = tonerLevel; 9 | } else this.tonerLevel = -1; 10 | this.duplex = duplex; 11 | this.pagesPrinted = 0; 12 | } 13 | 14 | public int addToner(int tonerAmount) { 15 | if (tonerAmount > 0 && tonerAmount <= 100) { 16 | if (this.tonerLevel + tonerAmount > 100) { 17 | return -1; 18 | } 19 | this.tonerLevel += tonerAmount; 20 | return this.tonerLevel; 21 | } else return -1; 22 | } 23 | 24 | public int printPages(int pages) { 25 | int pagesToPrint = pages; 26 | if (this.duplex) { 27 | pagesToPrint = (pages / 2) + (pages % 2); 28 | System.out.println("Printing in duplex mode"); 29 | } 30 | this.pagesPrinted += pagesToPrint; 31 | return pagesToPrint; 32 | } 33 | 34 | public int getPagesPrinted() { 35 | return pagesPrinted; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Section 07/OOP Master Challenge/src/DeluxeBurger.java: -------------------------------------------------------------------------------- 1 | public class DeluxeBurger extends Hamburger { 2 | public DeluxeBurger() { 3 | super("Deluxe", "Sausage & Bacon", 14.54, "White"); 4 | super.addHamburgerAddition1("Chips", 2.75); 5 | super.addHamburgerAddition2("Drink", 1.81); 6 | } 7 | 8 | @Override 9 | public void addHamburgerAddition1(String name, double price) { 10 | System.out.println("Cannot not add additional items to a deluxe burger"); 11 | } 12 | 13 | @Override 14 | public void addHamburgerAddition2(String name, double price) { 15 | System.out.println("Cannot not add additional items to a deluxe burger"); 16 | } 17 | 18 | @Override 19 | public void addHamburgerAddition3(String name, double price) { 20 | System.out.println("Cannot not add additional items to a deluxe burger"); 21 | } 22 | 23 | @Override 24 | public void addHamburgerAddition4(String name, double price) { 25 | System.out.println("Cannot not add additional items to a deluxe burger"); 26 | } 27 | } -------------------------------------------------------------------------------- /Section 07/OOP Master Challenge/src/Hamburger.java: -------------------------------------------------------------------------------- 1 | public class Hamburger { 2 | private String name; 3 | private String meat; 4 | private double price; 5 | private String breadRollType; 6 | 7 | private String addition1Name; 8 | private double addition1Price; 9 | 10 | private String addition2Name; 11 | private double addition2Price; 12 | 13 | private String addition3Name; 14 | private double addition3Price; 15 | 16 | private String addition4Name; 17 | private double addition4Price; 18 | 19 | public Hamburger(String name, String meat, double price, String breadRollType) { 20 | this.name = name; 21 | this.meat = meat; 22 | this.price = price; 23 | this.breadRollType = breadRollType; 24 | } 25 | 26 | public void addHamburgerAddition1(String name, double price) { 27 | this.addition1Name = name; 28 | this.addition1Price = price; 29 | } 30 | 31 | public void addHamburgerAddition2(String name, double price) { 32 | this.addition2Name = name; 33 | this.addition2Price = price; 34 | } 35 | 36 | public void addHamburgerAddition3(String name, double price) { 37 | this.addition3Name = name; 38 | this.addition3Price = price; 39 | } 40 | 41 | public void addHamburgerAddition4(String name, double price) { 42 | this.addition4Name = name; 43 | this.addition4Price = price; 44 | } 45 | 46 | public double itemizeHamburger() { 47 | double hamburgerPrice = this.price; 48 | System.out.println(this.name + " hamburger " + " on a " + this.breadRollType + " roll " 49 | + "with " + this.meat + ", price is " + this.price); 50 | if (this.addition1Name != null) { 51 | hamburgerPrice += this.addition1Price; 52 | System.out.println("Added " + this.addition1Name + " for an extra " + this.addition1Price); 53 | } 54 | if (this.addition2Name != null) { 55 | hamburgerPrice += this.addition2Price; 56 | System.out.println("Added " + this.addition2Name + " for an extra " + this.addition2Price); 57 | } 58 | if (this.addition3Name != null) { 59 | hamburgerPrice += this.addition3Price; 60 | System.out.println("Added " + this.addition3Name + " for an extra " + this.addition3Price); 61 | } 62 | if (this.addition4Name != null) { 63 | hamburgerPrice += this.addition4Price; 64 | System.out.println("Added " + this.addition4Name + " for an extra " + this.addition4Price); 65 | } 66 | return hamburgerPrice; 67 | } 68 | } -------------------------------------------------------------------------------- /Section 07/OOP Master Challenge/src/HealthyBurger.java: -------------------------------------------------------------------------------- 1 | public class HealthyBurger extends Hamburger { 2 | 3 | private String healthyExtra1Name; 4 | private double healthyExtra1Price; 5 | 6 | private String healthyExtra2Name; 7 | private double healthyExtra2Price; 8 | 9 | public HealthyBurger(String meat, double price) { 10 | super("Healthy", meat, price, "Brown rye"); 11 | } 12 | 13 | public void addHealthAddition1(String name, double price) { 14 | this.healthyExtra1Name = name; 15 | this.healthyExtra1Price = price; 16 | } 17 | 18 | public void addHealthAddition2(String name, double price) { 19 | this.healthyExtra2Name = name; 20 | this.healthyExtra2Price = price; 21 | } 22 | 23 | @Override 24 | public double itemizeHamburger() { 25 | double hamburgerPrice = super.itemizeHamburger(); 26 | if (this.healthyExtra1Name != null) { 27 | hamburgerPrice += this.healthyExtra1Price; 28 | System.out.println("Added " + this.healthyExtra1Name + " for an extra " + this.healthyExtra1Price); 29 | } 30 | if (this.healthyExtra2Name != null) { 31 | hamburgerPrice += this.healthyExtra2Price; 32 | System.out.println("Added " + this.healthyExtra2Name + " for an extra " + this.healthyExtra2Price); 33 | } 34 | return hamburgerPrice; 35 | } 36 | } -------------------------------------------------------------------------------- /Section 07/Polymorphism Challenge/src/Bugatti.java: -------------------------------------------------------------------------------- 1 | class Bugatti extends Car { 2 | public Bugatti(String name, int cylinders) { 3 | super(name, cylinders); 4 | } 5 | 6 | @Override 7 | public void startEngine() { 8 | System.out.println("Bugatti -> startEngine()"); 9 | } 10 | 11 | @Override 12 | public void accelerate() { 13 | System.out.println("Bugatti -> accelerate()"); 14 | } 15 | 16 | @Override 17 | public void brake() { 18 | System.out.println("Bugatti -> brake()"); 19 | } 20 | } -------------------------------------------------------------------------------- /Section 07/Polymorphism Challenge/src/Car.java: -------------------------------------------------------------------------------- 1 | class Car { 2 | private String name; 3 | private int cylinders; 4 | private boolean engine; 5 | private int wheels; 6 | 7 | public Car(String name, int cylinders) { 8 | this.name = name; 9 | this.cylinders = cylinders; 10 | this.engine = true; 11 | this.wheels = 4; 12 | } 13 | 14 | public String getName() { 15 | return name; 16 | } 17 | 18 | public int getCylinders() { 19 | return cylinders; 20 | } 21 | 22 | public boolean isEngine() { 23 | return engine; 24 | } 25 | 26 | public int getWheels() { 27 | return wheels; 28 | } 29 | 30 | public void startEngine() { 31 | System.out.println("Car -> startEngine()"); 32 | } 33 | 34 | public void accelerate() { 35 | System.out.println("Car -> accelerate()"); 36 | } 37 | 38 | public void brake() { 39 | System.out.println("Car -> brake()"); 40 | } 41 | } -------------------------------------------------------------------------------- /Section 07/Polymorphism Challenge/src/Ferrari.java: -------------------------------------------------------------------------------- 1 | class Ferrari extends Car { 2 | public Ferrari(String name, int cylinders) { 3 | super(name, cylinders); 4 | } 5 | 6 | @Override 7 | public void startEngine() { 8 | System.out.println("Ferrari -> startEngine()"); 9 | } 10 | 11 | @Override 12 | public void accelerate() { 13 | System.out.println("Ferrari -> accelerate()"); 14 | } 15 | 16 | @Override 17 | public void brake() { 18 | System.out.println("Ferrari -> brake()"); 19 | } 20 | } -------------------------------------------------------------------------------- /Section 07/Polymorphism Challenge/src/Lamborghini.java: -------------------------------------------------------------------------------- 1 | class Lamborghini extends Car { 2 | public Lamborghini(String name, int cylinders) { 3 | super(name, cylinders); 4 | } 5 | 6 | @Override 7 | public void startEngine() { 8 | System.out.println("Lamborghini -> startEngine()"); 9 | } 10 | 11 | @Override 12 | public void accelerate() { 13 | System.out.println("Lamborghini -> accelerate()"); 14 | } 15 | 16 | @Override 17 | public void brake() { 18 | System.out.println("Lamborghini -> brake()"); 19 | } 20 | } -------------------------------------------------------------------------------- /Section 07/Polymorphism Challenge/src/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | /* 4 | We are going to go back to the car analogy. 5 | Create a base class called Car 6 | It should have a few fields that would be appropriate for a generice car calss. 7 | engine, cylinders, wheels, etc. 8 | Constructor should initialize cylinders (number of) and name, and set wheels to 4 9 | and engine to true. Cylinders and names would be passed parameters. 10 | Create appropriate getters 11 | Create some methods like startEngine, accelerate, and brake 12 | show a message for each in the base class 13 | Now create 3 sub classes for your favorite vehicles. 14 | Override the appropriate methods to demonstrate polymorphism in use. 15 | put all classes in the one java file (this one). 16 | */ 17 | Bugatti bugatti = new Bugatti("Bugatti Chiron", 16); 18 | Lamborghini lamborghini = new Lamborghini("Lamborghini Aventador", 12); 19 | Ferrari ferrari = new Ferrari("LaFerrari", 12); 20 | 21 | System.out.println(bugatti.getName()); 22 | System.out.println(bugatti.getCylinders()); 23 | bugatti.startEngine(); 24 | bugatti.accelerate(); 25 | bugatti.brake(); 26 | 27 | System.out.println(lamborghini.getName()); 28 | System.out.println(lamborghini.getCylinders()); 29 | lamborghini.startEngine(); 30 | lamborghini.accelerate(); 31 | lamborghini.brake(); 32 | 33 | System.out.println(ferrari.getName()); 34 | System.out.println(ferrari.getCylinders()); 35 | ferrari.startEngine(); 36 | ferrari.accelerate(); 37 | ferrari.brake(); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Section 08/Array Challenge/src/Main.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class Main { 4 | private static Scanner scanner = new Scanner(System.in); 5 | 6 | public static void main(String[] args) { 7 | /* 8 | Create a program using arrays that sorts a list of integers in descending order. 9 | Descending order is highest value to lowest. 10 | In other words if the array had the values in it 106, 26, 81, 5, 15 your program should 11 | ultimately have an array with 106, 81, 26, 15, 5 in it. 12 | Set up the program so that the numbers to sort are read in from the keyboard. 13 | Implement the following methods - getIntegers, printArray, and sortIntegers 14 | getIntegers returns an array of entered integers from keyboard 15 | printArray print out the contents of the array 16 | sortIntegers should sort the array and return a new array containing the sorted numbers 17 | you will have to figure out how to copy the array elements from the passed array into a 18 | new array and sort them and return the new sorted array. 19 | */ 20 | int[] myIntegers = getIntegers(5); 21 | int[] sorted = sortIntegers(myIntegers); 22 | printArray(sorted); 23 | } 24 | 25 | private static int[] getIntegers(int number) { 26 | System.out.println("Enter " + number + " integer values.\r"); 27 | int[] array = new int[number]; 28 | for (int i = 0; i < array.length; i++) { 29 | array[i] = scanner.nextInt(); 30 | } 31 | scanner.close(); 32 | return array; 33 | } 34 | 35 | private static int[] sortIntegers(int[] array) { 36 | int[] sortedArray = new int[array.length]; 37 | for (int i = 0; i < array.length; i++) { 38 | sortedArray[i] = array[i]; 39 | } 40 | boolean flag = true; 41 | int temp; 42 | while (flag) { 43 | flag = false; 44 | for (int i = 0; i < sortedArray.length - 1; i++) { 45 | if (sortedArray[i] < sortedArray[i + 1]) { 46 | temp = sortedArray[i]; 47 | sortedArray[i] = sortedArray[i + 1]; 48 | sortedArray[i + 1] = temp; 49 | flag = true; 50 | } 51 | } 52 | } 53 | return sortedArray; 54 | } 55 | 56 | private static void printArray(int[] array) { 57 | for (int i = 0; i < array.length; i++) { 58 | System.out.println("Element " + i + " contents " + array[i]); 59 | } 60 | } 61 | } -------------------------------------------------------------------------------- /Section 08/ArrayList Challenge/src/Contact.java: -------------------------------------------------------------------------------- 1 | public class Contact { 2 | private String name; 3 | private String phoneNumber; 4 | 5 | public Contact(String name, String phoneNumber) { 6 | this.name = name; 7 | this.phoneNumber = phoneNumber; 8 | } 9 | 10 | public String getName() { 11 | return name; 12 | } 13 | 14 | public String getPhoneNumber() { 15 | return phoneNumber; 16 | } 17 | 18 | public static Contact createContact(String name, String phoneNumber) { 19 | return new Contact(name, phoneNumber); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Section 08/Autoboxing & Unboxing Challenge/src/Bank.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class Bank { 4 | private String name; 5 | private ArrayList branches; 6 | 7 | public Bank(String name) { 8 | this.name = name; 9 | this.branches = new ArrayList<>(); 10 | } 11 | 12 | public boolean addBranch(String branchName) { 13 | if (findBranch(branchName) == null) { 14 | this.branches.add(new Branch(branchName)); 15 | return true; 16 | } 17 | return false; 18 | } 19 | 20 | public boolean addCustomer(String branchName, String customerName, double initialAmount) { 21 | Branch branch = findBranch(branchName); 22 | if (branch != null) { 23 | return branch.newCustomer(customerName, initialAmount); 24 | } 25 | return false; 26 | } 27 | 28 | public boolean addCustomerTransaction(String branchName, String customerName, double amount) { 29 | Branch branch = findBranch(branchName); 30 | if (branch != null) { 31 | return branch.addCustomerTransaction(customerName, amount); 32 | } 33 | return false; 34 | } 35 | 36 | private Branch findBranch(String branchName) { 37 | for (int i = 0; i < this.branches.size(); i++) { 38 | Branch branch = this.branches.get(i); 39 | if (branch.getName().equals(branchName)) { 40 | return branch; 41 | } 42 | } 43 | return null; 44 | } 45 | 46 | public boolean listCustomers(String branchName, boolean showTransactions) { 47 | Branch branch = findBranch(branchName); 48 | if (branch != null) { 49 | System.out.println("Customer details for branch " + branch.getName()); 50 | ArrayList branchCustomers = branch.getCustomers(); 51 | for (int i = 0; i < branchCustomers.size(); i++) { 52 | Customer branchCustomer = branchCustomers.get(i); 53 | System.out.println("Customer: " + branchCustomer.getName() + " [" + (i + 1) + "]"); 54 | if (showTransactions) { 55 | System.out.println("Transactions"); 56 | ArrayList transactions = branchCustomer.getTransactions(); 57 | for (int j = 0; j < transactions.size(); j++) { 58 | System.out.println("[" + (j + 1) + "] Amount " + transactions.get(j)); 59 | } 60 | } 61 | } 62 | return true; 63 | } 64 | return false; 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /Section 08/Autoboxing & Unboxing Challenge/src/Branch.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class Branch { 4 | private String name; 5 | private ArrayList customers; 6 | 7 | public Branch(String name) { 8 | this.name = name; 9 | this.customers = new ArrayList<>(); 10 | } 11 | 12 | public String getName() { 13 | return name; 14 | } 15 | 16 | public ArrayList getCustomers() { 17 | return customers; 18 | } 19 | 20 | public boolean newCustomer(String customerName, double initialAmount) { 21 | if (findCustomer(customerName) == null) { 22 | this.customers.add(new Customer(customerName, initialAmount)); 23 | return true; 24 | } 25 | return false; 26 | } 27 | 28 | public boolean addCustomerTransaction(String customerName, double amount) { 29 | Customer customer = findCustomer(customerName); 30 | if (customer != null) { 31 | customer.addTransaction(amount); 32 | return true; 33 | } 34 | return false; 35 | } 36 | 37 | private Customer findCustomer(String customerName) { 38 | for (int i = 0; i < this.customers.size(); i++) { 39 | Customer customer = this.customers.get(i); 40 | if (customer.getName().equals(customerName)) { 41 | return customer; 42 | } 43 | } 44 | return null; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Section 08/Autoboxing & Unboxing Challenge/src/Customer.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class Customer { 4 | private String name; 5 | private ArrayList transactions; 6 | 7 | public Customer(String name, double initialAmount) { 8 | this.name = name; 9 | this.transactions = new ArrayList<>(); 10 | addTransaction(initialAmount); 11 | } 12 | 13 | public void addTransaction(double amount) { 14 | this.transactions.add(amount); 15 | } 16 | 17 | public String getName() { 18 | return name; 19 | } 20 | 21 | public ArrayList getTransactions() { 22 | return transactions; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Section 08/LinkedList Challenge/src/Album.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.LinkedList; 3 | 4 | public class Album { 5 | private String name; 6 | private String artist; 7 | private ArrayList songs; 8 | 9 | public Album(String name, String artist) { 10 | this.name = name; 11 | this.artist = artist; 12 | this.songs = new ArrayList<>(); 13 | } 14 | 15 | public String getName() { 16 | return name; 17 | } 18 | 19 | public String getArtist() { 20 | return artist; 21 | } 22 | 23 | public boolean addSong(String title, double duration) { 24 | if (findSong(title) == null) { 25 | this.songs.add(new Song(title, duration)); 26 | return true; 27 | } 28 | return false; 29 | } 30 | 31 | private Song findSong(String title) { 32 | for (Song song : this.songs) { 33 | if (song.getTitle().equals(title)) { 34 | return song; 35 | } 36 | } 37 | return null; 38 | } 39 | 40 | public boolean addToPlayList(int trackNumber, LinkedList playlist) { 41 | int index = trackNumber - 1; 42 | if ((index >= 0) && (index < this.songs.size())) { 43 | playlist.add(this.songs.get(index)); 44 | return true; 45 | } 46 | System.out.println("This album does not have a track " + trackNumber); 47 | return false; 48 | } 49 | 50 | public boolean addToPlayList(String title, LinkedList playlist) { 51 | Song song = findSong(title); 52 | if (song != null) { 53 | playlist.add(song); 54 | return true; 55 | } 56 | System.out.println("This song " + title + " is not in this album"); 57 | return false; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /Section 08/LinkedList Challenge/src/Song.java: -------------------------------------------------------------------------------- 1 | public class Song { 2 | private String title; 3 | private double duration; 4 | 5 | public Song(String title, double duration) { 6 | this.title = title; 7 | this.duration = duration; 8 | } 9 | 10 | public String getTitle() { 11 | return title; 12 | } 13 | 14 | @Override 15 | public String toString() { 16 | return this.title + " " + this.duration; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Section 08/Minimum Element Challenge/src/Main.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class Main { 4 | private static Scanner scanner = new Scanner(System.in); 5 | 6 | public static void main(String[] args) { 7 | /* 8 | Write a method called readIntegers() with a parameter called count that represents 9 | how many integers the user need to enter. 10 | 11 | The method need to read from the console until all the numbers are entered, and 12 | then return an array containing the numbers entered. 13 | 14 | Write a method findMin() with the array as a parameter. The method need to return 15 | the minimum value in the array. 16 | 17 | In the main() method read the count from the console and call the method readIntegers() 18 | with the count parameter. 19 | 20 | Then call the findMin() method passing the array returned from the call to the 21 | readIntegers() method. 22 | */ 23 | System.out.println("Enter count:"); 24 | int count = scanner.nextInt(); 25 | int[] returnedArray = readIntegers(count); 26 | int returnedMin = findMin(returnedArray); 27 | System.out.println("min = " + returnedMin); 28 | } 29 | 30 | private static int[] readIntegers(int count) { 31 | int[] array = new int[count]; 32 | for (int i = 0; i < array.length; i++) { 33 | System.out.println("Enter a number:\r"); 34 | array[i] = scanner.nextInt(); 35 | } 36 | return array; 37 | } 38 | 39 | private static int findMin(int[] array) { 40 | int min = Integer.MAX_VALUE; 41 | for (int i = 0; i < array.length; i++) { 42 | if (array[i] < min) { 43 | min = array[i]; 44 | } 45 | } 46 | return min; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Section 08/Reverse Array Challenge/src/Main.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | /* 6 | Write a method called reverse() with an int array as a parameter. 7 | The method should not return any value. In other words, the method 8 | is allowed to modify the array parameter. 9 | 10 | In main() test the reverse() method and print the array both reversed 11 | and non-reversed. 12 | 13 | To reverse the array, you have to swap the elements, so that the first element is 14 | swapped with the last element and son on. 15 | 16 | For example, if the array is {1, 2, 3, 4, 5}, then the reversed array is {5, 4, 3, 2, 1}. 17 | */ 18 | int[] array = {1, 5, 3, 7, 11, 9, 15}; 19 | System.out.println("Array = " + Arrays.toString(array)); 20 | reverse(array); 21 | System.out.println("Reversed array = " + Arrays.toString(array)); 22 | } 23 | 24 | private static void reverse(int[] array) { 25 | int maxIndex = array.length - 1; 26 | int halfLength = array.length / 2; 27 | for (int i = 0; i < halfLength; i++) { 28 | int temp = array[i]; 29 | array[i] = array[maxIndex - i]; 30 | array[maxIndex - i] = temp; 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Section 09/Abstract Class Challenge/src/ListItem.java: -------------------------------------------------------------------------------- 1 | public abstract class ListItem { 2 | 3 | protected ListItem next = null; 4 | protected ListItem previous = null; 5 | 6 | protected Object value; 7 | 8 | public ListItem(Object value) { 9 | this.value = value; 10 | } 11 | 12 | abstract ListItem next(); 13 | 14 | abstract ListItem setNext(ListItem item); 15 | 16 | abstract ListItem previous(); 17 | 18 | abstract ListItem setPrevious(ListItem item); 19 | 20 | abstract int compareTo(ListItem item); 21 | 22 | public Object getValue() { 23 | return value; 24 | } 25 | 26 | public void setValue(Object value) { 27 | this.value = value; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Section 09/Abstract Class Challenge/src/Node.java: -------------------------------------------------------------------------------- 1 | public class Node extends ListItem { 2 | 3 | public Node(Object value) { 4 | super(value); 5 | } 6 | 7 | @Override 8 | ListItem next() { 9 | return this.next; 10 | } 11 | 12 | @Override 13 | ListItem setNext(ListItem item) { 14 | this.next = item; 15 | return this.next; 16 | } 17 | 18 | @Override 19 | ListItem previous() { 20 | return this.previous; 21 | } 22 | 23 | @Override 24 | ListItem setPrevious(ListItem item) { 25 | this.previous = item; 26 | return this.previous; 27 | } 28 | 29 | @Override 30 | int compareTo(ListItem item) { 31 | if (item != null) { 32 | return ((String) super.getValue()).compareTo((String) item.getValue()); 33 | } else { 34 | return -1; 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Section 09/Abstract Class Challenge/src/NodeList.java: -------------------------------------------------------------------------------- 1 | public interface NodeList { 2 | ListItem getRoot(); 3 | 4 | boolean addItem(ListItem item); 5 | 6 | boolean removeItem(ListItem item); 7 | 8 | void traverse(ListItem root); 9 | } 10 | -------------------------------------------------------------------------------- /Section 09/Inner Class Challenge/src/Album.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.LinkedList; 3 | 4 | public class Album { 5 | private String name; 6 | private String artist; 7 | private SongList songs; 8 | 9 | public Album(String name, String artist) { 10 | this.name = name; 11 | this.artist = artist; 12 | this.songs = new SongList(); 13 | } 14 | 15 | public String getName() { 16 | return name; 17 | } 18 | 19 | public String getArtist() { 20 | return artist; 21 | } 22 | 23 | public boolean addSong(String title, double duration) { 24 | return this.songs.add(new Song(title, duration)); 25 | } 26 | 27 | private Song findSong(String title) { 28 | return this.songs.findSong(title); 29 | } 30 | 31 | public boolean addToPlayList(int trackNumber, LinkedList playlist) { 32 | Song checkedSong = this.songs.findSong(trackNumber); 33 | if (checkedSong != null) { 34 | playlist.add(checkedSong); 35 | return true; 36 | } 37 | return false; 38 | } 39 | 40 | public boolean addToPlayList(String title, LinkedList playlist) { 41 | Song checkedSong = this.songs.findSong(title); 42 | if (checkedSong != null) { 43 | playlist.add(checkedSong); 44 | return true; 45 | } 46 | System.out.println("This song " + title + " is not in this album"); 47 | return false; 48 | } 49 | 50 | private class SongList { 51 | private ArrayList songs; 52 | 53 | public SongList() { 54 | this.songs = new ArrayList<>(); 55 | } 56 | 57 | public boolean add(Song song) { 58 | if (!this.songs.contains(song)) { 59 | this.songs.add(song); 60 | return true; 61 | } 62 | return false; 63 | } 64 | 65 | private Song findSong(String title) { 66 | for (Song song : this.songs) { 67 | if (song.getTitle().equals(title)) { 68 | return song; 69 | } 70 | } 71 | return null; 72 | } 73 | 74 | public Song findSong(int trackNumber) { 75 | int index = trackNumber - 1; 76 | if (index >= 0 && index < this.songs.size()) { 77 | return this.songs.get(index); 78 | } 79 | return null; 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /Section 09/Inner Class Challenge/src/Song.java: -------------------------------------------------------------------------------- 1 | public class Song { 2 | private String title; 3 | private double duration; 4 | 5 | public Song(String title, double duration) { 6 | this.title = title; 7 | this.duration = duration; 8 | } 9 | 10 | public String getTitle() { 11 | return title; 12 | } 13 | 14 | @Override 15 | public String toString() { 16 | return this.title + " " + this.duration; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Section 09/Interfaces Challenge/src/ISaveable.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public interface ISaveable { 4 | ArrayList write(); 5 | 6 | void read(ArrayList values); 7 | } 8 | -------------------------------------------------------------------------------- /Section 09/Interfaces Challenge/src/Monster.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class Monster implements ISaveable { 4 | private String name; 5 | private int stamina; 6 | private int strength; 7 | 8 | public Monster(String name, int stamina, int strength) { 9 | this.name = name; 10 | this.stamina = stamina; 11 | this.strength = strength; 12 | } 13 | 14 | public String getName() { 15 | return name; 16 | } 17 | 18 | public int getStamina() { 19 | return stamina; 20 | } 21 | 22 | public int getStrength() { 23 | return strength; 24 | } 25 | 26 | @Override 27 | public String toString() { 28 | return "Monster{" + 29 | "name='" + name + '\'' + 30 | ", stamina=" + stamina + 31 | ", strength=" + strength + 32 | '}'; 33 | } 34 | 35 | @Override 36 | public ArrayList write() { 37 | ArrayList values = new ArrayList<>(); 38 | values.add(0, this.name); 39 | values.add(1, "" + this.stamina); 40 | values.add(2, "" + this.strength); 41 | return values; 42 | } 43 | 44 | @Override 45 | public void read(ArrayList savedValues) { 46 | if (savedValues != null && savedValues.size() > 0) { 47 | this.name = savedValues.get(0); 48 | this.stamina = Integer.parseInt(savedValues.get(1)); 49 | this.strength = Integer.parseInt(savedValues.get(2)); 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /Section 10/Generics Challenge/src/BaseballTeam.java: -------------------------------------------------------------------------------- 1 | public class BaseballTeam extends Team { 2 | public BaseballTeam(String name) { 3 | super(name); 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /Section 10/Generics Challenge/src/FootballTeam.java: -------------------------------------------------------------------------------- 1 | public class FootballTeam extends Team { 2 | public FootballTeam(String name) { 3 | super(name); 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /Section 10/Generics Challenge/src/League.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Collections; 3 | 4 | public class League { 5 | private String name; 6 | private ArrayList league = new ArrayList<>(); 7 | 8 | public League(String name) { 9 | this.name = name; 10 | } 11 | 12 | public String getName() { 13 | return name; 14 | } 15 | 16 | public boolean addTeam(T team) { 17 | if (league.contains(team)) { 18 | return false; 19 | } else { 20 | league.add(team); 21 | return true; 22 | } 23 | } 24 | 25 | public void showLeagueTable() { 26 | Collections.sort(league); 27 | for (T team : league) { 28 | System.out.println(team.getName() + ": " + team.ranking()); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Section 10/Generics Challenge/src/SoccerTeam.java: -------------------------------------------------------------------------------- 1 | public class SoccerTeam extends Team { 2 | public SoccerTeam(String name) { 3 | super(name); 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /Section 10/Generics Challenge/src/Team.java: -------------------------------------------------------------------------------- 1 | public class Team implements Comparable> { 2 | private String name; 3 | private int played = 0; 4 | private int won = 0; 5 | private int lost = 0; 6 | private int tied = 0; 7 | 8 | public Team(String name) { 9 | this.name = name; 10 | } 11 | 12 | public String getName() { 13 | return name; 14 | } 15 | 16 | public void matchResult(Team opponent, int ourScore, int theirScore) { 17 | String message; 18 | if (ourScore > theirScore) { 19 | won++; 20 | message = " beat "; 21 | } else if (ourScore == theirScore) { 22 | tied++; 23 | message = " drew with "; 24 | } else { 25 | lost++; 26 | message = " lost to "; 27 | } 28 | played++; 29 | if (opponent != null) { 30 | System.out.println(this.getName() + message + opponent.getName()); 31 | } 32 | } 33 | 34 | public int ranking() { 35 | return (won * 2) + tied; 36 | } 37 | 38 | public int compareTo(Team team) { 39 | if (this.ranking() > team.ranking()) { 40 | return -1; 41 | } else if (this.ranking() < team.ranking()) { 42 | return 1; 43 | } else { 44 | return 0; 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Section 11/Package Challenge/Package Challenge/src/com/example/Series.java: -------------------------------------------------------------------------------- 1 | package com.example; 2 | 3 | /* 4 | Create a suitably named package containing a class called Series 5 | with the following static methods: 6 | nSum(int n) returns the sum of all numbers from 0 to n. The first 10 numbers are: 7 | 0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55. 8 | 9 | factorial(int n) returns the product of all numbers from 1 to n 10 | i.e. 1 * 2 * 3 * 4 ... * (n - 1) * n. 11 | The first 10 factorials are: 12 | 0, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800. 13 | 14 | fibonacci(n) returns the nth Fibonacci number. These are defined as: 15 | f(0) = 0 16 | f(1) = 1 17 | f(n) = f(n-1) + f(n-2) 18 | (so f(2) is also 1. The first 10 fibonacci numbers are: 19 | 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55. 20 | 21 | When you have tested your functions, delete the Main class and 22 | produce a jar file. 23 | 24 | Create a new project and add your Series library, then test the 25 | three methods in the main() method of your new project. 26 | */ 27 | 28 | public class Series { 29 | public static long nSum(int n) { 30 | int sum = 0; 31 | for (int i = 0; i <= n; i++) { 32 | sum += i; 33 | } 34 | return sum; 35 | } 36 | 37 | public static long factorial(int n) { 38 | if (n == 0) return 0; 39 | int fact = 1; 40 | for (int i = 1; i <= n; i++) { 41 | fact *= i; 42 | } 43 | return fact; 44 | } 45 | 46 | public static long fibonacci(int n) { 47 | if (n == 0) return 0; 48 | if (n == 1) return 1; 49 | return fibonacci(n - 1) + fibonacci(n - 2); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /Section 11/Package Challenge/SeriesTest/src/com/example/test/Main.java: -------------------------------------------------------------------------------- 1 | package com.example.test; 2 | 3 | import com.example.Series; 4 | 5 | public class Main { 6 | public static void main(String[] args) { 7 | for (int i = 0; i <= 10; i++) { 8 | System.out.println(Series.nSum(i)); 9 | } 10 | System.out.println("***********************"); 11 | for (int i = 0; i <= 10; i++) { 12 | System.out.println(Series.factorial(i)); 13 | } 14 | System.out.println("***********************"); 15 | for (int i = 0; i <= 10; i++) { 16 | System.out.println(Series.fibonacci(i)); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Section 11/Scope Challenge/src/Main.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | /* 6 | Write a small program to read an integer from the keyboard. 7 | (using Scanner) and print out the times table for that number. 8 | The table should run from 1 to 12. 9 | 10 | You are allowed to use one variable called scanner for your Scanner instance. 11 | You can use as many other variables as you need, but they must all be called x. 12 | That includes any class instances and loop variables that you may decide to use. 13 | 14 | If you use a class, the class can be called X (capital), 15 | but any instances of it must be called x (lower case). 16 | 17 | Any methods you create must also be called x. 18 | 19 | Optional Extra: 20 | Change your program so that ALL variables (including the scanner instance) are called x. 21 | */ 22 | X x = new X(new Scanner(System.in)); 23 | x.x(); 24 | } 25 | } -------------------------------------------------------------------------------- /Section 11/Scope Challenge/src/X.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class X { 4 | private int x; 5 | 6 | public X(Scanner x) { 7 | System.out.println("Please enter a number: "); 8 | this.x = x.nextInt(); 9 | } 10 | 11 | public void x() { 12 | for (int x = 1; x <= 12; x++) { 13 | System.out.println(x + " times " + this.x + " equals " + x * this.x); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Section 12/Adventure Game Challenge/src/Location.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | 4 | public class Location { 5 | private final int locationID; 6 | private final String description; 7 | private final Map exits; 8 | 9 | public Location(int locationID, String description) { 10 | this.locationID = locationID; 11 | this.description = description; 12 | this.exits = new HashMap<>(); 13 | this.exits.put("Q", 0); 14 | } 15 | 16 | public void addExit(String direction, int location) { 17 | exits.put(direction, location); 18 | } 19 | 20 | public int getLocationID() { 21 | return locationID; 22 | } 23 | 24 | public String getDescription() { 25 | return description; 26 | } 27 | 28 | public Map getExits() { 29 | return new HashMap<>(exits); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Section 12/Collections Challenge/src/Basket.java: -------------------------------------------------------------------------------- 1 | import java.util.Collections; 2 | import java.util.Map; 3 | import java.util.TreeMap; 4 | 5 | public class Basket { 6 | private final String name; 7 | private final Map basket; 8 | 9 | public Basket(String name) { 10 | this.name = name; 11 | this.basket = new TreeMap<>(); 12 | } 13 | 14 | public int addToBasket(StockItem item, int quantity) { 15 | if (item != null && quantity > 0) { 16 | int inBasket = basket.getOrDefault(item, 0); 17 | basket.put(item, inBasket + quantity); 18 | return inBasket; 19 | } 20 | return 0; 21 | } 22 | 23 | public int removeFromBasket(StockItem item, int quantity) { 24 | if (item != null && quantity > 0) { 25 | int inBasket = basket.getOrDefault(item, 0); 26 | int newQuantity = inBasket - quantity; 27 | if (newQuantity > 0) { 28 | basket.put(item, newQuantity); 29 | return quantity; 30 | } else if (newQuantity == 0) { 31 | basket.remove(item); 32 | return quantity; 33 | } 34 | } 35 | return 0; 36 | } 37 | 38 | public void clearBasket() { 39 | this.basket.clear(); 40 | } 41 | 42 | public Map Items() { 43 | return Collections.unmodifiableMap(basket); 44 | } 45 | 46 | @Override 47 | public String toString() { 48 | String s = "\nShopping basket " + name + " contains " + basket.size() + ((basket.size() == 1) ? " item" : " items") + "\n"; 49 | double totalCost = 0.0; 50 | for (Map.Entry item : basket.entrySet()) { 51 | s = s + item.getKey() + ". " + item.getValue() + " purchased\n"; 52 | totalCost += item.getKey().getPrice() * item.getValue(); 53 | } 54 | return s + "Total cost " + totalCost; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /Section 12/Immutable Class Challenge/src/Location.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | 4 | public class Location { 5 | private final int locationID; 6 | private final String description; 7 | private final Map exits; 8 | 9 | /* 10 | The challenge is to work out what is wrong with the location constructor 11 | that would allow the program to compile and crash at runtime so when you identify the problem modify 12 | the code to fix it so I just i’ll just say that again your challenge here is to work out what is wrong 13 | with the location constructor that you can see on screen line 20 that will allow the program to compile 14 | but crash on run time when you identify the problem modify the code to fix it. 15 | */ 16 | 17 | public Location(int locationID, String description, Map exits) { 18 | this.locationID = locationID; 19 | this.description = description; 20 | if (exits != null) this.exits = new HashMap<>(exits); 21 | else this.exits = new HashMap<>(); 22 | this.exits.put("Q", 0); 23 | } 24 | 25 | public void addExit(String direction, int location) { 26 | exits.put(direction, location); 27 | } 28 | 29 | public int getLocationID() { 30 | return locationID; 31 | } 32 | 33 | public String getDescription() { 34 | return description; 35 | } 36 | 37 | public Map getExits() { 38 | return new HashMap<>(exits); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Section 12/Set Challenge/src/DwarfPlanet.java: -------------------------------------------------------------------------------- 1 | public class DwarfPlanet extends HeavenlyBody { 2 | public DwarfPlanet(String name, double orbitalPeriod) { 3 | super(name, orbitalPeriod, BodyTypes.DWARF_PLANET); 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /Section 12/Set Challenge/src/Moon.java: -------------------------------------------------------------------------------- 1 | public class Moon extends HeavenlyBody { 2 | public Moon(String name, double orbitalPeriod) { 3 | super(name, orbitalPeriod, BodyTypes.MOON); 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /Section 12/Set Challenge/src/Planet.java: -------------------------------------------------------------------------------- 1 | public class Planet extends HeavenlyBody { 2 | public Planet(String name, double orbitalPeriod) { 3 | super(name, orbitalPeriod, BodyTypes.PLANET); 4 | } 5 | 6 | @Override 7 | public boolean addSatellite(HeavenlyBody moon) { 8 | if (moon.getKey().getBodyTypes() == BodyTypes.MOON) { 9 | return super.addSatellite(moon); 10 | } else { 11 | return false; 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Section 12/Set Challenge/src/Star.java: -------------------------------------------------------------------------------- 1 | public class Star extends HeavenlyBody { 2 | public Star(String name, double orbitalPeriod) { 3 | super(name, orbitalPeriod, BodyTypes.STAR); 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /Section 13/JavaFX Challenge/src/module-info.java: -------------------------------------------------------------------------------- 1 | module JavaFX.Challenge { 2 | requires javafx.fxml; 3 | requires javafx.controls; 4 | requires java.xml; 5 | 6 | opens sample.datamodel to javafx.base; 7 | opens sample to javafx.fxml; 8 | 9 | exports sample to javafx.graphics; 10 | } -------------------------------------------------------------------------------- /Section 13/JavaFX Challenge/src/sample/ContactController.java: -------------------------------------------------------------------------------- 1 | package sample; 2 | 3 | import javafx.fxml.FXML; 4 | import javafx.scene.control.TextField; 5 | import sample.datamodel.Contact; 6 | 7 | public class ContactController { 8 | 9 | @FXML 10 | private TextField firstNameField; 11 | 12 | @FXML 13 | private TextField lastNameField; 14 | 15 | @FXML 16 | private TextField phoneNumberField; 17 | 18 | @FXML 19 | private TextField notesField; 20 | 21 | public Contact getNewContact() { 22 | String firstName = firstNameField.getText(); 23 | String lastName = lastNameField.getText(); 24 | String phoneNumber = phoneNumberField.getText(); 25 | String notes = notesField.getText(); 26 | return new Contact(firstName, lastName, phoneNumber, notes); 27 | } 28 | 29 | public void editContact(Contact contact) { 30 | firstNameField.setText(contact.getFirstName()); 31 | lastNameField.setText(contact.getLastName()); 32 | phoneNumberField.setText(contact.getPhoneNumber()); 33 | notesField.setText(contact.getNotes()); 34 | } 35 | 36 | public void updateContact(Contact contact) { 37 | contact.setFirstName(firstNameField.getText()); 38 | contact.setLastName(lastNameField.getText()); 39 | contact.setPhoneNumber(phoneNumberField.getText()); 40 | contact.setNotes(notesField.getText()); 41 | } 42 | } -------------------------------------------------------------------------------- /Section 13/JavaFX Challenge/src/sample/Main.java: -------------------------------------------------------------------------------- 1 | package sample; 2 | 3 | import javafx.application.Application; 4 | import javafx.fxml.FXMLLoader; 5 | import javafx.scene.Parent; 6 | import javafx.scene.Scene; 7 | import javafx.stage.Stage; 8 | 9 | public class Main extends Application { 10 | /* 11 | For this challenge, you'll create a simple contacts application that has a single main window. 12 | The application will allow the user to add a contact, edit a contact, and delete a contact. 13 | You'll display the contacts using the TableView control. 14 | 15 | There will be a single Contacts menu that contains Add, Edit, and Delete items. 16 | You will want to be able to load and store the contacts, which isn't a JavaFX topic. 17 | I've provided a ContactData class that contains a quick and dirty way to load and store contacts using XML. 18 | You'll have to add code to the ContactData class to complete the challenge. 19 | There are comments that indicate where your code should go. 20 | 21 | Hints: 22 | 1. In addition to the ContactData class, you'll need a Contact class to store individual contacts. 23 | For each contact, you'll store the first name, last name, phone number, and notes. 24 | 2. To get data binding to work with the TableView, you'll want to store the contact information as SimpleStringProperty fields. 25 | 3. The TodoList application we worked on in an earlier lecture covers 90% of what you'll need to complete this challenge. 26 | */ 27 | @Override 28 | public void start(Stage primaryStage) throws Exception { 29 | Parent root = FXMLLoader.load(getClass().getResource("main.fxml")); 30 | primaryStage.setTitle("My Contacts"); 31 | primaryStage.setScene(new Scene(root, 600, 400)); 32 | primaryStage.show(); 33 | } 34 | 35 | 36 | public static void main(String[] args) { 37 | launch(args); 38 | } 39 | } -------------------------------------------------------------------------------- /Section 13/JavaFX Challenge/src/sample/contactdialog.fxml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Fill in the information for the new Contact 6 | 7 | 8 | 9 | 21 | 22 | -------------------------------------------------------------------------------- /Section 13/JavaFX Challenge/src/sample/datamodel/Contact.java: -------------------------------------------------------------------------------- 1 | package sample.datamodel; 2 | 3 | import javafx.beans.property.SimpleStringProperty; 4 | 5 | public class Contact { 6 | 7 | private SimpleStringProperty firstName = new SimpleStringProperty(""); 8 | private SimpleStringProperty lastName = new SimpleStringProperty(""); 9 | private SimpleStringProperty phoneNumber = new SimpleStringProperty(""); 10 | private SimpleStringProperty notes = new SimpleStringProperty(""); 11 | 12 | public Contact() { 13 | } 14 | 15 | public Contact(String firstName, String lastName, String phoneNumber, String notes) { 16 | this.firstName.set(firstName); 17 | this.lastName.set(lastName); 18 | this.phoneNumber.set(phoneNumber); 19 | this.notes.set(notes); 20 | } 21 | 22 | public String getFirstName() { 23 | return firstName.get(); 24 | } 25 | 26 | public SimpleStringProperty firstNameProperty() { 27 | return firstName; 28 | } 29 | 30 | public void setFirstName(String firstName) { 31 | this.firstName.set(firstName); 32 | } 33 | 34 | public String getLastName() { 35 | return lastName.get(); 36 | } 37 | 38 | public SimpleStringProperty lastNameProperty() { 39 | return lastName; 40 | } 41 | 42 | public void setLastName(String lastName) { 43 | this.lastName.set(lastName); 44 | } 45 | 46 | public String getPhoneNumber() { 47 | return phoneNumber.get(); 48 | } 49 | 50 | public SimpleStringProperty phoneNumberProperty() { 51 | return phoneNumber; 52 | } 53 | 54 | public void setPhoneNumber(String phoneNumber) { 55 | this.phoneNumber.set(phoneNumber); 56 | } 57 | 58 | public String getNotes() { 59 | return notes.get(); 60 | } 61 | 62 | public SimpleStringProperty notesProperty() { 63 | return notes; 64 | } 65 | 66 | public void setNotes(String notes) { 67 | this.notes.set(notes); 68 | } 69 | 70 | @Override 71 | public String toString() { 72 | return "Contact{" + 73 | "firstName=" + firstName + 74 | ", lastName=" + lastName + 75 | ", phoneNumber=" + phoneNumber + 76 | ", notes=" + notes + 77 | '}'; 78 | } 79 | } -------------------------------------------------------------------------------- /Section 13/JavaFX Challenge/src/sample/main.fxml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 |
52 |
-------------------------------------------------------------------------------- /Section 14/Input and Output Challenge 1/directions.txt: -------------------------------------------------------------------------------- 1 | 0,Q,0 2 | 1,Q,0 3 | 1,S,4 4 | 1,E,3 5 | 1,N,5 6 | 1,W,2 7 | 2,Q,0 8 | 2,N,5 9 | 3,Q,0 10 | 3,W,1 11 | 4,Q,0 12 | 4,N,1 13 | 4,W,2 14 | 5,Q,0 15 | 5,S,1 16 | 5,W,2 17 | -------------------------------------------------------------------------------- /Section 14/Input and Output Challenge 1/locations.txt: -------------------------------------------------------------------------------- 1 | 0,You are sitting in front of a computer learning Java 2 | 1,You are standing at the end of a road before a small brick building 3 | 2,You are at the top of a hill 4 | 3,You are inside a building, a well house for a small spring 5 | 4,You are in a valley beside a stream 6 | 5,You are in the forest 7 | -------------------------------------------------------------------------------- /Section 14/Input and Output Challenge 1/src/Location.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | 4 | public class Location { 5 | private final int locationID; 6 | private final String description; 7 | private final Map exits; 8 | 9 | public Location(int locationID, String description, Map exits) { 10 | this.locationID = locationID; 11 | this.description = description; 12 | if (exits != null) { 13 | this.exits = new HashMap<>(exits); 14 | } else { 15 | this.exits = new HashMap<>(); 16 | } 17 | this.exits.put("Q", 0); 18 | } 19 | 20 | public int getLocationID() { 21 | return locationID; 22 | } 23 | 24 | public String getDescription() { 25 | return description; 26 | } 27 | 28 | public Map getExits() { 29 | return new HashMap<>(exits); 30 | } 31 | 32 | protected void addExit(String direction, int location) { 33 | exits.put(direction, location); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Section 14/Input and Output Challenge 1/src/Main.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | import java.util.Scanner; 4 | 5 | public class Main { 6 | private static Locations locations = new Locations(); 7 | 8 | public static void main(String[] args) { 9 | // Change the program to allow players to type full words, or phrases, then move to the 10 | // correct location based upon their input. 11 | // The player should be able to type commands such as "Go West", "run South", or just "East" 12 | // and the program will move to the appropriate location if there is one. As at present, an 13 | // attempt to move in an invalid direction should print a message and remain in the same place. 14 | // 15 | // Single letter commands (N, W, S, E, Q) should still be available. 16 | 17 | Scanner scanner = new Scanner(System.in); 18 | 19 | Map vocabulary = new HashMap<>(); 20 | vocabulary.put("QUIT", "Q"); 21 | vocabulary.put("NORTH", "N"); 22 | vocabulary.put("SOUTH", "S"); 23 | vocabulary.put("WEST", "W"); 24 | vocabulary.put("EAST", "E"); 25 | 26 | 27 | int loc = 64; 28 | // int loc = 1; 29 | while (true) { 30 | System.out.println(locations.get(loc).getDescription()); 31 | 32 | if (loc == 0) { 33 | break; 34 | } 35 | 36 | Map exits = locations.get(loc).getExits(); 37 | System.out.print("Available exits are "); 38 | for (String exit : exits.keySet()) { 39 | System.out.print(exit + ", "); 40 | } 41 | System.out.println(); 42 | 43 | String direction = scanner.nextLine().toUpperCase(); 44 | if (direction.length() > 1) { 45 | String[] words = direction.split(" "); 46 | for (String word : words) { 47 | if (vocabulary.containsKey(word)) { 48 | direction = vocabulary.get(word); 49 | break; 50 | } 51 | } 52 | } 53 | 54 | if (exits.containsKey(direction)) { 55 | loc = exits.get(direction); 56 | 57 | } else { 58 | System.out.println("You cannot go in that direction"); 59 | } 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /Section 14/Input and Output Challenge 2/src/Location.java: -------------------------------------------------------------------------------- 1 | import java.util.LinkedHashMap; 2 | import java.util.Map; 3 | 4 | public class Location { 5 | private final int locationID; 6 | private final String description; 7 | private final Map exits; 8 | 9 | public Location(int locationID, String description, Map exits) { 10 | this.locationID = locationID; 11 | this.description = description; 12 | if (exits != null) { 13 | this.exits = new LinkedHashMap<>(exits); 14 | } else { 15 | this.exits = new LinkedHashMap<>(); 16 | } 17 | this.exits.put("Q", 0); 18 | } 19 | 20 | public int getLocationID() { 21 | return locationID; 22 | } 23 | 24 | public String getDescription() { 25 | return description; 26 | } 27 | 28 | public Map getExits() { 29 | return new LinkedHashMap<>(exits); 30 | } 31 | 32 | protected void addExit(String direction, int location) { 33 | exits.put(direction, location); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Section 15/Concurrency Challenge 1/src/BankAccount.java: -------------------------------------------------------------------------------- 1 | class BankAccount { 2 | 3 | private double balance; 4 | private String accountNumber; 5 | 6 | public BankAccount(String accountNumber, double initialBalance) { 7 | this.accountNumber = accountNumber; 8 | this.balance = initialBalance; 9 | } 10 | 11 | public void deposit(double amount) { 12 | balance += amount; 13 | } 14 | 15 | public void withdraw(double amount) { 16 | balance -= amount; 17 | } 18 | } -------------------------------------------------------------------------------- /Section 15/Concurrency Challenge 1/src/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | /* 4 | Create and start threads. 5 | 6 | We could have two people using a joint bank account at the same time. 7 | Create and start two threads that use the same BankAccount instance and an initial balance of $1000.00. 8 | One will deposit $300.00 into the bank account, and then withdraw $50.00. 9 | The other will deposit $203.75 and then withdraw $100.00 10 | */ 11 | final BankAccount account = new BankAccount("12345-678", 1000.00); 12 | 13 | Thread t1 = new Thread() { 14 | public void run() { 15 | account.deposit(300.00); 16 | account.withdraw(50.00); 17 | } 18 | }; 19 | 20 | Thread t2 = new Thread() { 21 | public void run() { 22 | account.deposit(203.75); 23 | account.withdraw(100.00); 24 | } 25 | }; 26 | 27 | t1.start(); 28 | t2.start(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Section 15/Concurrency Challenge 2/src/BankAccount.java: -------------------------------------------------------------------------------- 1 | public class BankAccount { 2 | private double balance; 3 | private String accountNumber; 4 | 5 | public BankAccount(String accountNumber, double initialBalance) { 6 | this.accountNumber = accountNumber; 7 | this.balance = initialBalance; 8 | } 9 | 10 | public synchronized void deposit(double amount) { 11 | balance += amount; 12 | } 13 | 14 | public synchronized void withdraw(double amount) { 15 | balance -= amount; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Section 15/Concurrency Challenge 2/src/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | /* 4 | Make the BankAccount class Threadsafe using the synchronize keyword. 5 | 6 | I hope you can see that there's going to be thread interference when two 7 | threads are accessing the same BankAccount instance at the same time. 8 | We have to make the BankAccount class threadsafe, and that's our next challenge. 9 | Use the synchronized keyword to make the BankAccount class threadsafe. 10 | */ 11 | final BankAccount account = new BankAccount("12345-678", 1000.00); 12 | 13 | Thread t1 = new Thread() { 14 | public void run() { 15 | account.deposit(300.00); 16 | account.withdraw(50.00); 17 | } 18 | }; 19 | 20 | Thread t2 = new Thread() { 21 | public void run() { 22 | account.deposit(203.75); 23 | account.withdraw(100.00); 24 | } 25 | }; 26 | 27 | t1.start(); 28 | t2.start(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Section 15/Concurrency Challenge 3/src/BankAccount.java: -------------------------------------------------------------------------------- 1 | public class BankAccount { 2 | 3 | private double balance; 4 | private String accountNumber; 5 | 6 | public BankAccount(String accountNumber, double initialBalance) { 7 | this.accountNumber = accountNumber; 8 | this.balance = initialBalance; 9 | } 10 | 11 | public synchronized void deposit(double amount) { 12 | balance += amount; 13 | } 14 | 15 | public synchronized void withdraw(double amount) { 16 | balance -= amount; 17 | } 18 | 19 | public String getAccountNumber() { 20 | return accountNumber; 21 | } 22 | 23 | public void printAccountNumber() { 24 | System.out.println("Account number = " + accountNumber); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Section 15/Concurrency Challenge 3/src/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | /* 5 | Make the BankAccount class threadsafe again using the synchronized keyword. 6 | 7 | We've added two new methods. Update the code so that the BankAccount class 8 | is threadsafe. Use the synchronized keyword wherever necessary. 9 | */ 10 | final BankAccount account = new BankAccount("12345-678", 1000.00); 11 | 12 | // Answer: Both threads are using the same account number so it is unnecessary to use the synchronized keyword. 13 | // However, this question was a trick question. 14 | 15 | Thread t1 = new Thread() { 16 | public void run() { 17 | account.deposit(300.00); 18 | account.withdraw(50.00); 19 | } 20 | }; 21 | 22 | Thread t2 = new Thread() { 23 | public void run() { 24 | account.deposit(203.75); 25 | account.withdraw(100.00); 26 | } 27 | }; 28 | 29 | t1.start(); 30 | t2.start(); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Section 15/Concurrency Challenge 4/src/BankAccount.java: -------------------------------------------------------------------------------- 1 | import java.util.concurrent.locks.Lock; 2 | import java.util.concurrent.locks.ReentrantLock; 3 | 4 | public class BankAccount { 5 | 6 | private double balance; 7 | private String accountNumber; 8 | 9 | private Lock lock; 10 | 11 | public BankAccount(String accountNumber, double initialBalance) { 12 | this.accountNumber = accountNumber; 13 | this.balance = initialBalance; 14 | this.lock = new ReentrantLock(); 15 | } 16 | 17 | public void deposit(double amount) { 18 | lock.lock(); 19 | try { 20 | balance += amount; 21 | } finally { 22 | lock.unlock(); 23 | } 24 | } 25 | 26 | public void withdraw(double amount) { 27 | lock.lock(); 28 | try { 29 | balance -= amount; 30 | } finally { 31 | lock.unlock(); 32 | } 33 | } 34 | 35 | public String getAccountNumber() { 36 | return accountNumber; 37 | } 38 | 39 | public void printAccountNumber() { 40 | System.out.println("Account number = " + accountNumber); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Section 15/Concurrency Challenge 4/src/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | /* 5 | Use ReentrantLock. 6 | 7 | Instead of using the synchronized keyword, make the BankAccount class 8 | threadsafe using the ReentrantLock class. 9 | */ 10 | final BankAccount account = new BankAccount("12345-678", 1000.00); 11 | 12 | // Answer: Both threads are using the same account number so it is unnecessary to use the synchronized keyword. 13 | // However, this question was a trick question. 14 | 15 | Thread t1 = new Thread() { 16 | public void run() { 17 | account.deposit(300.00); 18 | account.withdraw(50.00); 19 | } 20 | }; 21 | 22 | Thread t2 = new Thread() { 23 | public void run() { 24 | account.deposit(203.75); 25 | account.withdraw(100.00); 26 | } 27 | }; 28 | 29 | t1.start(); 30 | t2.start(); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Section 15/Concurrency Challenge 5/src/BankAccount.java: -------------------------------------------------------------------------------- 1 | import java.util.concurrent.TimeUnit; 2 | import java.util.concurrent.locks.Lock; 3 | import java.util.concurrent.locks.ReentrantLock; 4 | 5 | public class BankAccount { 6 | 7 | private double balance; 8 | private String accountNumber; 9 | 10 | private Lock lock; 11 | 12 | public BankAccount(String accountNumber, double initialBalance) { 13 | this.accountNumber = accountNumber; 14 | this.balance = initialBalance; 15 | this.lock = new ReentrantLock(); 16 | } 17 | 18 | public void deposit(double amount) { 19 | try { 20 | if (lock.tryLock(1000, TimeUnit.MILLISECONDS)) { 21 | try { 22 | balance += amount; 23 | } finally { 24 | lock.unlock(); 25 | } 26 | } else { 27 | System.out.println("Could not get the lock"); 28 | } 29 | } catch (InterruptedException e) { 30 | e.printStackTrace(); 31 | } 32 | } 33 | 34 | public void withdraw(double amount) { 35 | try { 36 | if (lock.tryLock(1000, TimeUnit.MILLISECONDS)) { 37 | try { 38 | balance -= amount; 39 | } finally { 40 | lock.unlock(); 41 | } 42 | } else { 43 | System.out.println("Could not get the lock"); 44 | } 45 | } catch (InterruptedException e) { 46 | e.printStackTrace(); 47 | } 48 | } 49 | 50 | public String getAccountNumber() { 51 | return accountNumber; 52 | } 53 | 54 | public void printAccountNumber() { 55 | System.out.println("Account number = " + accountNumber); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /Section 15/Concurrency Challenge 5/src/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | /* 5 | Use tryLock with a timeout value. 6 | 7 | Instead of using lock(), use tryLock() with a timeout value of 1 second. 8 | If the waiting period times out, print the message, "Could not get the lock" to the console. 9 | 10 | Hint: Use the form of the tryLock() method that accepts two parameters - the first parameter 11 | is the timeout value, and the second parameter is the time unit of the first parameter. 12 | Use TimeUnite.MILLISECONDS for the second parameter. 13 | */ 14 | final BankAccount account = new BankAccount("12345-678", 1000.00); 15 | 16 | Thread t1 = new Thread() { 17 | public void run() { 18 | account.deposit(300.00); 19 | account.withdraw(50.00); 20 | } 21 | }; 22 | 23 | Thread t2 = new Thread() { 24 | public void run() { 25 | account.deposit(203.75); 26 | account.withdraw(100.00); 27 | } 28 | }; 29 | 30 | t1.start(); 31 | t2.start(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Section 15/Concurrency Challenge 6/src/BankAccount.java: -------------------------------------------------------------------------------- 1 | import java.util.concurrent.TimeUnit; 2 | import java.util.concurrent.locks.Lock; 3 | import java.util.concurrent.locks.ReentrantLock; 4 | 5 | public class BankAccount { 6 | 7 | private double balance; 8 | private String accountNumber; 9 | 10 | private Lock lock; 11 | 12 | public BankAccount(String accountNumber, double initialBalance) { 13 | this.accountNumber = accountNumber; 14 | this.balance = initialBalance; 15 | this.lock = new ReentrantLock(); 16 | } 17 | 18 | public void deposit(double amount) { 19 | boolean status = false; 20 | try { 21 | if (lock.tryLock(1000, TimeUnit.MILLISECONDS)) { 22 | try { 23 | balance += amount; 24 | status = true; 25 | } finally { 26 | lock.unlock(); 27 | } 28 | } else { 29 | System.out.println("Could not get the lock"); 30 | } 31 | } catch (InterruptedException e) { 32 | e.printStackTrace(); 33 | } 34 | System.out.println("Transaction status = " + status); 35 | } 36 | 37 | public void withdraw(double amount) { 38 | boolean status = false; 39 | try { 40 | if (lock.tryLock(1000, TimeUnit.MILLISECONDS)) { 41 | try { 42 | balance -= amount; 43 | status = true; 44 | } finally { 45 | lock.unlock(); 46 | } 47 | } else { 48 | System.out.println("Could not get the lock"); 49 | } 50 | } catch (InterruptedException e) { 51 | e.printStackTrace(); 52 | } 53 | System.out.println("Transaction status = " + status); 54 | } 55 | 56 | public String getAccountNumber() { 57 | return accountNumber; 58 | } 59 | 60 | public void printAccountNumber() { 61 | System.out.println("Account number = " + accountNumber); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /Section 15/Concurrency Challenge 6/src/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | /* 5 | Update the code so that the status variable is thread safe. 6 | 7 | Use whatever method you like: the synchronized keyword or the lock object. 8 | */ 9 | final BankAccount account = new BankAccount("12345-678", 1000.00); 10 | 11 | // The status variable is already thread safe because local variables are stored on the thread stack 12 | // so that they have their own copy of the status variable. 13 | 14 | Thread t1 = new Thread() { 15 | public void run() { 16 | account.deposit(300.00); 17 | account.withdraw(50.00); 18 | } 19 | }; 20 | 21 | Thread t2 = new Thread() { 22 | public void run() { 23 | account.deposit(203.75); 24 | account.withdraw(100.00); 25 | } 26 | }; 27 | 28 | t1.start(); 29 | t2.start(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Section 15/Concurrency Challenge 7/src/BankAccount.java: -------------------------------------------------------------------------------- 1 | import java.util.concurrent.locks.Lock; 2 | import java.util.concurrent.locks.ReentrantLock; 3 | 4 | class BankAccount { 5 | 6 | private double balance; 7 | private String accountNumber; 8 | private Lock lock = new ReentrantLock(); 9 | 10 | BankAccount(String accountNumber, double balance) { 11 | this.accountNumber = accountNumber; 12 | this.balance = balance; 13 | } 14 | 15 | public boolean withdraw(double amount) { 16 | if (lock.tryLock()) { 17 | try { 18 | try { 19 | // Simulate database access 20 | Thread.sleep(100); 21 | } catch (InterruptedException e) { 22 | e.printStackTrace(); 23 | } 24 | balance -= amount; 25 | System.out.printf("%s: Withdrew %f\n", Thread.currentThread().getName(), amount); 26 | return true; 27 | } finally { 28 | lock.unlock(); 29 | } 30 | } 31 | return false; 32 | } 33 | 34 | public boolean deposit(double amount) { 35 | if (lock.tryLock()) { 36 | try { 37 | try { 38 | // Simulate database access 39 | Thread.sleep(100); 40 | } catch (InterruptedException e) { 41 | e.printStackTrace(); 42 | } 43 | balance += amount; 44 | System.out.printf("%s: Deposited %f\n", Thread.currentThread().getName(), amount); 45 | return true; 46 | } finally { 47 | lock.unlock(); 48 | } 49 | } 50 | return false; 51 | } 52 | 53 | public boolean transfer(BankAccount destinationAccount, double amount) { 54 | if (withdraw(amount)) { 55 | if (destinationAccount.deposit(amount)) { 56 | return true; 57 | } else { 58 | // The deposit failed. Refund the money back into the account. 59 | System.out.printf("%s: Destination account busy. Refunding money\n", Thread.currentThread().getName()); 60 | deposit(amount); 61 | } 62 | } 63 | return false; 64 | } 65 | } -------------------------------------------------------------------------------- /Section 15/Concurrency Challenge 7/src/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | /* 4 | Spot and fix the problem. 5 | 6 | Let's take a look at a similar application which also deals with Bank Accounts, 7 | but in this case, performs transfers from one bank account to another. 8 | 9 | This version of the BankAccount class has three methods: deposit(), withdraw(), 10 | and transfer(). The deposit() and withdraw() methods are similar to what we had before. 11 | The transfer() method first tries to withdraw the money from the source account. 12 | If it's successful, it deposits the money into the destination account and returns true. 13 | If it's not successful, it refunds the source account and returns false. 14 | 15 | In the main() method, we create two bank accounts and start two threads. 16 | Each thread will perform a transfer using an instance of the Transfer class. 17 | The Transfer class's run() method loops until a transfer is successful. 18 | 19 | The challenge is to spot what's wrong with this code and to fix it. 20 | 21 | What do we call this particular situation (deadlock, livelock, etc.)? 22 | This is a livelock. 23 | 24 | Why is it happening? 25 | Thread1 is trying to transfer money to Thread2, however Thread2 is busy so it refunds 26 | the money back and the loop continues endlessly. 27 | 28 | How would we fix it? 29 | The code did never release the lock, so I unlocked the lock after it withdraws and deposits. 30 | */ 31 | BankAccount account1 = new BankAccount("12345-678", 500.00); 32 | BankAccount account2 = new BankAccount("98765-432", 1000.00); 33 | 34 | new Thread(new Transfer(account1, account2, 10.00), "Transfer1").start(); 35 | new Thread(new Transfer(account2, account1, 55.88), "Transfer2").start(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Section 15/Concurrency Challenge 7/src/Transfer.java: -------------------------------------------------------------------------------- 1 | class Transfer implements Runnable { 2 | 3 | private BankAccount sourceAccount, destinationAccount; 4 | private double amount; 5 | 6 | Transfer(BankAccount sourceAccount, BankAccount destinationAccount, double amount) { 7 | this.sourceAccount = sourceAccount; 8 | this.destinationAccount = destinationAccount; 9 | this.amount = amount; 10 | } 11 | 12 | public void run() { 13 | while (!sourceAccount.transfer(destinationAccount, amount)) 14 | continue; 15 | System.out.printf("%s completed\n", Thread.currentThread().getName()); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Section 15/Concurrency Challenge 8/src/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | /* 5 | What is wrong with this code? 6 | The code has a deadlock. 7 | The threads are trying to get the same locks in different order 8 | so that is why it results in a deadlock. 9 | 10 | Example: 11 | Tutor gets the tutor lock and then tries to get the student lock. 12 | Student gets the student lock and then tries to get the tutor lock. 13 | Deadlock. 14 | 15 | Solution: 16 | 1. Is a set of locks being obtained in a different order by multiple threads (that's the case here). 17 | If so, can we force all threads to obtain the locks in the same order? 18 | 2. Are we over-synchronizing the code? 19 | 3. Can we rewrite the code to break any circular call patterns? 20 | 4. Would using ReentrantLocks objects help? 21 | */ 22 | Tutor tutor = new Tutor(); 23 | Student student = new Student(tutor); 24 | tutor.setStudent(student); 25 | 26 | Thread tutorThread = new Thread(new Runnable() { 27 | @Override 28 | public void run() { 29 | tutor.studyTime(); 30 | } 31 | }); 32 | 33 | Thread studentThread = new Thread(new Runnable() { 34 | @Override 35 | public void run() { 36 | student.handInAssignment(); 37 | } 38 | }); 39 | 40 | tutorThread.start(); 41 | studentThread.start(); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Section 15/Concurrency Challenge 8/src/Student.java: -------------------------------------------------------------------------------- 1 | class Student { 2 | 3 | private Tutor tutor; 4 | 5 | Student(Tutor tutor) { 6 | this.tutor = tutor; 7 | } 8 | 9 | public synchronized void startStudy() { 10 | // study 11 | System.out.println("Student is studying"); 12 | } 13 | 14 | public synchronized void handInAssignment() { 15 | tutor.getProgressReport(); 16 | System.out.println("Student handed in assignment"); 17 | } 18 | } -------------------------------------------------------------------------------- /Section 15/Concurrency Challenge 8/src/Tutor.java: -------------------------------------------------------------------------------- 1 | public class Tutor { 2 | 3 | private Student student; 4 | 5 | public synchronized void setStudent(Student student) { 6 | this.student = student; 7 | } 8 | 9 | public synchronized void studyTime() { 10 | System.out.println("Tutor has arrived"); 11 | try { 12 | // wait for student to arrive and hand in assignment 13 | Thread.sleep(300); 14 | } catch (InterruptedException e) { 15 | e.printStackTrace(); 16 | } 17 | student.startStudy(); 18 | System.out.println("Tutor is studying with student"); 19 | } 20 | 21 | public synchronized void getProgressReport() { 22 | // get progress report 23 | System.out.println("Tutor gave progress report"); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Section 15/Concurrency Challenge 9/src/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | /* 5 | What is wrong with this code? 6 | It's a deadlock. 7 | 8 | Example: 9 | Tutor calls tutor.studyTime() and gets the tutor lock and then the student lock. 10 | Tutor then waits for the student and releases the tutor lock. 11 | Student calls the handInAssignment() and gets the tutor lock and calls getProgressReport(). 12 | Student tries to get the student lock but the Tutor is still holding the lock. 13 | Deadlock. 14 | 15 | Solution: 16 | Check in the code where it calls wait() and see if it causes a deadlock. 17 | wait() method releases a lock before exiting the synchronized block, 18 | so releasing can lead to problems. 19 | */ 20 | final NewTutor tutor = new NewTutor(); 21 | final NewStudent student = new NewStudent(tutor); 22 | tutor.setStudent(student); 23 | 24 | Thread tutorThread = new Thread(new Runnable() { 25 | @Override 26 | public void run() { 27 | tutor.studyTime(); 28 | } 29 | }); 30 | 31 | Thread studentThread = new Thread(new Runnable() { 32 | @Override 33 | public void run() { 34 | student.handInAssignment(); 35 | } 36 | }); 37 | 38 | tutorThread.start(); 39 | studentThread.start(); 40 | } 41 | } -------------------------------------------------------------------------------- /Section 15/Concurrency Challenge 9/src/NewStudent.java: -------------------------------------------------------------------------------- 1 | class NewStudent { 2 | 3 | private NewTutor tutor; 4 | 5 | NewStudent(NewTutor tutor) { 6 | this.tutor = tutor; 7 | } 8 | 9 | public void startStudy() { 10 | // study 11 | System.out.println("Student is studying"); 12 | } 13 | 14 | public void handInAssignment() { 15 | synchronized (tutor) { 16 | tutor.getProgressReport(); 17 | synchronized (this) { 18 | System.out.println("Student handed in assignment"); 19 | tutor.notifyAll(); 20 | } 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /Section 15/Concurrency Challenge 9/src/NewTutor.java: -------------------------------------------------------------------------------- 1 | class NewTutor { 2 | 3 | private NewStudent student; 4 | 5 | public void setStudent(NewStudent student) { 6 | this.student = student; 7 | } 8 | 9 | public void studyTime() { 10 | synchronized (this) { 11 | System.out.println("Tutor has arrived"); 12 | synchronized (student) { 13 | try { 14 | // wait for student to arrive 15 | this.wait(); 16 | } catch (InterruptedException e) { 17 | e.printStackTrace(); 18 | } 19 | student.startStudy(); 20 | System.out.println("Tutor is studying with student"); 21 | } 22 | } 23 | } 24 | 25 | public void getProgressReport() { 26 | // get progress report 27 | System.out.println("Tutor gave progress report"); 28 | } 29 | } -------------------------------------------------------------------------------- /Section 16/Lambda Challenge 1/src/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | /* 5 | Write the following anonymous class as a lambda expression: 6 | Runnable anonymous = new Runnable() { 7 | @Override 8 | public void run() { 9 | String myString = "Let's split this up into an array"; 10 | String[] parts = myString.split(" "); 11 | for (String part: parts) { 12 | System.out.println(part); 13 | } 14 | } 15 | }; 16 | */ 17 | Runnable lambda = () -> { 18 | String myString = "Let's split this up into an array"; 19 | String[] parts = myString.split(" "); 20 | for (String part : parts) { 21 | System.out.println(part); 22 | } 23 | }; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Section 16/Lambda Challenge 10/src/Main.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.List; 3 | 4 | public class Main { 5 | 6 | public static void main(String[] args) { 7 | /* 8 | Now do the same thing (uppercase first letter, then sort and print the list) 9 | using a stream and a chain of stream operations. 10 | */ 11 | List topNames2015 = Arrays.asList( 12 | "Amelia", 13 | "Olivia", 14 | "emily", 15 | "Isla", 16 | "Ava", 17 | "oliver", 18 | "Jack", 19 | "Charlie", 20 | "harry", 21 | "Jacob" 22 | ); 23 | 24 | topNames2015 25 | .stream() 26 | .map(s -> s.substring(0, 1).toUpperCase() + s.substring(1)) 27 | .sorted() 28 | .forEach(System.out::println); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Section 16/Lambda Challenge 11/src/Main.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.List; 3 | 4 | public class Main { 5 | 6 | public static void main(String[] args) { 7 | /* 8 | Instead of printing out the sorted names, 9 | print out how many names being with the letter 'A' instead. 10 | 11 | Two hints: 12 | 1. You'll have to modify the stream chain 13 | 2. You'll have to add another statement to print the number of items 14 | */ 15 | List topNames2015 = Arrays.asList( 16 | "Amelia", 17 | "Olivia", 18 | "emily", 19 | "Isla", 20 | "Ava", 21 | "oliver", 22 | "Jack", 23 | "Charlie", 24 | "harry", 25 | "Jacob" 26 | ); 27 | 28 | long namesBeginWithA = topNames2015 29 | .stream() 30 | .map(s -> s.substring(0, 1).toUpperCase() + s.substring(1)) 31 | .filter(s -> s.startsWith("A")) 32 | .count(); 33 | 34 | System.out.println("Number of names beginning with A is: " + namesBeginWithA); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Section 16/Lambda Challenge 12/src/Main.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.List; 3 | 4 | public class Main { 5 | 6 | public static void main(String[] args) { 7 | /* 8 | Let's go back to the previous version of the code, 9 | when we were printing out the sorted names. 10 | Let's suppose we want to debug what's going on when the chain is executed. 11 | 12 | Instead of printing out the names at the end of the chain, maybe we're not sure 13 | the code that uppercases the first letter is working correctly. 14 | 15 | Let's use peek() to print out the names after the map() method has executed. 16 | What will the following code print to the console? 17 | */ 18 | List topNames2015 = Arrays.asList( 19 | "Amelia", 20 | "Olivia", 21 | "emily", 22 | "Isla", 23 | "Ava", 24 | "oliver", 25 | "Jack", 26 | "Charlie", 27 | "harry", 28 | "Jacob" 29 | ); 30 | 31 | topNames2015 32 | .stream() 33 | .map(name -> name.substring(0, 1).toUpperCase() + name.substring(1)) 34 | .peek(System.out::println) 35 | .sorted(String::compareTo); 36 | 37 | // Nothing will be printed out. 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Section 16/Lambda Challenge 13/src/Main.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.List; 3 | import java.util.stream.Collectors; 4 | 5 | public class Main { 6 | 7 | public static void main(String[] args) { 8 | /* 9 | Add a terminal operation to this chain so that the peek call will execute. 10 | 11 | If you need to, check the Stream documentation at 12 | https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html 13 | 14 | Since the peek() call is printing every item, try to do something else with 15 | the terminal operation. Don't print out the items again. 16 | */ 17 | List topNames2015 = Arrays.asList( 18 | "Amelia", 19 | "Olivia", 20 | "emily", 21 | "Isla", 22 | "Ava", 23 | "oliver", 24 | "Jack", 25 | "Charlie", 26 | "harry", 27 | "Jacob" 28 | ); 29 | 30 | topNames2015 31 | .stream() 32 | .map(name -> name.substring(0, 1).toUpperCase() + name.substring(1)) 33 | .peek(System.out::println) 34 | .sorted(String::compareTo) 35 | .collect(Collectors.toList()); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Section 16/Lambda Challenge 2/src/Main.java: -------------------------------------------------------------------------------- 1 | import java.util.function.Function; 2 | 3 | public class Main { 4 | 5 | public static void main(String[] args) { 6 | /* 7 | Write the following method as a lambda expression: 8 | public static String everySecondChar(String source) { 9 | StringBuilder returnVal = new StringBuilder(); 10 | for (int i = 0; i < source.length(); i++) { 11 | if (i % 2 == 1) { 12 | returnVal.append(source.charAt(i)); 13 | } 14 | } 15 | return returnVal.toString(); 16 | } 17 | */ 18 | Function lambda = source -> { 19 | StringBuilder returnVal = new StringBuilder(); 20 | for (int i = 0; i < source.length(); i++) { 21 | if (i % 2 == 1) { 22 | returnVal.append(source.charAt(i)); 23 | } 24 | } 25 | return returnVal.toString(); 26 | }; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Section 16/Lambda Challenge 3/src/Main.java: -------------------------------------------------------------------------------- 1 | import java.util.function.Function; 2 | 3 | public class Main { 4 | 5 | public static void main(String[] args) { 6 | /* 7 | Right now, the function doesn't do anything. 8 | Write the code that will execute the function with an argument of "1234567890" 9 | */ 10 | Function lambdaFunction = s -> { 11 | StringBuilder returnVal = new StringBuilder(); 12 | for (int i = 0; i < s.length(); i++) { 13 | if (i % 2 == 1) { 14 | returnVal.append(s.charAt(i)); 15 | } 16 | } 17 | return returnVal.toString(); 18 | }; 19 | 20 | System.out.println(lambdaFunction.apply("1234567890")); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Section 16/Lambda Challenge 4/src/Main.java: -------------------------------------------------------------------------------- 1 | import java.util.function.Function; 2 | 3 | public class Main { 4 | 5 | public static void main(String[] args) { 6 | /* 7 | Instead of executing this function directly, suppose we want to pass it to a method. 8 | Write a method called everySecondCharacter that accepts the function as a parameter 9 | and executes it with the argument "1234567890". 10 | 11 | It should return the result of the function. 12 | For bonus points, don't hard-code the argument string within the method. 13 | */ 14 | Function lambdaFunction = s -> { 15 | StringBuilder returnVal = new StringBuilder(); 16 | for (int i = 0; i < s.length(); i++) { 17 | if (i % 2 == 1) { 18 | returnVal.append(s.charAt(i)); 19 | } 20 | } 21 | return returnVal.toString(); 22 | }; 23 | 24 | everySecondCharacter(lambdaFunction, "1234567890"); 25 | } 26 | 27 | public static String everySecondCharacter(Function function, String source) { 28 | return function.apply(source); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Section 16/Lambda Challenge 5/src/Main.java: -------------------------------------------------------------------------------- 1 | import java.util.function.Function; 2 | 3 | public class Main { 4 | 5 | public static void main(String[] args) { 6 | /* 7 | Using the bonus version, call the method with the lambdaFunction we created 8 | earlier and the string "1234567890". Print the result returned from the method. 9 | */ 10 | Function lambdaFunction = s -> { 11 | StringBuilder returnVal = new StringBuilder(); 12 | for (int i = 0; i < s.length(); i++) { 13 | if (i % 2 == 1) { 14 | returnVal.append(s.charAt(i)); 15 | } 16 | } 17 | return returnVal.toString(); 18 | }; 19 | 20 | System.out.println(everySecondCharacter(lambdaFunction, "1234567890")); 21 | } 22 | 23 | public static String everySecondCharacter(Function function, String source) { 24 | return function.apply(source); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Section 16/Lambda Challenge 6/src/Main.java: -------------------------------------------------------------------------------- 1 | import java.util.function.Supplier; 2 | 3 | public class Main { 4 | 5 | public static void main(String[] args) { 6 | /* 7 | Now write a lambda expression that maps to the java.util.Supplier interface. 8 | This lambda should return the string "I love Java!" Assign it to a variable called iLoveJava. 9 | */ 10 | Supplier iLoveJava = () -> "I love Java!"; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Section 16/Lambda Challenge 7/src/Main.java: -------------------------------------------------------------------------------- 1 | import java.util.function.Supplier; 2 | 3 | public class Main { 4 | 5 | public static void main(String[] args) { 6 | /* 7 | As with Function, the Supplier won't do anything until we use it. 8 | Use this supplier to assign the string "I love Java!" to a variable called supplierResult. 9 | Then print the variable to the console. 10 | */ 11 | Supplier iLoveJava = () -> "I love Java!"; 12 | String supplierResult = iLoveJava.get(); 13 | System.out.println(supplierResult); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Section 16/Lambda Challenge 8/src/Main.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Arrays; 3 | import java.util.List; 4 | 5 | public class Main { 6 | 7 | public static void main(String[] args) { 8 | /* 9 | Write code to print the items in the list in sorted order, 10 | and with the first letter in each name upper-cased. 11 | The name "harry" should be printed as "Harry" and should be printed 12 | after "Emily" and before "Isla". Use lambda expressions wherever possible. 13 | */ 14 | List topNames2015 = Arrays.asList( 15 | "Amelia", 16 | "Olivia", 17 | "emily", 18 | "Isla", 19 | "Ava", 20 | "oliver", 21 | "Jack", 22 | "Charlie", 23 | "harry", 24 | "Jacob" 25 | ); 26 | 27 | List firstNameUpperCase = new ArrayList<>(); 28 | topNames2015.forEach(s -> firstNameUpperCase.add(s.substring(0, 1).toUpperCase() + s.substring(1))); 29 | firstNameUpperCase.sort((x, y) -> x.compareTo(y)); 30 | firstNameUpperCase.forEach(s -> System.out.println(s)); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Section 16/Lambda Challenge 9/src/Main.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Arrays; 3 | import java.util.List; 4 | 5 | public class Main { 6 | 7 | public static void main(String[] args) { 8 | /* 9 | Change the code so that is uses method references. 10 | Remember that a method reference looks like Class::MethodName 11 | */ 12 | List topNames2015 = Arrays.asList( 13 | "Amelia", 14 | "Olivia", 15 | "emily", 16 | "Isla", 17 | "Ava", 18 | "oliver", 19 | "Jack", 20 | "Charlie", 21 | "harry", 22 | "Jacob" 23 | ); 24 | 25 | List firstNameUpperCase = new ArrayList<>(); 26 | topNames2015.forEach(s -> firstNameUpperCase.add(s.substring(0, 1).toUpperCase() + s.substring(1))); 27 | firstNameUpperCase.sort(String::compareTo); 28 | firstNameUpperCase.forEach(System.out::println); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Section 17/Regular Expressions Challenge 1/src/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | /* 5 | Write the string literal regular expression that will match the following String. 6 | Use the String.matches() method to verify your answer. 7 | */ 8 | String challenge1 = "I want a bike."; 9 | System.out.println(challenge1.matches("I want a bike.")); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Section 17/Regular Expressions Challenge 10/src/Main.java: -------------------------------------------------------------------------------- 1 | import java.util.regex.Matcher; 2 | import java.util.regex.Pattern; 3 | 4 | public class Main { 5 | 6 | public static void main(String[] args) { 7 | /* 8 | Instead of printing out the numbers themselves, print out their start and end indices. 9 | Use the same string we used for challenge 9. 10 | Make those indices inclusive. For example, the start index printed for 135 should be 5, 11 | and the end index should be 7. Hint: You will need to look at the documentation for the 12 | Matcher.start() and Matcher.end() methods. There's more than one version of these methods. 13 | The documentation is here: https://docs.oracle.com/javase/8/docs/api/java/util/regex/Matcher.html 14 | */ 15 | String challenge10 = "abcd.135\tuvqz.7\ttzik.999\n"; 16 | Pattern pattern = Pattern.compile("\\w+\\.(\\d+)\\s"); 17 | Matcher matcher = pattern.matcher(challenge10); 18 | 19 | while (matcher.find()) { 20 | System.out.println("Occurrence: start = " + matcher.start(1) + " end = " + (matcher.end(1) - 1)); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Section 17/Regular Expressions Challenge 11/src/Main.java: -------------------------------------------------------------------------------- 1 | import java.util.regex.Matcher; 2 | import java.util.regex.Pattern; 3 | 4 | public class Main { 5 | 6 | public static void main(String[] args) { 7 | /* 8 | Suppose we have the following string containing points on a graph within curly braces. 9 | Extract what's in the curly braces. 10 | */ 11 | String challenge11 = "{0, 2}, {0, 5}, {1, 3}, {2, 4}"; 12 | Pattern pattern = Pattern.compile("\\{(\\d, \\d)\\}"); 13 | Matcher matcher = pattern.matcher(challenge11); 14 | 15 | while (matcher.find()) { 16 | System.out.println("Occurrence: " + matcher.group(1)); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Section 17/Regular Expressions Challenge 12/src/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | /* 5 | Write a regular expression that will match a 5-digit US zip code. 6 | Use "11111" as your test string. 7 | */ 8 | String challenge12 = "11111"; 9 | System.out.println(challenge12.matches("^\\d{5}$")); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Section 17/Regular Expressions Challenge 13/src/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | /* 5 | US zip codes can be followed by a dash and another four numbers. 6 | Write a regular expression that will match those zip codes. 7 | Use "11111-1111" as your test string. 8 | */ 9 | String challenge13 = "11111-1111"; 10 | System.out.println(challenge13.matches("^\\d{5}-\\d{4}$")); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Section 17/Regular Expressions Challenge 14/src/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | /* 5 | Write a regular expression that will match 5-digit US zip codes, 6 | and zip codes that contain the optional 4 digits preceded by a dash. 7 | */ 8 | String challenge14_1 = "11111"; 9 | String challenge14_2 = "11111-1111"; 10 | String zipRegExp = "^\\d{5}|\\d{5}-\\d{4}$"; 11 | System.out.println(challenge14_1.matches(zipRegExp)); 12 | System.out.println(challenge14_2.matches(zipRegExp)); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Section 17/Regular Expressions Challenge 2/src/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | /* 5 | Now write a regular expression that will match "I want a bike." and "I want a ball." 6 | Verify your answer using the matches() method. 7 | */ 8 | String challenge1 = "I want a bike."; 9 | String challenge2 = "I want a ball."; 10 | String regExp = "I want a (bike|ball)."; 11 | System.out.println(challenge1.matches(regExp)); 12 | System.out.println(challenge2.matches(regExp)); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Section 17/Regular Expressions Challenge 3/src/Main.java: -------------------------------------------------------------------------------- 1 | import java.util.regex.Matcher; 2 | import java.util.regex.Pattern; 3 | 4 | public class Main { 5 | 6 | public static void main(String[] args) { 7 | /* 8 | In the last challenge, we used the same regular expression twice. 9 | Use the Matcher.matches() method to check for matches, 10 | instead of String.matches(), for the regular expression that uses \w+. 11 | Hint: You'll have to compile a pattern. 12 | */ 13 | String challenge1 = "I want a bike."; 14 | String challenge2 = "I want a ball."; 15 | Pattern pattern = Pattern.compile("I want a (bike|ball)."); 16 | Matcher matcher = pattern.matcher(challenge1); 17 | System.out.println(matcher.matches()); 18 | matcher = pattern.matcher(challenge2); 19 | System.out.println(matcher.matches()); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Section 17/Regular Expressions Challenge 4/src/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | /* 5 | Replace all occurrences of blank with an underscore for the following string. 6 | Print out the resulting string. 7 | */ 8 | String challenge4 = "Replace all blanks with underscores."; 9 | System.out.println(challenge4.replaceAll(" ", "_")); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Section 17/Regular Expressions Challenge 5/src/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | /* 5 | Write a regular expression that will match the following string in its entirety. 6 | Use the String.matches() method to verify your answer. 7 | */ 8 | String challenge5 = "aaabccccccccdddefffg"; 9 | System.out.println(challenge5.matches("[a-g]+")); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Section 17/Regular Expressions Challenge 6/src/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | /* 5 | Write a regular expression that will only match the challenge 5 string in its entirety. 6 | */ 7 | String challenge6 = "aaabccccccccdddefffg"; 8 | System.out.println(challenge6.matches("^a{3}bc{8}d{3}ef{3}g$")); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Section 17/Regular Expressions Challenge 7/src/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | /* 5 | Write a regular expression that will match a string that starts with a series of letters. 6 | The letters must be followed by a period. 7 | After the period, there must be a series of digits. 8 | The string "kjisl.22" would match. 9 | The string "f5.12a" would not. 10 | Use this string to test your regular expression. 11 | */ 12 | String challenge7 = "abcd.135"; 13 | System.out.println(challenge7.matches("^\\w+\\.\\d+$")); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Section 17/Regular Expressions Challenge 8/src/Main.java: -------------------------------------------------------------------------------- 1 | import java.util.regex.Matcher; 2 | import java.util.regex.Pattern; 3 | 4 | public class Main { 5 | 6 | public static void main(String[] args) { 7 | /* 8 | Modify the regular expression in challenge 7 to use a group, 9 | so that we can print all the digits that occur in a string 10 | that contains multiple occurrences of the pattern. 11 | Write all the code required to accomplish this (create a pattern and matcher, etc.). 12 | 13 | There are three occurrences of the pattern we looked for in challenge #7. 14 | When you run your code, you should see 135, 7, and 999 printed to the console. 15 | */ 16 | String challenge8 = "abcd.135uvqz.7tzik.999"; 17 | Pattern pattern = Pattern.compile("\\w+\\.(\\d+)"); 18 | Matcher matcher = pattern.matcher(challenge8); 19 | 20 | while (matcher.find()) { 21 | System.out.println(matcher.group(1)); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Section 17/Regular Expressions Challenge 9/src/Main.java: -------------------------------------------------------------------------------- 1 | import java.util.regex.Matcher; 2 | import java.util.regex.Pattern; 3 | 4 | public class Main { 5 | 6 | public static void main(String[] args) { 7 | /* 8 | Let's suppose we're reading strings that match the patterns we used in challenges 7 and 8 from a file. 9 | Tabs are used to separate the matches, with one exception. 10 | The last match is followed by a newline. 11 | Revise the regular expression accordingly and extract all the numbers, as we did in challenge 8. 12 | */ 13 | String challenge9 = "abcd.135\tuvqz.7\ttzik.999\n"; 14 | Pattern pattern = Pattern.compile("\\w+\\.(\\d+)\\s"); 15 | Matcher matcher = pattern.matcher(challenge9); 16 | 17 | while (matcher.find()) { 18 | System.out.println("Occurrence: " + matcher.group(1)); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Section 18/JUnit Challenge 1/src/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | /* 5 | Create a JUnit test class that contains a test method for each method in the Utilities class. 6 | Don't add any test code to the methods yet. 7 | When you run the tests, they should all fail. 8 | Use the naming conventions we discussed in the JUnit lecture. 9 | Remember that you'll have to add the JUnit4 library to the test project. 10 | */ 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Section 18/JUnit Challenge 1/src/Utilities.java: -------------------------------------------------------------------------------- 1 | public class Utilities { 2 | 3 | // Returns a char array containing every nth char. 4 | // When sourceArray.length < n, returns sourceArray 5 | public char[] everyNthChar(char[] sourceArray, int n) { 6 | if (sourceArray == null || sourceArray.length < n) { 7 | return sourceArray; 8 | } 9 | 10 | int returnedLength = sourceArray.length / n; 11 | char[] result = new char[returnedLength]; 12 | int index = 0; 13 | 14 | for (int i = n - 1; i < sourceArray.length; i += n) { 15 | result[index++] = sourceArray[i]; 16 | } 17 | 18 | return result; 19 | } 20 | 21 | // Remove pairs of the same character that are next 22 | // to each other, by removing on occurrence of the character. 23 | // "ABBCDEEF" -> "ABCDEF" 24 | // "ABCBDEEF" -> "ABCBDEF" (two B's aren't next to each other, so they 25 | // aren't removed. 26 | public String removePairs(String source) { 27 | 28 | // If length is less than 2, there won't be any pairs 29 | if (source.length() < 2) { 30 | return source; 31 | } 32 | 33 | StringBuilder sb = new StringBuilder(); 34 | char[] string = source.toCharArray(); 35 | 36 | for (int i = 0; i < string.length; i++) { 37 | if (string[i] != string[i++]) { 38 | sb.append(string[i]); 39 | } 40 | } 41 | 42 | return sb.toString(); 43 | } 44 | 45 | // Perform a conversion based on some internal business rule. 46 | public int converter(int a, int b) { 47 | return (a / b) + (a * 30) - 2; 48 | } 49 | 50 | public String nullIfOddLength(String source) { 51 | if (source.length() % 2 == 0) { 52 | return source; 53 | } 54 | 55 | return null; 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /Section 18/JUnit Challenge 1/src/UtilitiesTest.java: -------------------------------------------------------------------------------- 1 | import static junit.framework.TestCase.fail; 2 | 3 | public class UtilitiesTest { 4 | 5 | @org.junit.Test 6 | public void everyNthChar() { 7 | fail("This test has not been implemented"); 8 | } 9 | 10 | @org.junit.Test 11 | public void removePairs() { 12 | fail("This test has not been implemented"); 13 | } 14 | 15 | @org.junit.Test 16 | public void converter() { 17 | fail("This test has not been implemented"); 18 | } 19 | 20 | @org.junit.Test 21 | public void nullIfOddLength() { 22 | fail("This test has not been implemented"); 23 | } 24 | } -------------------------------------------------------------------------------- /Section 18/JUnit Challenge 10/src/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | /* 5 | Test the following inputs and outputs. 6 | You could add all these tests to the existing test method, 7 | or write a method for each set of input/output, 8 | but that wouldn't be the best way to do it. 9 | 10 | Do it in such a way that you only have to write one test method. 11 | Hint: You'll have to create a new class that's using a particular JUnit annotation. 12 | 13 | Input = "ABCDEFF", Output = "ABCDEF" 14 | Input = "AB88EFFG", Output = "AB8EFG" 15 | Input = "112233445566", Output = "123456" 16 | Input = "ZYZQQB", Output = "ZYZQB" 17 | Input = "A", Output = "A" 18 | */ 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Section 18/JUnit Challenge 10/src/Utilities.java: -------------------------------------------------------------------------------- 1 | public class Utilities { 2 | 3 | // Returns a char array containing every nth char. 4 | // When sourceArray.length < n, returns sourceArray 5 | public char[] everyNthChar(char[] sourceArray, int n) { 6 | if (sourceArray == null || sourceArray.length < n) { 7 | return sourceArray; 8 | } 9 | 10 | int returnedLength = sourceArray.length / n; 11 | char[] result = new char[returnedLength]; 12 | int index = 0; 13 | 14 | for (int i = n - 1; i < sourceArray.length; i += n) { 15 | result[index++] = sourceArray[i]; 16 | } 17 | 18 | return result; 19 | } 20 | 21 | // Remove pairs of the same character that are next 22 | // to each other, by removing on occurrence of the character. 23 | // "ABBCDEEF" -> "ABCDEF" 24 | // "ABCBDEEF" -> "ABCBDEF" (two B's aren't next to each other, so they 25 | // aren't removed. 26 | public String removePairs(String source) { 27 | 28 | // If length is less than 2, there won't be any pairs 29 | if (source == null || source.length() < 2) { 30 | return source; 31 | } 32 | 33 | StringBuilder sb = new StringBuilder(); 34 | char[] string = source.toCharArray(); 35 | 36 | for (int i = 0; i < string.length - 1; i++) { 37 | if (string[i] != string[i + 1]) { 38 | sb.append(string[i]); 39 | } 40 | } 41 | 42 | // Add the final character, which is always safe 43 | sb.append(string[string.length - 1]); 44 | 45 | return sb.toString(); 46 | } 47 | 48 | // Perform a conversion based on some internal business rule. 49 | public int converter(int a, int b) { 50 | return (a / b) + (a * 30) - 2; 51 | } 52 | 53 | public String nullIfOddLength(String source) { 54 | if (source.length() % 2 == 0) { 55 | return source; 56 | } 57 | 58 | return null; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /Section 18/JUnit Challenge 10/src/UtilitiesTest.java: -------------------------------------------------------------------------------- 1 | import static org.junit.Assert.*; 2 | 3 | public class UtilitiesTest { 4 | 5 | private Utilities util; 6 | 7 | @org.junit.Before 8 | public void setup() { 9 | util = new Utilities(); 10 | } 11 | 12 | @org.junit.Test 13 | public void everyNthChar() { 14 | char[] array = new char[]{'h', 'e', 'l', 'l', 'o'}; 15 | assertArrayEquals(new char[]{'e', 'l'}, util.everyNthChar(array, 2)); 16 | assertArrayEquals(new char[]{'h', 'e', 'l', 'l', 'o'}, util.everyNthChar(array, 6)); 17 | } 18 | 19 | @org.junit.Test 20 | public void removePairs() { 21 | assertEquals("ABCDEF", util.removePairs("AABCDDEFF")); 22 | assertEquals("ABCABDEF", util.removePairs("ABCCABDEEF")); 23 | assertEquals("A", util.removePairs("A")); 24 | assertEquals("", util.removePairs("")); 25 | assertNull(util.removePairs(null)); 26 | } 27 | 28 | @org.junit.Test 29 | public void converter() { 30 | assertEquals(300, util.converter(10, 5)); 31 | } 32 | 33 | @org.junit.Test(expected = ArithmeticException.class) 34 | public void converter_arithmeticException() { 35 | util.converter(10, 0); 36 | } 37 | 38 | @org.junit.Test 39 | public void nullIfOddLength() { 40 | assertNull(util.nullIfOddLength("odd")); 41 | assertNotNull(util.nullIfOddLength("even")); 42 | } 43 | } -------------------------------------------------------------------------------- /Section 18/JUnit Challenge 10/src/UtilitiesTestParameterized.java: -------------------------------------------------------------------------------- 1 | import org.junit.runner.RunWith; 2 | import org.junit.runners.Parameterized; 3 | 4 | import java.util.Arrays; 5 | import java.util.Collection; 6 | 7 | import static junit.framework.TestCase.assertEquals; 8 | 9 | @RunWith(Parameterized.class) 10 | public class UtilitiesTestParameterized { 11 | 12 | private Utilities util; 13 | private String input; 14 | private String output; 15 | 16 | public UtilitiesTestParameterized(String input, String output) { 17 | this.input = input; 18 | this.output = output; 19 | } 20 | 21 | @org.junit.Before 22 | public void setup() { 23 | util = new Utilities(); 24 | } 25 | 26 | @Parameterized.Parameters 27 | public static Collection testConditions() { 28 | return Arrays.asList(new Object[][]{ 29 | {"ABCDEFF", "ABCDEF"}, 30 | {"AB88EFFG", "AB8EFG"}, 31 | {"112233445566", "123456"}, 32 | {"ZYZQQB", "ZYZQB"}, 33 | {"A", "A"} 34 | }); 35 | } 36 | 37 | @org.junit.Test 38 | public void removePairs() { 39 | assertEquals(output, util.removePairs(input)); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Section 18/JUnit Challenge 2/src/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | /* 5 | In this challenge, you'll create tests for the Utilities.removePairs() method. 6 | This method accepts a string and removes any pairs it contains by removing one half of the pair. 7 | For example: 8 | 9 | Input: AABCDDEFF 10 | Output: ABCDEF 11 | 12 | Input: ABCCABDEEF 13 | Output: ABCABDEF 14 | 15 | Write the test code that tests the above two scenarios. 16 | Start by writing a test for the first set of input/output. 17 | Once that test passes, add a test for the second input/output pair. 18 | To keep things simple, you can add the second test to the same test method, 19 | but if you want to be strict about it, you can create another test method for it. 20 | */ 21 | Utilities utils = new Utilities(); 22 | System.out.println(utils.removePairs("AABCDDEFF")); 23 | System.out.println(utils.removePairs("ABCCABDEEF")); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Section 18/JUnit Challenge 2/src/Utilities.java: -------------------------------------------------------------------------------- 1 | public class Utilities { 2 | 3 | // Returns a char array containing every nth char. 4 | // When sourceArray.length < n, returns sourceArray 5 | public char[] everyNthChar(char[] sourceArray, int n) { 6 | if (sourceArray == null || sourceArray.length < n) { 7 | return sourceArray; 8 | } 9 | 10 | int returnedLength = sourceArray.length / n; 11 | char[] result = new char[returnedLength]; 12 | int index = 0; 13 | 14 | for (int i = n - 1; i < sourceArray.length; i += n) { 15 | result[index++] = sourceArray[i]; 16 | } 17 | 18 | return result; 19 | } 20 | 21 | // Remove pairs of the same character that are next 22 | // to each other, by removing on occurrence of the character. 23 | // "ABBCDEEF" -> "ABCDEF" 24 | // "ABCBDEEF" -> "ABCBDEF" (two B's aren't next to each other, so they 25 | // aren't removed. 26 | public String removePairs(String source) { 27 | 28 | // If length is less than 2, there won't be any pairs 29 | if (source.length() < 2) { 30 | return source; 31 | } 32 | 33 | StringBuilder sb = new StringBuilder(); 34 | char[] string = source.toCharArray(); 35 | 36 | for (int i = 0; i < string.length - 1; i++) { 37 | if (string[i] != string[i + 1]) { 38 | sb.append(string[i]); 39 | } 40 | } 41 | 42 | // Add the final character, which is always safe 43 | sb.append(string[string.length - 1]); 44 | 45 | return sb.toString(); 46 | } 47 | 48 | // Perform a conversion based on some internal business rule. 49 | public int converter(int a, int b) { 50 | return (a / b) + (a * 30) - 2; 51 | } 52 | 53 | public String nullIfOddLength(String source) { 54 | if (source.length() % 2 == 0) { 55 | return source; 56 | } 57 | 58 | return null; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /Section 18/JUnit Challenge 2/src/UtilitiesTest.java: -------------------------------------------------------------------------------- 1 | import static junit.framework.TestCase.assertEquals; 2 | import static junit.framework.TestCase.fail; 3 | 4 | public class UtilitiesTest { 5 | 6 | @org.junit.Test 7 | public void everyNthChar() { 8 | fail("This test has not been implemented"); 9 | } 10 | 11 | @org.junit.Test 12 | public void removePairs() { 13 | Utilities util = new Utilities(); 14 | assertEquals("ABCDEF", util.removePairs("AABCDDEFF")); 15 | assertEquals("ABCABDEF", util.removePairs("ABCCABDEEF")); 16 | } 17 | 18 | @org.junit.Test 19 | public void converter() { 20 | fail("This test has not been implemented"); 21 | } 22 | 23 | @org.junit.Test 24 | public void nullIfOddLength() { 25 | fail("This test has not been implemented"); 26 | } 27 | } -------------------------------------------------------------------------------- /Section 18/JUnit Challenge 3/src/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | /* 5 | We wouldn't stop with the two tests we've run. 6 | Now it's time for you to come up with two more tests 7 | that don't test the same functionality as the existing tests. 8 | Take a look at the code, and see if you can think of another string 9 | we should pass to test a specific part of the code. 10 | 11 | There's also another special input value that we'd want to test, 12 | and which will reveal another bug in our code. 13 | You don't have to write the tests, 14 | just think of what the inputs and expected outputs would be. 15 | */ 16 | Utilities utils = new Utilities(); 17 | System.out.println(utils.removePairs("AABCDDEFF")); 18 | System.out.println(utils.removePairs("ABCCABDEEF")); 19 | System.out.println(utils.removePairs("A")); 20 | System.out.println(utils.removePairs("")); 21 | System.out.println(utils.removePairs(null)); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Section 18/JUnit Challenge 3/src/Utilities.java: -------------------------------------------------------------------------------- 1 | public class Utilities { 2 | 3 | // Returns a char array containing every nth char. 4 | // When sourceArray.length < n, returns sourceArray 5 | public char[] everyNthChar(char[] sourceArray, int n) { 6 | if (sourceArray == null || sourceArray.length < n) { 7 | return sourceArray; 8 | } 9 | 10 | int returnedLength = sourceArray.length / n; 11 | char[] result = new char[returnedLength]; 12 | int index = 0; 13 | 14 | for (int i = n - 1; i < sourceArray.length; i += n) { 15 | result[index++] = sourceArray[i]; 16 | } 17 | 18 | return result; 19 | } 20 | 21 | // Remove pairs of the same character that are next 22 | // to each other, by removing on occurrence of the character. 23 | // "ABBCDEEF" -> "ABCDEF" 24 | // "ABCBDEEF" -> "ABCBDEF" (two B's aren't next to each other, so they 25 | // aren't removed. 26 | public String removePairs(String source) { 27 | 28 | // If length is less than 2, there won't be any pairs 29 | if (source == null || source.length() < 2) { 30 | return source; 31 | } 32 | 33 | StringBuilder sb = new StringBuilder(); 34 | char[] string = source.toCharArray(); 35 | 36 | for (int i = 0; i < string.length - 1; i++) { 37 | if (string[i] != string[i + 1]) { 38 | sb.append(string[i]); 39 | } 40 | } 41 | 42 | // Add the final character, which is always safe 43 | sb.append(string[string.length - 1]); 44 | 45 | return sb.toString(); 46 | } 47 | 48 | // Perform a conversion based on some internal business rule. 49 | public int converter(int a, int b) { 50 | return (a / b) + (a * 30) - 2; 51 | } 52 | 53 | public String nullIfOddLength(String source) { 54 | if (source.length() % 2 == 0) { 55 | return source; 56 | } 57 | 58 | return null; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /Section 18/JUnit Challenge 3/src/UtilitiesTest.java: -------------------------------------------------------------------------------- 1 | import static junit.framework.TestCase.*; 2 | 3 | public class UtilitiesTest { 4 | 5 | @org.junit.Test 6 | public void everyNthChar() { 7 | fail("This test has not been implemented"); 8 | } 9 | 10 | @org.junit.Test 11 | public void removePairs() { 12 | Utilities util = new Utilities(); 13 | assertEquals("ABCDEF", util.removePairs("AABCDDEFF")); 14 | assertEquals("ABCABDEF", util.removePairs("ABCCABDEEF")); 15 | assertEquals("A", util.removePairs("A")); 16 | assertEquals("", util.removePairs("")); 17 | assertNull(util.removePairs(null)); 18 | } 19 | 20 | @org.junit.Test 21 | public void converter() { 22 | fail("This test has not been implemented"); 23 | } 24 | 25 | @org.junit.Test 26 | public void nullIfOddLength() { 27 | fail("This test has not been implemented"); 28 | } 29 | } -------------------------------------------------------------------------------- /Section 18/JUnit Challenge 4/src/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | /* 5 | Now write a test for the everyNthChar() method that tests the following scenario: 6 | Input: char array containing the letters 'h', 'e', 'l', 'l', 'o', in that order, and n = 2 7 | Output: char array containing the letters 'e', 'l', in that order 8 | */ 9 | Utilities util = new Utilities(); 10 | char[] array = new char[]{'h', 'e', 'l', 'l', 'o'}; 11 | System.out.println(util.everyNthChar(array, 2)); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Section 18/JUnit Challenge 4/src/Utilities.java: -------------------------------------------------------------------------------- 1 | public class Utilities { 2 | 3 | // Returns a char array containing every nth char. 4 | // When sourceArray.length < n, returns sourceArray 5 | public char[] everyNthChar(char[] sourceArray, int n) { 6 | if (sourceArray == null || sourceArray.length < n) { 7 | return sourceArray; 8 | } 9 | 10 | int returnedLength = sourceArray.length / n; 11 | char[] result = new char[returnedLength]; 12 | int index = 0; 13 | 14 | for (int i = n - 1; i < sourceArray.length; i += n) { 15 | result[index++] = sourceArray[i]; 16 | } 17 | 18 | return result; 19 | } 20 | 21 | // Remove pairs of the same character that are next 22 | // to each other, by removing on occurrence of the character. 23 | // "ABBCDEEF" -> "ABCDEF" 24 | // "ABCBDEEF" -> "ABCBDEF" (two B's aren't next to each other, so they 25 | // aren't removed. 26 | public String removePairs(String source) { 27 | 28 | // If length is less than 2, there won't be any pairs 29 | if (source == null || source.length() < 2) { 30 | return source; 31 | } 32 | 33 | StringBuilder sb = new StringBuilder(); 34 | char[] string = source.toCharArray(); 35 | 36 | for (int i = 0; i < string.length - 1; i++) { 37 | if (string[i] != string[i + 1]) { 38 | sb.append(string[i]); 39 | } 40 | } 41 | 42 | // Add the final character, which is always safe 43 | sb.append(string[string.length - 1]); 44 | 45 | return sb.toString(); 46 | } 47 | 48 | // Perform a conversion based on some internal business rule. 49 | public int converter(int a, int b) { 50 | return (a / b) + (a * 30) - 2; 51 | } 52 | 53 | public String nullIfOddLength(String source) { 54 | if (source.length() % 2 == 0) { 55 | return source; 56 | } 57 | 58 | return null; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /Section 18/JUnit Challenge 4/src/UtilitiesTest.java: -------------------------------------------------------------------------------- 1 | import static org.junit.Assert.*; 2 | 3 | public class UtilitiesTest { 4 | 5 | @org.junit.Test 6 | public void everyNthChar() { 7 | Utilities util = new Utilities(); 8 | char[] array = new char[]{'h', 'e', 'l', 'l', 'o'}; 9 | assertArrayEquals(new char[]{'e', 'l'}, util.everyNthChar(array, 2)); 10 | } 11 | 12 | @org.junit.Test 13 | public void removePairs() { 14 | Utilities util = new Utilities(); 15 | assertEquals("ABCDEF", util.removePairs("AABCDDEFF")); 16 | assertEquals("ABCABDEF", util.removePairs("ABCCABDEEF")); 17 | assertEquals("A", util.removePairs("A")); 18 | assertEquals("", util.removePairs("")); 19 | assertNull(util.removePairs(null)); 20 | } 21 | 22 | @org.junit.Test 23 | public void converter() { 24 | fail("This test has not been implemented"); 25 | } 26 | 27 | @org.junit.Test 28 | public void nullIfOddLength() { 29 | fail("This test has not been implemented"); 30 | } 31 | } -------------------------------------------------------------------------------- /Section 18/JUnit Challenge 5/src/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | /* 5 | Write a test that tests the case when the value of n is greater then the length of the string. 6 | You can add a new test case, or you can add the test to the existing test case. 7 | */ 8 | Utilities util = new Utilities(); 9 | char[] array = new char[]{'h', 'e', 'l', 'l', 'o'}; 10 | System.out.println(util.everyNthChar(array, 6)); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Section 18/JUnit Challenge 5/src/Utilities.java: -------------------------------------------------------------------------------- 1 | public class Utilities { 2 | 3 | // Returns a char array containing every nth char. 4 | // When sourceArray.length < n, returns sourceArray 5 | public char[] everyNthChar(char[] sourceArray, int n) { 6 | if (sourceArray == null || sourceArray.length < n) { 7 | return sourceArray; 8 | } 9 | 10 | int returnedLength = sourceArray.length / n; 11 | char[] result = new char[returnedLength]; 12 | int index = 0; 13 | 14 | for (int i = n - 1; i < sourceArray.length; i += n) { 15 | result[index++] = sourceArray[i]; 16 | } 17 | 18 | return result; 19 | } 20 | 21 | // Remove pairs of the same character that are next 22 | // to each other, by removing on occurrence of the character. 23 | // "ABBCDEEF" -> "ABCDEF" 24 | // "ABCBDEEF" -> "ABCBDEF" (two B's aren't next to each other, so they 25 | // aren't removed. 26 | public String removePairs(String source) { 27 | 28 | // If length is less than 2, there won't be any pairs 29 | if (source == null || source.length() < 2) { 30 | return source; 31 | } 32 | 33 | StringBuilder sb = new StringBuilder(); 34 | char[] string = source.toCharArray(); 35 | 36 | for (int i = 0; i < string.length - 1; i++) { 37 | if (string[i] != string[i + 1]) { 38 | sb.append(string[i]); 39 | } 40 | } 41 | 42 | // Add the final character, which is always safe 43 | sb.append(string[string.length - 1]); 44 | 45 | return sb.toString(); 46 | } 47 | 48 | // Perform a conversion based on some internal business rule. 49 | public int converter(int a, int b) { 50 | return (a / b) + (a * 30) - 2; 51 | } 52 | 53 | public String nullIfOddLength(String source) { 54 | if (source.length() % 2 == 0) { 55 | return source; 56 | } 57 | 58 | return null; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /Section 18/JUnit Challenge 5/src/UtilitiesTest.java: -------------------------------------------------------------------------------- 1 | import static org.junit.Assert.*; 2 | 3 | public class UtilitiesTest { 4 | 5 | @org.junit.Test 6 | public void everyNthChar() { 7 | Utilities util = new Utilities(); 8 | char[] array = new char[]{'h', 'e', 'l', 'l', 'o'}; 9 | assertArrayEquals(new char[]{'e', 'l'}, util.everyNthChar(array, 2)); 10 | assertArrayEquals(new char[]{'h', 'e', 'l', 'l', 'o'}, util.everyNthChar(array, 6)); 11 | } 12 | 13 | @org.junit.Test 14 | public void removePairs() { 15 | Utilities util = new Utilities(); 16 | assertEquals("ABCDEF", util.removePairs("AABCDDEFF")); 17 | assertEquals("ABCABDEF", util.removePairs("ABCCABDEEF")); 18 | assertEquals("A", util.removePairs("A")); 19 | assertEquals("", util.removePairs("")); 20 | assertNull(util.removePairs(null)); 21 | } 22 | 23 | @org.junit.Test 24 | public void converter() { 25 | fail("This test has not been implemented"); 26 | } 27 | 28 | @org.junit.Test 29 | public void nullIfOddLength() { 30 | fail("This test has not been implemented"); 31 | } 32 | } -------------------------------------------------------------------------------- /Section 18/JUnit Challenge 6/src/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | /* 5 | Now write two tests for the nullIfOddLength() method. 6 | Include both tests in the nullIfOddLength() test method. 7 | In one test, pass an String that has an even length, 8 | and in the second test, pass an String that has an odd length. 9 | */ 10 | Utilities util = new Utilities(); 11 | System.out.println(util.nullIfOddLength("odd")); 12 | System.out.println(util.nullIfOddLength("even")); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Section 18/JUnit Challenge 6/src/Utilities.java: -------------------------------------------------------------------------------- 1 | public class Utilities { 2 | 3 | // Returns a char array containing every nth char. 4 | // When sourceArray.length < n, returns sourceArray 5 | public char[] everyNthChar(char[] sourceArray, int n) { 6 | if (sourceArray == null || sourceArray.length < n) { 7 | return sourceArray; 8 | } 9 | 10 | int returnedLength = sourceArray.length / n; 11 | char[] result = new char[returnedLength]; 12 | int index = 0; 13 | 14 | for (int i = n - 1; i < sourceArray.length; i += n) { 15 | result[index++] = sourceArray[i]; 16 | } 17 | 18 | return result; 19 | } 20 | 21 | // Remove pairs of the same character that are next 22 | // to each other, by removing on occurrence of the character. 23 | // "ABBCDEEF" -> "ABCDEF" 24 | // "ABCBDEEF" -> "ABCBDEF" (two B's aren't next to each other, so they 25 | // aren't removed. 26 | public String removePairs(String source) { 27 | 28 | // If length is less than 2, there won't be any pairs 29 | if (source == null || source.length() < 2) { 30 | return source; 31 | } 32 | 33 | StringBuilder sb = new StringBuilder(); 34 | char[] string = source.toCharArray(); 35 | 36 | for (int i = 0; i < string.length - 1; i++) { 37 | if (string[i] != string[i + 1]) { 38 | sb.append(string[i]); 39 | } 40 | } 41 | 42 | // Add the final character, which is always safe 43 | sb.append(string[string.length - 1]); 44 | 45 | return sb.toString(); 46 | } 47 | 48 | // Perform a conversion based on some internal business rule. 49 | public int converter(int a, int b) { 50 | return (a / b) + (a * 30) - 2; 51 | } 52 | 53 | public String nullIfOddLength(String source) { 54 | if (source.length() % 2 == 0) { 55 | return source; 56 | } 57 | 58 | return null; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /Section 18/JUnit Challenge 6/src/UtilitiesTest.java: -------------------------------------------------------------------------------- 1 | import static org.junit.Assert.*; 2 | 3 | public class UtilitiesTest { 4 | 5 | @org.junit.Test 6 | public void everyNthChar() { 7 | Utilities util = new Utilities(); 8 | char[] array = new char[]{'h', 'e', 'l', 'l', 'o'}; 9 | assertArrayEquals(new char[]{'e', 'l'}, util.everyNthChar(array, 2)); 10 | assertArrayEquals(new char[]{'h', 'e', 'l', 'l', 'o'}, util.everyNthChar(array, 6)); 11 | } 12 | 13 | @org.junit.Test 14 | public void removePairs() { 15 | Utilities util = new Utilities(); 16 | assertEquals("ABCDEF", util.removePairs("AABCDDEFF")); 17 | assertEquals("ABCABDEF", util.removePairs("ABCCABDEEF")); 18 | assertEquals("A", util.removePairs("A")); 19 | assertEquals("", util.removePairs("")); 20 | assertNull(util.removePairs(null)); 21 | } 22 | 23 | @org.junit.Test 24 | public void converter() { 25 | fail("This test has not been implemented"); 26 | } 27 | 28 | @org.junit.Test 29 | public void nullIfOddLength() { 30 | Utilities util = new Utilities(); 31 | assertNull(util.nullIfOddLength("odd")); 32 | assertNotNull(util.nullIfOddLength("even")); 33 | } 34 | } -------------------------------------------------------------------------------- /Section 18/JUnit Challenge 7/src/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | /* 5 | Test the converter() method with the following input/output: 6 | Input: a = 10, b = 5 7 | Output: 300 8 | */ 9 | Utilities util = new Utilities(); 10 | System.out.println(util.converter(10, 5)); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Section 18/JUnit Challenge 7/src/Utilities.java: -------------------------------------------------------------------------------- 1 | public class Utilities { 2 | 3 | // Returns a char array containing every nth char. 4 | // When sourceArray.length < n, returns sourceArray 5 | public char[] everyNthChar(char[] sourceArray, int n) { 6 | if (sourceArray == null || sourceArray.length < n) { 7 | return sourceArray; 8 | } 9 | 10 | int returnedLength = sourceArray.length / n; 11 | char[] result = new char[returnedLength]; 12 | int index = 0; 13 | 14 | for (int i = n - 1; i < sourceArray.length; i += n) { 15 | result[index++] = sourceArray[i]; 16 | } 17 | 18 | return result; 19 | } 20 | 21 | // Remove pairs of the same character that are next 22 | // to each other, by removing on occurrence of the character. 23 | // "ABBCDEEF" -> "ABCDEF" 24 | // "ABCBDEEF" -> "ABCBDEF" (two B's aren't next to each other, so they 25 | // aren't removed. 26 | public String removePairs(String source) { 27 | 28 | // If length is less than 2, there won't be any pairs 29 | if (source == null || source.length() < 2) { 30 | return source; 31 | } 32 | 33 | StringBuilder sb = new StringBuilder(); 34 | char[] string = source.toCharArray(); 35 | 36 | for (int i = 0; i < string.length - 1; i++) { 37 | if (string[i] != string[i + 1]) { 38 | sb.append(string[i]); 39 | } 40 | } 41 | 42 | // Add the final character, which is always safe 43 | sb.append(string[string.length - 1]); 44 | 45 | return sb.toString(); 46 | } 47 | 48 | // Perform a conversion based on some internal business rule. 49 | public int converter(int a, int b) { 50 | return (a / b) + (a * 30) - 2; 51 | } 52 | 53 | public String nullIfOddLength(String source) { 54 | if (source.length() % 2 == 0) { 55 | return source; 56 | } 57 | 58 | return null; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /Section 18/JUnit Challenge 7/src/UtilitiesTest.java: -------------------------------------------------------------------------------- 1 | import static org.junit.Assert.*; 2 | 3 | public class UtilitiesTest { 4 | 5 | @org.junit.Test 6 | public void everyNthChar() { 7 | Utilities util = new Utilities(); 8 | char[] array = new char[]{'h', 'e', 'l', 'l', 'o'}; 9 | assertArrayEquals(new char[]{'e', 'l'}, util.everyNthChar(array, 2)); 10 | assertArrayEquals(new char[]{'h', 'e', 'l', 'l', 'o'}, util.everyNthChar(array, 6)); 11 | } 12 | 13 | @org.junit.Test 14 | public void removePairs() { 15 | Utilities util = new Utilities(); 16 | assertEquals("ABCDEF", util.removePairs("AABCDDEFF")); 17 | assertEquals("ABCABDEF", util.removePairs("ABCCABDEEF")); 18 | assertEquals("A", util.removePairs("A")); 19 | assertEquals("", util.removePairs("")); 20 | assertNull(util.removePairs(null)); 21 | } 22 | 23 | @org.junit.Test 24 | public void converter() { 25 | Utilities util = new Utilities(); 26 | assertEquals(300, util.converter(10, 5)); 27 | } 28 | 29 | @org.junit.Test 30 | public void nullIfOddLength() { 31 | Utilities util = new Utilities(); 32 | assertNull(util.nullIfOddLength("odd")); 33 | assertNotNull(util.nullIfOddLength("even")); 34 | } 35 | } -------------------------------------------------------------------------------- /Section 18/JUnit Challenge 8/src/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | /* 5 | Now write a test for the converter() method that tests the following scenario. 6 | You can add the test to the existing test method, or create a new one. 7 | Input: a = 10, b = 0 8 | Output: ArithmeticException (divide by 0) 9 | */ 10 | Utilities util = new Utilities(); 11 | System.out.println(util.converter(10, 0)); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Section 18/JUnit Challenge 8/src/Utilities.java: -------------------------------------------------------------------------------- 1 | public class Utilities { 2 | 3 | // Returns a char array containing every nth char. 4 | // When sourceArray.length < n, returns sourceArray 5 | public char[] everyNthChar(char[] sourceArray, int n) { 6 | if (sourceArray == null || sourceArray.length < n) { 7 | return sourceArray; 8 | } 9 | 10 | int returnedLength = sourceArray.length / n; 11 | char[] result = new char[returnedLength]; 12 | int index = 0; 13 | 14 | for (int i = n - 1; i < sourceArray.length; i += n) { 15 | result[index++] = sourceArray[i]; 16 | } 17 | 18 | return result; 19 | } 20 | 21 | // Remove pairs of the same character that are next 22 | // to each other, by removing on occurrence of the character. 23 | // "ABBCDEEF" -> "ABCDEF" 24 | // "ABCBDEEF" -> "ABCBDEF" (two B's aren't next to each other, so they 25 | // aren't removed. 26 | public String removePairs(String source) { 27 | 28 | // If length is less than 2, there won't be any pairs 29 | if (source == null || source.length() < 2) { 30 | return source; 31 | } 32 | 33 | StringBuilder sb = new StringBuilder(); 34 | char[] string = source.toCharArray(); 35 | 36 | for (int i = 0; i < string.length - 1; i++) { 37 | if (string[i] != string[i + 1]) { 38 | sb.append(string[i]); 39 | } 40 | } 41 | 42 | // Add the final character, which is always safe 43 | sb.append(string[string.length - 1]); 44 | 45 | return sb.toString(); 46 | } 47 | 48 | // Perform a conversion based on some internal business rule. 49 | public int converter(int a, int b) { 50 | return (a / b) + (a * 30) - 2; 51 | } 52 | 53 | public String nullIfOddLength(String source) { 54 | if (source.length() % 2 == 0) { 55 | return source; 56 | } 57 | 58 | return null; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /Section 18/JUnit Challenge 8/src/UtilitiesTest.java: -------------------------------------------------------------------------------- 1 | import static org.junit.Assert.*; 2 | 3 | public class UtilitiesTest { 4 | 5 | @org.junit.Test 6 | public void everyNthChar() { 7 | Utilities util = new Utilities(); 8 | char[] array = new char[]{'h', 'e', 'l', 'l', 'o'}; 9 | assertArrayEquals(new char[]{'e', 'l'}, util.everyNthChar(array, 2)); 10 | assertArrayEquals(new char[]{'h', 'e', 'l', 'l', 'o'}, util.everyNthChar(array, 6)); 11 | } 12 | 13 | @org.junit.Test 14 | public void removePairs() { 15 | Utilities util = new Utilities(); 16 | assertEquals("ABCDEF", util.removePairs("AABCDDEFF")); 17 | assertEquals("ABCABDEF", util.removePairs("ABCCABDEEF")); 18 | assertEquals("A", util.removePairs("A")); 19 | assertEquals("", util.removePairs("")); 20 | assertNull(util.removePairs(null)); 21 | } 22 | 23 | @org.junit.Test 24 | public void converter() { 25 | Utilities util = new Utilities(); 26 | assertEquals(300, util.converter(10, 5)); 27 | } 28 | 29 | @org.junit.Test(expected = ArithmeticException.class) 30 | public void converter_arithmeticException() { 31 | Utilities util = new Utilities(); 32 | assertEquals(300, util.converter(10, 0)); 33 | } 34 | 35 | @org.junit.Test 36 | public void nullIfOddLength() { 37 | Utilities util = new Utilities(); 38 | assertNull(util.nullIfOddLength("odd")); 39 | assertNotNull(util.nullIfOddLength("even")); 40 | } 41 | } -------------------------------------------------------------------------------- /Section 18/JUnit Challenge 9/src/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | /* 5 | All of our test methods are now implemented, and our test are passing. 6 | We'd want to write more test cases to cover scenarios the existing ones don't test, 7 | but we'll pretend we're done. We could stop here, but every one of the test cases 8 | starts by creating an instance of the Utilities class. Modify the UtilitiesTest class 9 | so that it doesn't have this repetitive code. 10 | */ 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Section 18/JUnit Challenge 9/src/Utilities.java: -------------------------------------------------------------------------------- 1 | public class Utilities { 2 | 3 | // Returns a char array containing every nth char. 4 | // When sourceArray.length < n, returns sourceArray 5 | public char[] everyNthChar(char[] sourceArray, int n) { 6 | if (sourceArray == null || sourceArray.length < n) { 7 | return sourceArray; 8 | } 9 | 10 | int returnedLength = sourceArray.length / n; 11 | char[] result = new char[returnedLength]; 12 | int index = 0; 13 | 14 | for (int i = n - 1; i < sourceArray.length; i += n) { 15 | result[index++] = sourceArray[i]; 16 | } 17 | 18 | return result; 19 | } 20 | 21 | // Remove pairs of the same character that are next 22 | // to each other, by removing on occurrence of the character. 23 | // "ABBCDEEF" -> "ABCDEF" 24 | // "ABCBDEEF" -> "ABCBDEF" (two B's aren't next to each other, so they 25 | // aren't removed. 26 | public String removePairs(String source) { 27 | 28 | // If length is less than 2, there won't be any pairs 29 | if (source == null || source.length() < 2) { 30 | return source; 31 | } 32 | 33 | StringBuilder sb = new StringBuilder(); 34 | char[] string = source.toCharArray(); 35 | 36 | for (int i = 0; i < string.length - 1; i++) { 37 | if (string[i] != string[i + 1]) { 38 | sb.append(string[i]); 39 | } 40 | } 41 | 42 | // Add the final character, which is always safe 43 | sb.append(string[string.length - 1]); 44 | 45 | return sb.toString(); 46 | } 47 | 48 | // Perform a conversion based on some internal business rule. 49 | public int converter(int a, int b) { 50 | return (a / b) + (a * 30) - 2; 51 | } 52 | 53 | public String nullIfOddLength(String source) { 54 | if (source.length() % 2 == 0) { 55 | return source; 56 | } 57 | 58 | return null; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /Section 18/JUnit Challenge 9/src/UtilitiesTest.java: -------------------------------------------------------------------------------- 1 | import static org.junit.Assert.*; 2 | 3 | public class UtilitiesTest { 4 | 5 | private Utilities util; 6 | 7 | @org.junit.Before 8 | public void setup() { 9 | util = new Utilities(); 10 | } 11 | 12 | @org.junit.Test 13 | public void everyNthChar() { 14 | char[] array = new char[]{'h', 'e', 'l', 'l', 'o'}; 15 | assertArrayEquals(new char[]{'e', 'l'}, util.everyNthChar(array, 2)); 16 | assertArrayEquals(new char[]{'h', 'e', 'l', 'l', 'o'}, util.everyNthChar(array, 6)); 17 | } 18 | 19 | @org.junit.Test 20 | public void removePairs() { 21 | assertEquals("ABCDEF", util.removePairs("AABCDDEFF")); 22 | assertEquals("ABCABDEF", util.removePairs("ABCCABDEEF")); 23 | assertEquals("A", util.removePairs("A")); 24 | assertEquals("", util.removePairs("")); 25 | assertNull(util.removePairs(null)); 26 | } 27 | 28 | @org.junit.Test 29 | public void converter() { 30 | assertEquals(300, util.converter(10, 5)); 31 | } 32 | 33 | @org.junit.Test(expected = ArithmeticException.class) 34 | public void converter_arithmeticException() { 35 | assertEquals(300, util.converter(10, 0)); 36 | } 37 | 38 | @org.junit.Test 39 | public void nullIfOddLength() { 40 | assertNull(util.nullIfOddLength("odd")); 41 | assertNotNull(util.nullIfOddLength("even")); 42 | } 43 | } -------------------------------------------------------------------------------- /Section 19/music.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/elvarlax/java-masterclass/77dacdc826f69057ebb12c60315da4c782104f7b/Section 19/music.db -------------------------------------------------------------------------------- /Section 22/Module Challenge/academy.learnprogramming.common/src/academy/learnprogramming/common/Album.java: -------------------------------------------------------------------------------- 1 | package academy.learnprogramming.common; 2 | 3 | import javafx.beans.property.SimpleIntegerProperty; 4 | import javafx.beans.property.SimpleStringProperty; 5 | 6 | public class Album { 7 | 8 | private SimpleIntegerProperty id; 9 | private SimpleStringProperty name; 10 | private SimpleIntegerProperty artistId; 11 | 12 | public Album() { 13 | this.id = new SimpleIntegerProperty(); 14 | this.name = new SimpleStringProperty(); 15 | this.artistId = new SimpleIntegerProperty(); 16 | } 17 | 18 | public int getId() { 19 | return id.get(); 20 | } 21 | 22 | public void setId(int id) { 23 | this.id.set(id); 24 | } 25 | 26 | public String getName() { 27 | return name.get(); 28 | } 29 | 30 | public void setName(String name) { 31 | this.name.set(name); 32 | } 33 | 34 | public int getArtistId() { 35 | return artistId.get(); 36 | } 37 | 38 | public void setArtistId(int artistId) { 39 | this.artistId.set(artistId); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Section 22/Module Challenge/academy.learnprogramming.common/src/academy/learnprogramming/common/Artist.java: -------------------------------------------------------------------------------- 1 | package academy.learnprogramming.common; 2 | 3 | import javafx.beans.property.SimpleIntegerProperty; 4 | import javafx.beans.property.SimpleStringProperty; 5 | 6 | public class Artist { 7 | 8 | private SimpleIntegerProperty id; 9 | private SimpleStringProperty name; 10 | 11 | public Artist() { 12 | this.id = new SimpleIntegerProperty(); 13 | this.name = new SimpleStringProperty(); 14 | } 15 | 16 | public int getId() { 17 | return id.get(); 18 | } 19 | 20 | public void setId(int id) { 21 | this.id.set(id); 22 | } 23 | 24 | public String getName() { 25 | return name.get(); 26 | } 27 | 28 | public void setName(String name) { 29 | this.name.set(name); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Section 22/Module Challenge/academy.learnprogramming.common/src/module-info.java: -------------------------------------------------------------------------------- 1 | module academy.learnprogramming.common { 2 | requires javafx.base; 3 | 4 | exports academy.learnprogramming.common; 5 | 6 | opens academy.learnprogramming.common to javafx.base; 7 | } -------------------------------------------------------------------------------- /Section 22/Module Challenge/academy.learnprogramming.db/src/module-info.java: -------------------------------------------------------------------------------- 1 | module academy.learnprogramming.db { 2 | requires java.sql; 3 | requires sqlite.jdbc; 4 | requires transitive academy.learnprogramming.common; 5 | 6 | exports academy.learnprogramming.db; 7 | } -------------------------------------------------------------------------------- /Section 22/Module Challenge/academy.learnprogramming.ui/src/academy/learnprogramming/ui/Controller.java: -------------------------------------------------------------------------------- 1 | package academy.learnprogramming.ui; 2 | 3 | import academy.learnprogramming.common.Album; 4 | import academy.learnprogramming.common.Artist; 5 | import academy.learnprogramming.db.DataSource; 6 | import javafx.collections.FXCollections; 7 | import javafx.collections.ObservableList; 8 | import javafx.concurrent.Task; 9 | import javafx.fxml.FXML; 10 | import javafx.scene.control.ProgressBar; 11 | import javafx.scene.control.TableView; 12 | 13 | public class Controller { 14 | 15 | @FXML 16 | private TableView artistTable; 17 | 18 | @FXML 19 | private ProgressBar progressBar; 20 | 21 | @FXML 22 | public void listArtists() { 23 | Task> task = new GetAllArtistsTask(); 24 | artistTable.itemsProperty().bind(task.valueProperty()); 25 | progressBar.progressProperty().bind(task.progressProperty()); 26 | 27 | progressBar.setVisible(true); 28 | 29 | task.setOnSucceeded(e -> progressBar.setVisible(false)); 30 | task.setOnFailed(e -> progressBar.setVisible(false)); 31 | 32 | new Thread(task).start(); 33 | } 34 | 35 | @FXML 36 | public void listAlbumsForArtist() { 37 | final Artist artist = (Artist) artistTable.getSelectionModel().getSelectedItem(); 38 | if (artist == null) { 39 | System.out.println("NO ARTIST SELECTED"); 40 | return; 41 | } 42 | 43 | Task> task = new Task>() { 44 | @Override 45 | protected ObservableList call() throws Exception { 46 | return FXCollections.observableArrayList( 47 | DataSource.getInstance().queryAlbumsForArtistId(artist.getId())); 48 | } 49 | }; 50 | 51 | artistTable.itemsProperty().bind(task.valueProperty()); 52 | 53 | new Thread(task).start(); 54 | } 55 | } 56 | 57 | class GetAllArtistsTask extends Task { 58 | 59 | @Override 60 | public ObservableList call() { 61 | return FXCollections.observableArrayList 62 | (DataSource.getInstance().queryArtists(DataSource.ORDER_BY_ASC)); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /Section 22/Module Challenge/academy.learnprogramming.ui/src/academy/learnprogramming/ui/Main.java: -------------------------------------------------------------------------------- 1 | package academy.learnprogramming.ui; 2 | 3 | import academy.learnprogramming.db.DataSource; 4 | import javafx.application.Application; 5 | import javafx.application.Platform; 6 | import javafx.fxml.FXMLLoader; 7 | import javafx.scene.Parent; 8 | import javafx.scene.Scene; 9 | import javafx.stage.Stage; 10 | 11 | public class Main extends Application { 12 | /* 13 | Migrating: ui module 14 | The challenge is to fix the project and make it run properly. 15 | 16 | Steps: 17 | 1. Create the ui module. 18 | 2. Move the ui package to the new ui module. 19 | 3. Fix all module-info files (all three may need to be changed). 20 | 4. Note: The project needs to run the same as before without any exceptions! 21 | */ 22 | 23 | @Override 24 | public void start(Stage primaryStage) throws Exception { 25 | FXMLLoader loader = new FXMLLoader(getClass().getResource("/academy/learnprogramming/ui/main.fxml")); 26 | Parent root = loader.load(); 27 | Controller controller = loader.getController(); 28 | controller.listArtists(); 29 | 30 | primaryStage.setTitle("Music Database"); 31 | primaryStage.setScene(new Scene(root, 800, 600)); 32 | primaryStage.show(); 33 | } 34 | 35 | @Override 36 | public void init() throws Exception { 37 | super.init(); 38 | if (!DataSource.getInstance().open()) { 39 | System.out.println("FATAL ERROR: Couldn't connect to database"); 40 | Platform.exit(); 41 | } 42 | } 43 | 44 | @Override 45 | public void stop() throws Exception { 46 | super.stop(); 47 | DataSource.getInstance().close(); 48 | } 49 | 50 | public static void main(String[] args) { 51 | launch(args); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Section 22/Module Challenge/academy.learnprogramming.ui/src/academy/learnprogramming/ui/main.fxml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 |