├── Coding Exercises 01 - Speed Converter ├── Exercise Description.txt └── SpeedConverter.java ├── Coding Exercises 02 - MegaBytes Converter ├── Exercise Description.txt └── MegaBytesConverter.java ├── Coding Exercises 03 - Barking Dog ├── BarkingDog.java └── Exercise Description.txt ├── Coding Exercises 04 - Leap Year Calculator ├── Exercise Description.txt └── LeapYear.java ├── Coding Exercises 05 - Decimal Comparator ├── DecimalComparator.java └── Exercise Description.txt ├── Coding Exercises 06 - Equal Sum Checker ├── EqualSumChecker.java └── Exercise Description.txt ├── Coding Exercises 07 - Teen Number Checker ├── Exercise Description.txt └── TeenNumberChecker.java ├── Coding Exercises 08 - Area Calculator ├── AreaCalculator.java └── Exercise Description.txt ├── Coding Exercises 09 - Minutes to Years and Days Calculator ├── Exercise Description.txt └── MinutesToYearsDaysCalculator.java ├── Coding Exercises 10 - Equality Printer ├── Exercise Description.txt └── IntEqualityPrinte.java ├── Coding Exercises 11 - Playing Cat ├── Exercise Description.txt └── PlayingCat.java ├── Coding Exercises 12 - Number In Word ├── Exercise Description.txt └── NumberInWord.java ├── Coding Exercises 13 - Number Of Days In Month ├── Exercise Description.txt └── NumberOfDaysInMonth.java ├── Coding Exercises 14 - Sum Odd ├── Exercise Description.txt └── SumOddRange.java ├── Coding Exercises 15 - Number Palindrome ├── Exercise Description.txt └── NumberPalindrome.java ├── Coding Exercises 16 - First And Last Digit Sum ├── Exercise Description.txt └── FirstLastDigitSum.java ├── Coding Exercises 17 - Even Digit Sum ├── EvenDigitSum.java └── Exercise Description.txt ├── Coding Exercises 18 - Shared Digit ├── Exercise Description.txt └── SharedDigit.java ├── Coding Exercises 19 - Last Digit Checker ├── Exercise Description.txt └── LastDigitChecker.java ├── Coding Exercises 20 - Greatest Common Divisor ├── Exercise Description.txt └── GreatestCommonDivisor.java ├── Coding Exercises 21 - All Factors ├── Exercise Description.txt └── FactorPrinter.java ├── Coding Exercises 22 - Prefect Number ├── Exercise Description.txt └── PerfectNumber.java ├── Coding Exercises 23 - Number To Words ├── Exercise Description.txt └── NumberToWords.java ├── Coding Exercises 24 - Flour Pack Problem ├── Exercise Description.txt └── FlourPacker.java ├── Coding Exercises 25 - Largest Prime ├── Exercise Description.txt └── LargestPrime.java ├── Coding Exercises 26 - Diagonal Star ├── DiagonalStar.java └── Exercise Description.txt ├── Coding Exercises 27 - Input Calculator ├── Exercise Description.txt └── InputCalculator.java ├── Coding Exercises 28 - Paint Job ├── Exercise Description.txt └── PaintJob.java ├── Coding Exercises 29 - Sum Calculator ├── Exercise Description.txt └── SimpleCalculator.java ├── Coding Exercises 30 - Person ├── Exercise Description.txt └── Person.java ├── Coding Exercises 31 - Wall Area ├── Exercise Description.txt └── Wall.java ├── Coding Exercises 32 - Point ├── Exercise Description.txt └── Point.java ├── Coding Exercises 33 - Carpet Cost Calculator ├── Calculator.java ├── Carpet.java ├── Exercise Description.txt └── Floor.java ├── Coding Exercises 34 - Complex Operation ├── ComplexNumber.java └── Exercise Description.txt ├── Coding Exercises 35 - Cylinder ├── Circle.java ├── Cylinder.java └── Exercise Description.txt ├── Coding Exercises 36 - Pool Area ├── Cuboid.java ├── Exercise Description.txt └── Rectangle.java ├── Coding Exercises 37 - Composition ├── Bed.java ├── Bedroom.java ├── Ceiling.java ├── Lamp.java └── Wall.java ├── Coding Exercises 38 - Encapsulation └── Printer.java ├── Coding Exercises 39 - Polymorphism ├── Car.java ├── Ford.java ├── Holden.java └── Mitsubishi.java ├── Coding Exercises 40 - Bill's Burgers ├── DeluxeBurger.java ├── Exercise Description.txt ├── Hamburger.java └── HealthyBurger.java ├── Coding Exercises 41 - Sorted Array ├── Exercise Description.txt └── SortedArray.java ├── Coding Exercises 42- Minimum Element ├── Exercise Description.txt └── MinimumElement.java ├── Coding Exercises 43 - Reverse Array ├── Exercise Description.txt └── ReverseArray.java ├── Coding Exercises 44 - Mobile Phone ├── Contact.java ├── Exercise Description.txt └── MobilePhone.java ├── Coding Exercises 45 - Banking ├── Bank.java ├── Branch.java ├── Customer.java └── Exercise Description.txt ├── Coding Exercises 46 - Playlist ├── Album.java ├── Exercise Description.txt └── Song.java ├── Coding Exercises 47 - Interface ├── Exercise Description.txt ├── ISaveable.java ├── Monster.java └── Player.java ├── Coding Exercises 48 - Playlist - Inner Class ├── Album.java ├── Exercise Description.txt └── Song.java ├── Coding Exercises 49 - Abstract Class ├── Exercise Description.txt ├── ListItem.java ├── MyLinkedList.java ├── Node.java ├── NodeList.java └── SearchTree.java ├── Coding Exercises 50 - Adventure Game ├── Exercise Description.txt ├── Location.java └── Main.java ├── Coding Exercises 51 - Immutable Class ├── Exercise Description.txt └── Location.java ├── Coding Exercises 52 - Sets ├── DwarfPlanet.java ├── HeavenlyBody.java ├── Moon.java └── Planet.java └── README.md /Coding Exercises 01 - Speed Converter/Exercise Description.txt: -------------------------------------------------------------------------------- 1 | 1. Write a method called toMilesPerHour that has 1 parameter of type double with the name kilometersPerHour. This method needs to return the rounded value of the calculation of type long. 2 | 3 | If the parameter kilometersPerHour is less than 0, the method toMilesPerHour needs to return -1 to indicate an invalid value. 4 | 5 | Otherwise, if it is positive, calculate the value of miles per hour, round it and return it. For conversion and rounding, check the notes in the text below. 6 | 7 | Examples of input/output: 8 | * toMilesPerHour(1.5); → should return value 1 9 | * toMilesPerHour(10.25); → should return value 6 10 | * toMilesPerHour(-5.6); → should return value -1 11 | * toMilesPerHour(25.42); → should return value 16 12 | * toMilesPerHour(75.114); → should return value 47 13 | 14 | 15 | 2. Write another method called printConversion with 1 parameter of type double with the name kilometersPerHour. 16 | 17 | This method should not return anything (void) and it needs to calculate milesPerHour from the kilometersPerHour parameter. 18 | 19 | Then it needs to print a message in the format "XX km/h = YY mi/h". 20 | 21 | XX represents the original value kilometersPerHour. 22 | YY represents the rounded milesPerHour from the kilometersPerHour parameter. 23 | 24 | If the parameter kilometersPerHour is < 0 then print the text "Invalid Value". 25 | 26 | 27 | Examples of input/output: 28 | * printConversion(1.5); → should print the following text (into the console - System.out): 1.5 km/h = 1 mi/h 29 | * printConversion(10.25); → should print the following text (into the console - System.out): 10.25 km/h = 6 mi/h 30 | * printConversion(-5.6); → should print the following text (into the console - System.out): Invalid Value 31 | * printConversion(25.42); → should print the following text (into the console - System.out): 25.42 km/h = 16 mi/h 32 | * printConversion(75.114); → should print the following text (into the console - System.out): 75.114 km/h = 47 mi/h 33 | 34 | 35 | Use method Math.round to round the number of calculated miles per hour(double). The method round returns long. 36 | 37 | 38 | How to use the method round and how it works? 39 | 40 | The Math.round() is a built-in math method which returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result after adding 1/2, and typecasting the result to type long. The method returns the value of the argument rounded to the nearest int value. 41 | 42 | USAGE EXAMPLE: 43 | 44 | double number = 1.5; 45 | long rounded = Math.round(number); 46 | System.out.println("rounded= " + rounded); 47 | System.out.println("with 3.9= " + Math.round(3.9)); 48 | System.out.println("with 4.5= " + Math.round(4.5)); 49 | int sum = 45; 50 | int count = 10; 51 | // typecasting so result is double e.g. double / int -> double 52 | double average = (double) sum / count; 53 | long roundedAverage = Math.round(average); 54 | System.out.println("average= " + average); 55 | System.out.println("roundedAverage= " + roundedAverage); 56 | 57 | 58 | OUTPUT: 59 | 60 | rounded= 2 61 | with 3.9= 4 62 | with 4.5= 5 63 | average= 4.5 64 | roundedAverage= 5 65 | 66 | 67 | 68 | TIP: In the method printConversion, call the method toMilesPerHour instead of duplicating the code. 69 | 70 | NOTE: All methods should be defined as public static like we have been doing so far in the course. 71 | 72 | NOTE: 1 mile per hour is 1.609 kilometers per hour 73 | 74 | NOTE: Do not add a main method to the solution code. -------------------------------------------------------------------------------- /Coding Exercises 01 - Speed Converter/SpeedConverter.java: -------------------------------------------------------------------------------- 1 | public class SpeedConverter { 2 | // write your code here 3 | public static long toMilesPerHour(double kilometersPerHour){ 4 | if (kilometersPerHour < 0){ 5 | return -1; 6 | }else{ 7 | double con = (kilometersPerHour / 1.60934) ; 8 | // System.out.println(""+con); 9 | return (Math.round(con)); 10 | } 11 | } 12 | public static void printConversion(double kilometersPerHour){ 13 | double con = (kilometersPerHour / 1.609) ; 14 | if (kilometersPerHour < 0){ 15 | System.out.println("Invalid Value"); 16 | }else{ 17 | System.out.println(""+kilometersPerHour+" km/h = "+Math.round(con)+" mi/h"); 18 | 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /Coding Exercises 02 - MegaBytes Converter/Exercise Description.txt: -------------------------------------------------------------------------------- 1 | Write a method called printMegaBytesAndKiloBytes that has 1 parameter of type int with the name kiloBytes. 2 | 3 | The method should not return anything (void) and it needs to calculate the megabytes and remaining kilobytes from the kilobytes parameter. 4 | 5 | Then it needs to print a message in the format "XX KB = YY MB and ZZ KB". 6 | 7 | XX represents the original value kiloBytes. 8 | YY represents the calculated megabytes. 9 | ZZ represents the calculated remaining kilobytes. 10 | 11 | For example, when the parameter kiloBytes is 2500 it needs to print "2500 KB = 2 MB and 452 KB" 12 | 13 | If the parameter kiloBytes is less than 0 then print the text "Invalid Value". 14 | 15 | 16 | EXAMPLE INPUT/OUTPUT 17 | 18 | * printMegaBytesAndKiloBytes(2500); → should print the following text: "2500 KB = 2 MB and 452 KB" 19 | 20 | * printMegaBytesAndKiloBytes(-1024); → should print the following text: "Invalid Value" because parameter is less than 0. 21 | 22 | * printMegaBytesAndKiloBytes(5000); → should print the following text: "5000 KB = 4 MB and 904 KB" 23 | 24 | 25 | TIP: Be extremely careful about spaces in the printed message. 26 | 27 | TIP: Use the remainder operator 28 | 29 | TIP: 1 MB = 1024 KB 30 | 31 | NOTE: Do not set kilobytes parameter value inside your method. 32 | 33 | NOTE: The solution will not be accepted if there are extra spaces. 34 | NOTE: The printMegaBytesAndKiloBytes method needs to be defined as public static like we have been doing so far in the course.NOTE: Do not add a main method to solution code. -------------------------------------------------------------------------------- /Coding Exercises 02 - MegaBytes Converter/MegaBytesConverter.java: -------------------------------------------------------------------------------- 1 | public class MegaBytesConverter { 2 | public static void printMegaBytesAndKiloBytes(int kiloBytes){ 3 | if(kiloBytes < 0){ 4 | System.out.println("Invalid Value"); 5 | }else{ 6 | int mega = kiloBytes/1024; 7 | // double mega2 = (double)kiloBytes/1024; 8 | // // System.out.println(""+mega2); 9 | // mega2 = Math.round((mega2 - mega)*1000); 10 | int rnd = kiloBytes % 1024; 11 | System.out.println(""+kiloBytes +" KB = "+mega+" MB and "+rnd+" KB"); 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /Coding Exercises 03 - Barking Dog/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 | }else{ 6 | if(hourOfDay<8 || hourOfDay>22){ 7 | return barking; 8 | }else{ 9 | return false; 10 | } 11 | } 12 | } 13 | } -------------------------------------------------------------------------------- /Coding Exercises 03 - Barking Dog/Exercise Description.txt: -------------------------------------------------------------------------------- 1 | We have a dog that likes to bark. We need to wake up if the dog is barking at night! 2 | 3 | Write a method shouldWakeUp that has 2 parameters. 4 | 5 | 1st parameter should be of type boolean and be named barking it represents if our dog is currently barking. 6 | 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. 7 | 8 | We have to wake up if the dog is barking before 8 or after 22 hours so in that case return true. 9 | 10 | In all other cases return false. 11 | 12 | If the hourOfDay parameter is less than 0 or greater than 23 return false. 13 | 14 | Examples of input/output: 15 | 16 | * shouldWakeUp (true, 1); → should return true 17 | 18 | * shouldWakeUp (false, 2); → should return false since the dog is not barking. 19 | 20 | * shouldWakeUp (true, 8); → should return false, since it's not before 8. 21 | 22 | * shouldWakeUp (true, -1); → should return false since the hourOfDay parameter needs to be in a range 0-23. 23 | 24 | 25 | TIP: Use the if else statement with multiple conditions. 26 | 27 | NOTE: The shouldWakeUp method needs to be defined as public static like we have been doing so far in the course. 28 | 29 | NOTE: Do not add a main method to solution code. -------------------------------------------------------------------------------- /Coding Exercises 04 - Leap Year Calculator/Exercise Description.txt: -------------------------------------------------------------------------------- 1 | Write a method isLeapYear with a parameter of type int named year. 2 | 3 | The parameter needs to be greater than or equal to 1 and less than or equal to 9999. 4 | 5 | If the parameter is not in that range return false. 6 | 7 | Otherwise, if it is in the valid range, calculate if the year is a leap year and return true if it is a leap year, otherwise return false. 8 | 9 | 10 | To determine whether a year is a leap year, follow these steps: 11 | 1. If the year is evenly divisible by 4, go to step 12 | 2. Otherwise, go to step 5.2. If the year is evenly divisible by 100, go to step 13 | 3. Otherwise, go to step 4.3. If the year is evenly divisible by 400, go to step 14 | 4. Otherwise, go to step 5.4. The year is a leap year (it has 366 days). The method isLeapYear needs to return true. 15 | 5. The year is not a leap year (it has 365 days). The method isLeapYear needs to return false. 16 | 17 | The following years are not leap years: 18 | 1700, 1800, 1900, 2100, 2200, 2300, 2500, 2600 19 | This is because they are evenly divisible by 100 but not by 400. 20 | 21 | The following years are leap years: 22 | 1600, 2000, 2400 23 | This is because they are evenly divisible by both 100 and 400. 24 | 25 | Examples of input/output: 26 | 27 | * isLeapYear(-1600); → should return false since the parameter is not in range (1-9999) 28 | 29 | * isLeapYear(1600); → should return true since 1600 is a leap year 30 | 31 | * isLeapYear(2017); → should return false since 2017 is not a leap year 32 | 33 | * isLeapYear(2000); → should return true because 2000 is a leap year 34 | 35 | NOTE: The method isLeapYear needs to be defined as public static like we have been doing so far in the course. 36 | NOTE: Do not add a main method to solution code. -------------------------------------------------------------------------------- /Coding Exercises 04 - Leap Year Calculator/LeapYear.java: -------------------------------------------------------------------------------- 1 | public class LeapYear { 2 | public static boolean isLeapYear(int year){ 3 | if(year>=1 && year<=9999){ 4 | if(year%4==0){ 5 | if(year%100==0){ 6 | if(year%400==0){ 7 | return true; 8 | }else{ 9 | return false; 10 | } 11 | }else{ 12 | return true; 13 | } 14 | }else{ 15 | return false; 16 | } 17 | }else{ 18 | return false; 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /Coding Exercises 05 - Decimal Comparator/DecimalComparator.java: -------------------------------------------------------------------------------- 1 | public class DecimalComparator{ 2 | public static boolean areEqualByThreeDecimalPlaces(double d1,double d2){ 3 | d1 = d1*1000; 4 | d2 = d2*1000; 5 | int i1 = (int)d1; 6 | int i2 = (int)d2; 7 | if(i1 == i2){ 8 | return true; 9 | }else{ 10 | return false; 11 | } 12 | } 13 | } -------------------------------------------------------------------------------- /Coding Exercises 05 - Decimal Comparator/Exercise Description.txt: -------------------------------------------------------------------------------- 1 | Write a method areEqualByThreeDecimalPlaces with two parameters of type double. 2 | 3 | The method should return boolean and it needs to return true if two double numbers are the same up to three decimal places. Otherwise, return false. 4 | 5 | 6 | EXAMPLES OF INPUT/OUTPUT: 7 | 8 | * areEqualByThreeDecimalPlaces(-3.1756, -3.175); → should return true since numbers are equal up to 3 decimal places. 9 | 10 | * areEqualByThreeDecimalPlaces(3.175, 3.176); → should return false since numbers are not equal up to 3 decimal places 11 | 12 | * areEqualByThreeDecimalPlaces(3.0, 3.0); → should return true since numbers are equal up to 3 decimal places. 13 | 14 | * areEqualByThreeDecimalPlaces(-3.123, 3.123); → should return false since numbers are not equal up to 3 decimal places. 15 | 16 | 17 | TIP: Use paper and pencil. 18 | 19 | TIP: Use casting. 20 | 21 | NOTE: The areEqualByThreeDecimalPlaces method needs to be defined as public static like we have been doing so far in the course. 22 | NOTE: Do not add a main method to solution code. -------------------------------------------------------------------------------- /Coding Exercises 06 - Equal Sum Checker/EqualSumChecker.java: -------------------------------------------------------------------------------- 1 | public class EqualSumChecker { 2 | public static boolean hasEqualSum(int i1,int i2,int i3){ 3 | if((i1+i2) == i3){ 4 | return true; 5 | }else{ 6 | return false; 7 | } 8 | } 9 | } -------------------------------------------------------------------------------- /Coding Exercises 06 - Equal Sum Checker/Exercise Description.txt: -------------------------------------------------------------------------------- 1 | Write a method hasEqualSum with 3 parameters of type int. 2 | 3 | The method should return boolean and it needs to return true if the sum of the first and second parameter is equal to the third parameter. Otherwise, return false. 4 | 5 | 6 | EXAMPLES OF INPUT/OUTPUT: 7 | 8 | * hasEqualSum(1, 1, 1); should return false since 1 + 1 is not equal to 1 9 | 10 | * hasEqualSum(1, 1, 2); should return true since 1 + 1 is equal to 2 11 | 12 | * hasEqualSum(1, -1, 0); should return true since 1 + (-1) is 1 - 1 and is equal to 0 13 | 14 | 15 | NOTE: The hasEqualSum method needs to be defined as public static like we have been doing so far in the course. 16 | NOTE: Do not add a main method to solution code. -------------------------------------------------------------------------------- /Coding Exercises 07 - Teen Number Checker/Exercise Description.txt: -------------------------------------------------------------------------------- 1 | We'll say that a number is "teen" if it is in the range 13 -19 (inclusive). 2 | 3 | Write a method named hasTeen with 3 parameters of type int. 4 | 5 | The method should return boolean and it needs to return true if one of the parameters is in range 13(inclusive) - 19 (inclusive). Otherwise return false. 6 | 7 | 8 | EXAMPLES OF INPUT/OUTPUT: 9 | 10 | * hasTeen(9, 99, 19); should return true since 19 is in range 13 - 19 11 | 12 | * hasTeen(23, 15, 42); should return true since 15 is in range 13 - 19 13 | 14 | * hasTeen(22, 23, 34); should return false since numbers 22, 23, 34 are not in range 13-19 15 | 16 | 17 | Write another method named isTeen with 1 parameter of type int. 18 | 19 | The method should return boolean and it needs to return true if the parameter is in range 13(inclusive) - 19 (inclusive). Otherwise return false. 20 | 21 | EXAMPLES OF INPUT/OUTPUT: 22 | 23 | * isTeen(9); should return false since 9 is in not range 13 - 19 24 | 25 | * isTeen(13); should return true since 13 is in range 13 - 19 26 | 27 | NOTE: All methods need to be defined as public static like we have been doing so far in the course. 28 | NOTE: Do not add a main method to solution code. -------------------------------------------------------------------------------- /Coding Exercises 07 - Teen Number Checker/TeenNumberChecker.java: -------------------------------------------------------------------------------- 1 | public class TeenNumberChecker { 2 | public static boolean hasTeen(int i1,int i2,int i3){ 3 | if((i1<=19 && i1>=13) || (i2<=19 && i2>=13) || (i3<=19 && i3>=13)){ 4 | return true; 5 | }else{ 6 | return false; 7 | } 8 | } 9 | public static boolean isTeen(int i4){ 10 | if(i4<=19 && i4>=13){ 11 | return true; 12 | }else{ 13 | return false; 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /Coding Exercises 08 - Area Calculator/AreaCalculator.java: -------------------------------------------------------------------------------- 1 | public class AreaCalculator { 2 | public static double area(double radius){ 3 | if(radius<0){ 4 | return -1.0; 5 | }else{ 6 | return radius*radius*Math.PI; 7 | } 8 | } 9 | public static double area(double x,double y){ 10 | if(x<0 || y<0){ 11 | return -1.0; 12 | }else{ 13 | return x*y; 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /Coding Exercises 08 - Area Calculator/Exercise Description.txt: -------------------------------------------------------------------------------- 1 | Write a method named area with one double parameter named radius. 2 | 3 | The method needs to return a double value that represents the area of a circle. 4 | 5 | If the parameter radius is negative then return -1.0 to represent an invalid value. 6 | 7 | Write another overloaded method with 2 parameters x and y (both doubles), where x and y represent the sides of a rectangle. 8 | 9 | The method needs to return an area of a rectangle. 10 | 11 | If either or both parameters is/are a negative return -1.0 to indicate an invalid value. 12 | 13 | For formulas and PI value please check the tips below. 14 | 15 | Examples of input/output: 16 | 17 | * area(5.0); should return 78.53975 18 | 19 | * area(-1); should return -1 since the parameter is negative 20 | 21 | * area(5.0, 4.0); should return 20.0 (5 * 4 = 20) 22 | 23 | * area(-1.0, 4.0); should return -1 since first the parameter is negative 24 | 25 | 26 | 27 | TIP: The formula for calculating the area of a rectangle is x * y. 28 | 29 | TIP: The formula for calculating a circle area is radius * radius * PI. 30 | 31 | TIP: For PI use a constant from Math class e.g. Math.PI 32 | 33 | NOTE: All methods need to be defined as public static like we have been doing so far in the course. 34 | 35 | NOTE: Do not add a main method to your solution code! -------------------------------------------------------------------------------- /Coding Exercises 09 - Minutes to Years and Days Calculator/Exercise Description.txt: -------------------------------------------------------------------------------- 1 | Write a method printYearsAndDays with parameter of type long named minutes. 2 | 3 | The method should not return anything (void) and it needs to calculate the years and days from the minutes parameter. 4 | 5 | If the parameter is less than 0, print text "Invalid Value". 6 | 7 | Otherwise, if the parameter is valid then it needs to print a message in the format "XX min = YY y and ZZ d". 8 | 9 | XX represents the original value minutes. 10 | YY represents the calculated years. 11 | ZZ represents the calculated days. 12 | 13 | 14 | EXAMPLES OF INPUT/OUTPUT: 15 | 16 | * printYearsAndDays(525600); → should print "525600 min = 1 y and 0 d" 17 | 18 | * printYearsAndDays(1051200); → should print "1051200 min = 2 y and 0 d" 19 | 20 | * printYearsAndDays(561600); → should print "561600 min = 1 y and 25 d" 21 | 22 | 23 | TIPS: 24 | 25 | * Be extra careful about spaces in the printed message. 26 | 27 | * Use the remainder operator 28 | 29 | * 1 hour = 60 minutes 30 | 31 | * 1 day = 24 hours 32 | 33 | * 1 year = 365 days 34 | 35 | NOTES 36 | 37 | * The printYearsAndDays method needs to be defined as public static like we have been doing so far in the course. 38 | 39 | * Do not add main method to solution code. 40 | 41 | * The solution will not be accepted if there are extra spaces -------------------------------------------------------------------------------- /Coding Exercises 09 - Minutes to Years and Days Calculator/MinutesToYearsDaysCalculator.java: -------------------------------------------------------------------------------- 1 | public class MinutesToYearsDaysCalculator { 2 | // write your code here 3 | public static void printYearsAndDays(long minutes){ 4 | if(minutes<0){ 5 | System.out.println("Invalid Value"); 6 | }else{ 7 | long YY = minutes/(60*24*365); 8 | long DD = minutes%(60*24*365); 9 | long ZZ = DD/(60*24); 10 | System.out.println(""+minutes+" min = "+YY+" y and "+ZZ+" d"); 11 | } 12 | } 13 | } -------------------------------------------------------------------------------- /Coding Exercises 10 - Equality Printer/Exercise Description.txt: -------------------------------------------------------------------------------- 1 | Write a method printEqual with 3 parameters of type int. The method should not return anything (void). 2 | 3 | If one of the parameters is less than 0, print text "Invalid Value". 4 | 5 | If all numbers are equal print text "All numbers are equal" 6 | 7 | If all numbers are different print text "All numbers are different". 8 | 9 | Otherwise, print "Neither all are equal or different". 10 | 11 | 12 | EXAMPLES OF INPUT/OUTPUT: 13 | 14 | * printEqual(1, 1, 1); should print text All numbers are equal 15 | 16 | * printEqual(1, 1, 2); should print text Neither all are equal or different 17 | 18 | * printEqual(-1, -1, -1); should print text Invalid Value 19 | 20 | * printEqual(1, 2, 3); should print text All numbers are different 21 | 22 | 23 | TIP: Be extremely careful about spaces in the printed message. 24 | 25 | 26 | NOTES 27 | 28 | * The solution will not be accepted if there are extra spaces. 29 | 30 | * The method printEqual needs to be defined as public static like we have been doing so far in the course. 31 | 32 | * Do not add main method to solution code. -------------------------------------------------------------------------------- /Coding Exercises 10 - Equality Printer/IntEqualityPrinte.java: -------------------------------------------------------------------------------- 1 | public class IntEqualityPrinter { 2 | // write your code here 3 | public static void printEqual(int i1,int i2,int i3){ 4 | if(i1<0 || i2<0 || i3<0){ 5 | System.out.println("Invalid Value"); 6 | }else{ 7 | if(i1==i2 && i2==i3){ 8 | System.out.println("All numbers are equal"); 9 | }else{ 10 | if((i1 != i2) && (i1 != i3) && (i2 != i3)){ 11 | System.out.println("All numbers are different"); 12 | }else{ 13 | System.out.println("Neither all are equal or different"); 14 | } 15 | } 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Coding Exercises 11 - Playing Cat/Exercise Description.txt: -------------------------------------------------------------------------------- 1 | The cats spend most of the day playing. In particular, they play if the temperature is between 25 and 35 (inclusive). Unless it is summer, then the upper limit is 45 (inclusive) instead of 35. 2 | 3 | 4 | Write a method isCatPlaying that has 2 parameters. Method needs to return true if the cat is playing, otherwise return false 5 | 6 | 1st parameter should be of type boolean and be named summer it represents if it is summer. 7 | 2nd parameter represents the temperature and is of type int with the name temperature. 8 | 9 | 10 | EXAMPLES OF INPUT/OUTPUT: 11 | 12 | * isCatPlaying(true, 10); should return false since temperature is not in range 25 - 45 13 | 14 | * isCatPlaying(false, 36); should return false since temperature is not in range 25 - 35 (summer parameter is false) 15 | 16 | * isCatPlaying(false, 35); should return true since temperature is in range 25 - 35 17 | 18 | 19 | NOTES 20 | 21 | * The isCatPlaying method needs to be defined as public static like we have been doing so far in the course. 22 | 23 | * Do not add the main method to the solution code. -------------------------------------------------------------------------------- /Coding Exercises 11 - Playing Cat/PlayingCat.java: -------------------------------------------------------------------------------- 1 | public class PlayingCat { 2 | // write your code here 3 | public static boolean isCatPlaying(boolean summer,int temperature){ 4 | if(summer == true){ 5 | if(temperature >=25 && temperature<=45){ 6 | return true; 7 | }else{ 8 | return false; 9 | } 10 | }else{ 11 | if(temperature >=25 && temperature<=35){ 12 | return true; 13 | }else{ 14 | return false; 15 | } 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Coding Exercises 12 - Number In Word/Exercise Description.txt: -------------------------------------------------------------------------------- 1 | Write a method called printNumberInWord. The method has one parameter number which is the whole number. The method needs to print "ZERO", "ONE", "TWO", ... "NINE", "OTHER" if the int parameter number is 0, 1, 2, .... 9 or other for any other number including negative numbers. You can use if-else statement or switch statement whatever is easier for you. 2 | 3 | 4 | NOTE: Method printNumberInWord needs to be public static for now, we are only using static methods. 5 | 6 | NOTE: Do not add main method to solution code. -------------------------------------------------------------------------------- /Coding Exercises 12 - Number In Word/NumberInWord.java: -------------------------------------------------------------------------------- 1 | public class NumberInWord { 2 | // write your code here 3 | public static void printNumberInWord(int num){ 4 | int nm; 5 | 6 | // while(num !=0){ 7 | // nm = num%10; 8 | // num = num/10; 9 | switch(num){ 10 | case 0: 11 | System.out.print("ZERO"); 12 | break; 13 | case 1: 14 | System.out.print("ONE"); 15 | break; 16 | case 2: 17 | System.out.print("TWO"); 18 | break; 19 | case 3: 20 | System.out.print("THREE"); 21 | break; 22 | case 4: 23 | System.out.print("FOUR"); 24 | break; 25 | case 5: 26 | System.out.print("FIVE"); 27 | break; 28 | case 6: 29 | System.out.print("SIX"); 30 | break; 31 | case 7: 32 | System.out.print("SEVEN"); 33 | break; 34 | case 8: 35 | System.out.print("EIGHT"); 36 | break; 37 | case 9: 38 | System.out.print("NINE"); 39 | break; 40 | default: 41 | System.out.print("OTHER"); 42 | 43 | } 44 | } 45 | // } 46 | } -------------------------------------------------------------------------------- /Coding Exercises 13 - Number Of Days In Month/Exercise Description.txt: -------------------------------------------------------------------------------- 1 | Write a method isLeapYear with a parameter of type int named year. 2 | 3 | The parameter needs to be greater than or equal to 1 and less than or equal to 9999. 4 | 5 | If the parameter is not in that range return false. 6 | 7 | Otherwise, if it is in the valid range, calculate if the year is a leap year and return true if it is, otherwise return false. 8 | 9 | A year is a leap year if it is divisible by 4 but not by 100, or it is divisible by 400. 10 | 11 | Examples of input/output: 12 | 13 | * isLeapYear(-1600); → should return false since the parameter is not in the range (1-9999) 14 | 15 | * isLeapYear(1600); → should return true since 1600 is a leap year 16 | 17 | * isLeapYear(2017); → should return false since 2017 is not a leap year 18 | 19 | * isLeapYear(2000); → should return true because 2000 is a leap year 20 | 21 | ​NOTE: The solution to the Leap Year coding exercise earlier in the course created the isLeapYear method. You can use that solution if you wish. 22 | 23 | Write another method getDaysInMonth with two parameters month and year. ​Both of type int. 24 | 25 | If parameter month is < 1 or > 12 return -1. ​ 26 | If parameter year is < 1 or > 9999 then return -1. 27 | 28 | This method needs to return the number of days in the month. Be careful about leap years they have 29 days in month 2 (February). 29 | 30 | You should check if the year is a leap year using the method isLeapYear described above. 31 | 32 | Examples of input/output: 33 | 34 | * getDaysInMonth(1, 2020); → should return 31 since January has 31 days. 35 | 36 | * getDaysInMonth(2, 2020); → should return 29 since February has 29 days in a leap year and 2020 is a leap year. 37 | 38 | * getDaysInMonth(2, 2018); → should return 28 since February has 28 days if it's not a leap year and 2018 is not a leap year. 39 | 40 | * getDaysInMonth(-1, 2020); → should return -1 since the parameter month is invalid. 41 | 42 | * getDaysInMonth(1, -2020); → should return -1 since the parameter year is outside the range of 1 to 9999. 43 | 44 | 45 | HINT: Use the switch statement. 46 | 47 | NOTE: Methods isLeapYear and getDaysInMonth need to be public static like we have been doing so far in the course. 48 | 49 | NOTE: Do not add a main method to solution code. -------------------------------------------------------------------------------- /Coding Exercises 13 - Number Of Days In Month/NumberOfDaysInMonth.java: -------------------------------------------------------------------------------- 1 | public class NumberOfDaysInMonth { 2 | // write your code here 3 | public static boolean isLeapYear(int year){ 4 | if(year >=1 && year<=9999){ 5 | if(year%400 == 0){ 6 | return true; 7 | } 8 | if(year%4 ==0){ 9 | if(year%100 == 0){ 10 | return false; 11 | }else{ 12 | return true; 13 | } 14 | } 15 | 16 | } 17 | return false; 18 | 19 | } 20 | public static int getDaysInMonth(int month,int year){ 21 | if((month>=1 && month<=12) && (year>=1 && year<=9999)){ 22 | switch(month){ 23 | case 1: 24 | return 31; 25 | case 2: 26 | if(isLeapYear(year)){ 27 | return 29; 28 | }else{ 29 | return 28; 30 | } 31 | case 3: 32 | return 31; 33 | case 4: 34 | return 30; 35 | case 5: 36 | return 31; 37 | case 6: 38 | return 30; 39 | case 7: 40 | return 31; 41 | case 8: 42 | return 31; 43 | case 9: 44 | return 30; 45 | case 10: 46 | return 31; 47 | case 11: 48 | return 30; 49 | case 12: 50 | return 31; 51 | } 52 | } 53 | return -1; 54 | } 55 | } -------------------------------------------------------------------------------- /Coding Exercises 14 - Sum Odd/Exercise Description.txt: -------------------------------------------------------------------------------- 1 | The cats spend most of the day playing. In particular, they play if the temperature is between 25 and 35 (inclusive). Unless it is summer, then the upper limit is 45 (inclusive) instead of 35. 2 | 3 | 4 | Write a method isCatPlaying that has 2 parameters. Method needs to return true if the cat is playing, otherwise return false 5 | 6 | 1st parameter should be of type boolean and be named summer it represents if it is summer. 7 | 2nd parameter represents the temperature and is of type int with the name temperature. 8 | 9 | 10 | EXAMPLES OF INPUT/OUTPUT: 11 | 12 | * isCatPlaying(true, 10); should return false since temperature is not in range 25 - 45 13 | 14 | * isCatPlaying(false, 36); should return false since temperature is not in range 25 - 35 (summer parameter is false) 15 | 16 | * isCatPlaying(false, 35); should return true since temperature is in range 25 - 35 17 | 18 | 19 | NOTES 20 | 21 | * The isCatPlaying method needs to be defined as public static like we have been doing so far in the course. 22 | 23 | * Do not add the main method to the solution code. -------------------------------------------------------------------------------- /Coding Exercises 14 - Sum Odd/SumOddRange.java: -------------------------------------------------------------------------------- 1 | public class SumOddRange { 2 | public static boolean isOdd(int number){ 3 | if(number>0 && number%2 != 0){ 4 | return true; 5 | } 6 | return false; 7 | } 8 | public static int sumOdd(int start,int end){ 9 | int sim=0; 10 | if(start>0 && end>0 && end>=start){ 11 | for(int i=start;i<=end;i++){ 12 | if(isOdd(i)){ 13 | sim = sim+i; 14 | } 15 | } 16 | return sim; 17 | } 18 | return -1; 19 | } 20 | } -------------------------------------------------------------------------------- /Coding Exercises 15 - Number Palindrome/Exercise Description.txt: -------------------------------------------------------------------------------- 1 | Write a method called isPalindrome with one int parameter called number. 2 | 3 | The method needs to return a boolean. 4 | 5 | It should return true if the number is a palindrome number otherwise it should return false. 6 | 7 | Check the tips below for more info about palindromes. 8 | 9 | Example Input/Output 10 | 11 | isPalindrome(-1221); → should return true 12 | 13 | isPalindrome(707); → should return true 14 | 15 | isPalindrome(11212); → should return false because reverse is 21211 and that is not equal to 11212. 16 | 17 | Tip: What is a Palindrome number? A palindrome number is a number which when reversed is equal to the original number. For example: 121, 12321, 1001 etc. 18 | 19 | Tip: Logic to check a palindrome number 20 | 21 | Find the the reverse of the given number. Store it in some variable say reverse. Compare the number with reverse. 22 | 23 | If both are the the same then the number is a palindrome otherwise it is not. 24 | 25 | Tip: Logic to reverse a number 26 | 27 | Declare and initialize another variable to store the reverse of a number, for example reverse = 0. 28 | 29 | Extract the last digit of the given number by performing the modulo division (remainder). 30 | Store the last digit to some variable say lastDigit = num % 10. 31 | Increase the place value of reverse by one. 32 | To increase place value multiply the reverse variable by 10 e.g. reverse = reverse * 10. 33 | Add lastDigit to reverse. 34 | Since the last digit of the number is processed, remove the last digit of num. To remove the last digit divide number by 10. 35 | Repeat steps until number is not equal to (or greater than) zero. 36 | 37 | A while loop would be good for this coding exercise. 38 | 39 | 40 | Tip: Be careful with negative numbers. They can also be palindrome numbers. 41 | 42 | Tip: Be careful with reversing a number, you will need a parameter for comparing a reversed number with the starting number (parameter). 43 | 44 | NOTE: The method isPalindrome needs to be defined as public static like we have been doing -------------------------------------------------------------------------------- /Coding Exercises 15 - Number Palindrome/NumberPalindrome.java: -------------------------------------------------------------------------------- 1 | public class NumberPalindrome { 2 | public static boolean isPalindrome(int number){ 3 | int rev=0,temp; 4 | if(number<0){ 5 | temp = number; 6 | rev = 0; 7 | while(temp !=0){ 8 | rev = (rev*10)+(temp%10); 9 | temp = temp/10; 10 | } 11 | }else{ 12 | number = number*(-1); 13 | temp = number; 14 | rev =0; 15 | while(temp !=0){ 16 | rev = (rev*10)+(temp%10); 17 | temp = temp/10; 18 | } 19 | } 20 | if(rev == number){ 21 | return true; 22 | } 23 | return false; 24 | } 25 | } -------------------------------------------------------------------------------- /Coding Exercises 16 - First And Last Digit Sum/Exercise Description.txt: -------------------------------------------------------------------------------- 1 | Write a method named sumFirstAndLastDigit with one parameter of type int called number. 2 | 3 | The method needs to find the first and the last digit of the parameter number passed to the method, using a loop and return the sum of the first and the last digit of that number. 4 | 5 | If the number is negative then the method needs to return -1 to indicate an invalid value. 6 | 7 | Example input/output 8 | 9 | * 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. 10 | 11 | * 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. 12 | 13 | * sumFirstAndLastDigit(0); → should return 0, the first digit and the last digit is 0 since we only have 1 digit, which gives us 0+0 and the sum is 0. 14 | 15 | * sumFirstAndLastDigit(5); → should return 10, the first digit and the last digit is 5 since we only have 1 digit, which gives us 5+5 and the sum is 10. 16 | 17 | * sumFirstAndLastDigit(-10); → should return -1, since the parameter is negative and needs to be positive. 18 | 19 | 20 | NOTE: The method sumFirstAndLastDigit needs to be defined as public static like we have been doing so far in the course. 21 | 22 | NOTE: Do not add a main method to solution code. -------------------------------------------------------------------------------- /Coding Exercises 16 - First And Last Digit Sum/FirstLastDigitSum.java: -------------------------------------------------------------------------------- 1 | import java.lang.Math; 2 | public class FirstLastDigitSum { 3 | // write your code here 4 | public static int sumFirstAndLastDigit(int number){ 5 | int sum=0; 6 | String digit = Integer.toString(number); 7 | int num = digit.length(); 8 | num = (int)Math.pow(10,num-1); 9 | System.out.println(""+num); 10 | if(number>=0){ 11 | sum = sum+(number%10); 12 | sum = sum+(number/num); 13 | return sum; 14 | } 15 | return -1; 16 | } 17 | } -------------------------------------------------------------------------------- /Coding Exercises 17 - Even Digit Sum/EvenDigitSum.java: -------------------------------------------------------------------------------- 1 | public class EvenDigitSum { 2 | // write your code here 3 | public static int getEvenDigitSum(int number){ 4 | int sum=0; 5 | String digit = Integer.toString(number); 6 | int num = digit.length(); 7 | num = (int)Math.pow(10,num-1); 8 | System.out.println(""+num); 9 | if(number>=0){ 10 | // number = number/10; 11 | while(number !=0){ 12 | if((number%10)%2==0){ 13 | sum = sum+ number%10; 14 | } 15 | number = number/10; 16 | } 17 | return sum; 18 | } 19 | return -1; 20 | } 21 | } -------------------------------------------------------------------------------- /Coding Exercises 17 - Even Digit Sum/Exercise Description.txt: -------------------------------------------------------------------------------- 1 | Write a method named getEvenDigitSum with one parameter of type int called number. 2 | 3 | The method should return the sum of the even digits within the number. 4 | 5 | If the number is negative, the method should return -1 to indicate an invalid value. 6 | 7 | 8 | EXAMPLE INPUT/OUTPUT: 9 | 10 | * getEvenDigitSum(123456789); → should return 20 since 2 + 4 + 6 + 8 = 20 11 | 12 | * getEvenDigitSum(252); → should return 4 since 2 + 2 = 4 13 | 14 | * getEvenDigitSum(-22); → should return -1 since the number is negative 15 | 16 | 17 | NOTE: The method getEvenDigitSum should be defined as public static like we have been doing so far in the course. 18 | 19 | NOTE: Do not add a main method to the solution code. -------------------------------------------------------------------------------- /Coding Exercises 18 - Shared Digit/Exercise Description.txt: -------------------------------------------------------------------------------- 1 | Write a method named hasSharedDigit with two parameters of type int. 2 | 3 | Each number should be within the range of 10 (inclusive) - 99 (inclusive). If one of the numbers is not within the range, the method should return false. 4 | 5 | The method should return true if there is a digit that appears in both numbers, such as 2 in 12 and 23; otherwise, the method should return false. 6 | 7 | 8 | EXAMPLE INPUT/OUTPUT: 9 | 10 | * hasSharedDigit(12, 23); → should return true since the digit 2 appears in both numbers 11 | 12 | * hasSharedDigit(9, 99); → should return false since 9 is not within the range of 10-99 13 | 14 | * hasSharedDigit(15, 55); → should return true since the digit 5 appears in both numbers 15 | 16 | 17 | NOTE: The method hasSharedDigit should be defined as public static like we have been doing so far in the course. 18 | 19 | NOTE: Do not add a main method to the solution code. -------------------------------------------------------------------------------- /Coding Exercises 18 - Shared Digit/SharedDigit.java: -------------------------------------------------------------------------------- 1 | public class SharedDigit { 2 | // write your code here 3 | public static boolean hasSharedDigit(int a, int b){ 4 | if(a<=(99) && a>=10 && b<=(99) && b>=10){ 5 | int lefta = a/10; 6 | int righta = a % 10; 7 | int leftb = b/10; 8 | int rightb = b % 10; 9 | if(lefta == leftb || lefta == rightb || righta == leftb || righta ==rightb){ 10 | return true; 11 | } 12 | } 13 | return false; 14 | } 15 | } -------------------------------------------------------------------------------- /Coding Exercises 19 - Last Digit Checker/Exercise Description.txt: -------------------------------------------------------------------------------- 1 | Write a method named hasSameLastDigit with three parameters of type int. 2 | 3 | Each number should be within the range of 10 (inclusive) - 1000 (inclusive). If one of the numbers is not within the range, the method should return false. 4 | 5 | The method should return true if at least two of the numbers share the same rightmost digit; otherwise, it should return false. 6 | 7 | 8 | EXAMPLE INPUT/OUTPUT: 9 | 10 | * hasSameLastDigit (41, 22, 71); → should return true since 1 is the rightmost digit in numbers 41 and 71 11 | 12 | * hasSameLastDigit (23, 32, 42); → should return true since 2 is the rightmost digit in numbers 32 and 42 13 | 14 | * hasSameLastDigit (9, 99, 999); → should return false since 9 is not within the range of 10-1000 15 | 16 | 17 | Write another method named isValid with one parameter of type int. 18 | 19 | The method needs to return true if the number parameter is in range of 10(inclusive) - 1000(inclusive), otherwise return false. 20 | 21 | EXAMPLE INPUT/OUTPUT 22 | 23 | * isValid(10); → should return true since 10 is within the range of 10-1000 24 | 25 | * isValid(468); → should return true since 468 is within the range of 10-1000 26 | 27 | * isValid(1051); → should return false since 1051 is not within the range of 10-1000 28 | 29 | 30 | NOTE: All methods need to be defined as public static as we have been doing so far in the course. 31 | 32 | NOTE: Do not add a main method to the solution code. -------------------------------------------------------------------------------- /Coding Exercises 19 - Last Digit Checker/LastDigitChecker.java: -------------------------------------------------------------------------------- 1 | public class LastDigitChecker { 2 | // write your code here 3 | public static boolean hasSameLastDigit(int x,int y,int z){ 4 | if(x>=10 && x<=1000 && y>=10 && y<=1000 && z>=10 && z<=1000 ){ 5 | x = x%10; 6 | y = y%10; 7 | z = z%10; 8 | if(x==y || x==z || y==z){ 9 | return true; 10 | } 11 | } 12 | return false; 13 | } 14 | public static boolean isValid(int n){ 15 | if(n>=10 && n<=1000){ 16 | return true; 17 | } 18 | return false; 19 | } 20 | } -------------------------------------------------------------------------------- /Coding Exercises 20 - Greatest Common Divisor/Exercise Description.txt: -------------------------------------------------------------------------------- 1 | Write a method named getGreatestCommonDivisor with two parameters of type int named first and second. 2 | 3 | If one of the parameters is < 10, the method should return -1 to indicate an invalid value. 4 | 5 | The method should return the greatest common divisor of the two numbers (int). 6 | 7 | The greatest common divisor is the largest positive integer that can fully divide each of the integers (i.e. without leaving a remainder). 8 | 9 | 10 | For example 12 and 30: 11 | 12 | 12 can be divided by 1, 2, 3, 4, 6, 12 13 | 14 | 30 can be divided by 1, 2, 3, 5, 6, 10, 15, 30 15 | 16 | The greatest common divisor is 6 since both 12 and 30 can be divided by 6, and there is no resulting remainder. 17 | 18 | 19 | EXAMPLE INPUT/OUTPUT: 20 | 21 | * getGreatestCommonDivisor(25, 15); should return 5 since both can be divided by 5 without a remainder 22 | 23 | * getGreatestCommonDivisor(12, 30); should return 6 since both can be divided by 6 without a remainder 24 | 25 | * getGreatestCommonDivisor(9, 18); should return -1 since the first parameter is < 10 26 | 27 | * getGreatestCommonDivisor(81, 153); should return 9 since both can be divided by 9 without a remainder 28 | 29 | 30 | HINT: Use a while or a for loop and check if both numbers can be divided without a remainder. 31 | 32 | HINT: Find the minimum of the two numbers. 33 | 34 | 35 | NOTE: The method getGreatestCommonDivisor should be defined as public static like we have been doing so far in the course. 36 | 37 | NOTE: Do not add a main method to the solution code. -------------------------------------------------------------------------------- /Coding Exercises 20 - Greatest Common Divisor/GreatestCommonDivisor.java: -------------------------------------------------------------------------------- 1 | public class GreatestCommonDivisor { 2 | // write your code here 3 | public static int getGreatestCommonDivisor(int first, int second){ 4 | int div,r; 5 | if(first>=10 && second>=10){ 6 | while(first != 0){ 7 | div = second/first; 8 | r = second%first; 9 | second = first; 10 | first = r; 11 | } 12 | return second; 13 | } 14 | return -1; 15 | } 16 | } -------------------------------------------------------------------------------- /Coding Exercises 21 - All Factors/Exercise Description.txt: -------------------------------------------------------------------------------- 1 | Write a method named printFactors with one parameter of type int named number. 2 | 3 | If number is < 1, the method should print "Invalid Value". 4 | 5 | The method should print all factors of the number. A factor of a number is an integer which divides that number wholly (i.e. without leaving a remainder). 6 | 7 | For example, 3 is a factor of 6 because 3 fully divides 6 without leaving a remainder. In other words 6 / 3 = 2. 8 | 9 | 10 | EXAMPLE INPUT/OUTPUT: 11 | 12 | * printFactors(6); → should print 1 2 3 6 13 | 14 | * printFactors(32); → should print 1 2 4 8 16 32 15 | 16 | * printFactors(10); → should print 1 2 5 10 17 | 18 | * printFactors(-1); → should print "Invalid Value" since number is < 1 19 | 20 | 21 | HINT: Use a while or for loop. 22 | 23 | 24 | NOTE: When printing numbers, each number can be in its own line. They don't have to be separated by a space. 25 | 26 | For example, the printout for printFactors(10); can be: 27 | 28 | 1 29 | 2 30 | 5 31 | 10 32 | 33 | NOTE: The method printFactors should be defined as public static like we have been doing so far in the course. 34 | 35 | NOTE: Do not add a main method to the solution code. -------------------------------------------------------------------------------- /Coding Exercises 21 - All Factors/FactorPrinter.java: -------------------------------------------------------------------------------- 1 | public class FactorPrinter { 2 | // write your code here 3 | public static void printFactors(int number){ 4 | if(number<1){ 5 | System.out.print("Invalid Value"); 6 | }else{ 7 | for(int i=1;i<=number;i++){ 8 | if(number%i == 0){ 9 | System.out.print(""+i+" "); 10 | } 11 | } 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /Coding Exercises 22 - Prefect Number/Exercise Description.txt: -------------------------------------------------------------------------------- 1 | What is the perfect number? 2 | A perfect number is a positive integer which is equal to the sum of its proper positive divisors. 3 | Proper positive divisors are positive integers that fully divide the perfect number without leaving a remainder and exclude the perfect number itself. 4 | For example, take the number 6: 5 | Its proper divisors are 1, 2, and 3 (since 6 is the value of the perfect number, it is excluded), and the sum of its proper divisors is 1 + 2 + 3 = 6. 6 | 7 | Therefore, 6 is a perfect number (as well as the first perfect number). 8 | 9 | 10 | Write a method named isPerfectNumber with one parameter of type int named number. 11 | 12 | If number is < 1, the method should return false. 13 | 14 | The method must calculate if the number is perfect. If the number is perfect, the method should return true; otherwise, it should return false. 15 | 16 | 17 | EXAMPLE INPUT/OUTPUT: 18 | 19 | * isPerfectNumber(6); should return true since its proper divisors are 1, 2, 3 and the sum is 1 + 2 + 3 = 6 20 | 21 | * 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 22 | 23 | * isPerfectNumber(5); should return false since its only proper divisor is 1 and the sum is 1 not 5 24 | 25 | * isPerfectNumber(-1); should return false since the number is < 1 26 | 27 | 28 | HINT: Use a while or for loop. 29 | 30 | HINT: Use the remainder operator. 31 | 32 | NOTE: The method isPerfectNumber should be defined as public static like we have been doing so far in the course. 33 | 34 | NOTE: Do not add a main method to the solution code. -------------------------------------------------------------------------------- /Coding Exercises 22 - Prefect Number/PerfectNumber.java: -------------------------------------------------------------------------------- 1 | public class PerfectNumber { 2 | // write your code here 3 | public static boolean isPerfectNumber(int number){ 4 | int sum=0; 5 | if(number>=1){ 6 | for(int i=1;i=0){ 70 | while(n !=0){ 71 | r = (r*10)+(n%10); 72 | n = n/10; 73 | } 74 | return r; 75 | }else{ 76 | n = n*(-1); 77 | r=0; 78 | while(n !=0){ 79 | r = (r*10)+(n%10); 80 | n = n/10; 81 | } 82 | return r*(-1); 83 | } 84 | } 85 | public static int getDigitCount(int number){ 86 | int count = 0; 87 | if(number>0){ 88 | while(number !=0){ 89 | number = number/10; 90 | count++; 91 | } 92 | return count; 93 | } 94 | if(number==0){ 95 | return 1; 96 | } 97 | return -1; 98 | } 99 | } -------------------------------------------------------------------------------- /Coding Exercises 24 - Flour Pack Problem/Exercise Description.txt: -------------------------------------------------------------------------------- 1 | Write a method named canPack with three parameters of type int named bigCount, smallCount, and goal. 2 | 3 | The parameter bigCount represents the count of big flour bags (5 kilos each). 4 | 5 | The parameter smallCount represents the count of small flour bags (1 kilo each). 6 | 7 | The parameter goal represents the goal amount of kilos of flour needed to assemble a package. 8 | 9 | Therefore, the sum of the kilos of bigCount and smallCount must be at least equal to the value of goal. The method should return true if it is possible to make a package with goal kilos of flour. 10 | 11 | If the sum is greater than goal, ensure that only full bags are used towards the goal amount. For example, if goal = 9, bigCount = 2, and smallCount = 0, the method should return false since each big bag is 5 kilos and cannot be divided. However, if goal = 9, bigCount = 1, and smallCount = 5, the method should return true because of 1 full bigCount bag and 4 full smallCount bags equal goal, and it's okay if there are additional bags left over. 12 | 13 | If any of the parameters are negative, return false. 14 | 15 | 16 | EXAMPLE INPUT/OUTPUT: 17 | 18 | * canPack (1, 0, 4); should return false since bigCount is 1 (big bag of 5 kilos) and goal is 4 kilos. 19 | 20 | * canPack (1, 0, 5); should return true since bigCount is 1 (big bag of 5 kilos) and goal is 5 kilos. 21 | 22 | * canPack (0, 5, 4); should return true since smallCount is 5 (small bags of 1 kilo) and goal is 4 kilos, and we have 1 bag left which is ok as mentioned above. 23 | 24 | * canPack (2, 2, 11); should return true since bigCount is 2 (big bags 5 kilos each) and smallCount is 2 (small bags of 1 kilo), makes in total 12 kilos and goal is 11 kilos. 25 | 26 | * canPack (-3, 2, 12); should return false since bigCount is negative. 27 | 28 | 29 | NOTE: The method canPack should be defined as public static like we have been doing so far in the course. 30 | 31 | NOTE: Do not add a main method to the solution code. -------------------------------------------------------------------------------- /Coding Exercises 24 - Flour Pack Problem/FlourPacker.java: -------------------------------------------------------------------------------- 1 | public class FlourPacker { 2 | // write your code here 3 | public static boolean canPack(int bigCount,int smallCount,int goal){ 4 | if(bigCount>=0 && smallCount>=0 && goal>=0){ 5 | if(goal==((bigCount*5)+(smallCount*1))){ 6 | if(goal >=(bigCount+smallCount)){ 7 | return true; 8 | } 9 | } 10 | if(goal<=((bigCount*5)+(smallCount*1))){ 11 | if(bigCount==0){ 12 | return true; 13 | }else{ 14 | for(int i=1;i<=bigCount;i++){ 15 | if(goal<(i*5)){ 16 | return false; 17 | } 18 | if(goal == (i*5)){ 19 | return true; 20 | } 21 | for(int j=1;j<=smallCount;j++){ 22 | if(goal==((i*5)+(j*1))){ 23 | return true; 24 | } 25 | } 26 | } 27 | } 28 | } 29 | } 30 | return false; 31 | } 32 | } -------------------------------------------------------------------------------- /Coding Exercises 25 - Largest Prime/Exercise Description.txt: -------------------------------------------------------------------------------- 1 | Write a method named getLargestPrime with one parameter of type int named number. 2 | 3 | If the number is negative or does not have any prime numbers, the method should return -1 to indicate an invalid value. 4 | 5 | 6 | The method should calculate the largest prime factor of a given number and return it. 7 | 8 | 9 | EXAMPLE INPUT/OUTPUT: 10 | 11 | * getLargestPrime (21); should return 7 since 7 is the largest prime (3 * 7 = 21) 12 | 13 | * getLargestPrime (217); should return 31 since 31 is the largest prime (7 * 31 = 217) 14 | 15 | * getLargestPrime (0); should return -1 since 0 does not have any prime numbers 16 | 17 | * getLargestPrime (45); should return 5 since 5 is the largest prime (3 * 3 * 5 = 45) 18 | 19 | * getLargestPrime (-1); should return -1 since the parameter is negative 20 | 21 | 22 | HINT: Since the numbers 0 and 1 are not considered prime numbers, they cannot contain prime numbers. 23 | 24 | NOTE: The method getLargestPrime should be defined as public static like we have been doing so far in the course. 25 | 26 | NOTE: Do not add a main method to the solution code. -------------------------------------------------------------------------------- /Coding Exercises 25 - Largest Prime/LargestPrime.java: -------------------------------------------------------------------------------- 1 | public class LargestPrime { 2 | // write your code here 3 | public static int getLargestPrime(int number){ 4 | if(number>0){ 5 | int temp=-1; 6 | for(int i=2;i<=number;i++){ 7 | if(number%i == 0){ 8 | number /= i; 9 | temp = i; 10 | i--; 11 | } 12 | } 13 | // if((number/10)==0){ 14 | // for(int i=2;i<=number;i++){ 15 | // if(number%i == 0){ 16 | // number /= i; 17 | // temp = i; 18 | // } 19 | // } 20 | //} 21 | return temp; 22 | } 23 | return -1; 24 | } 25 | } -------------------------------------------------------------------------------- /Coding Exercises 26 - Diagonal Star/DiagonalStar.java: -------------------------------------------------------------------------------- 1 | public class DiagonalStar { 2 | // write your code here 3 | public static void printSquareStar(int number){ 4 | if(number<5){ 5 | System.out.print("Invalid Value"); 6 | }else{ 7 | int d1=1; 8 | int d2=number; 9 | for(int r=1;r<=number;r++){ 10 | for(int c=1;c<=number;c++){ 11 | if(r==1 || r==number){ 12 | System.out.print("*"); 13 | }else{ 14 | if(c==1 || c==number){ 15 | System.out.print("*"); 16 | }else if(c==d1 || c==d2){ 17 | System.out.print("*"); 18 | }else{ 19 | System.out.print(" "); 20 | } 21 | } 22 | } 23 | System.out.println(""); 24 | d1++; 25 | d2--; 26 | } 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /Coding Exercises 26 - Diagonal Star/Exercise Description.txt: -------------------------------------------------------------------------------- 1 | Write a method named printSquareStar with one parameter of type int named number. 2 | 3 | If number is < 5, the method should print "Invalid Value". 4 | 5 | The method should print diagonals to generate a rectangular pattern composed of stars (*). This should be accomplished by using loops (see examples below). 6 | 7 | 8 | EXAMPLE INPUT/OUTPUT: 9 | 10 | EXAMPLE 1 11 | 12 | printSquareStar(5); should print the following: 13 | 14 | → NOTE: For text in Code Blocks below, use code icon {...} on Udemy 15 | 16 | ***** 17 | ** ** 18 | * * * 19 | ** ** 20 | ***** 21 | 22 | 23 | Explanation: 24 | 25 | ***** 5 stars 26 | ** ** 2 stars space 2 stars 27 | * * * 1 star space 1 star space 1 star 28 | ** ** 2 stars space 2 stars 29 | ***** 5 stars 30 | 31 | 32 | EXAMPLE 2 33 | 34 | printSquareStar(8); should print the following: 35 | 36 | ******** 37 | ** ** 38 | * * * * 39 | * ** * 40 | * ** * 41 | * * * * 42 | ** ** 43 | ******** 44 | 45 | 46 | The patterns above consist of a number of rows and columns (where number is the number of rows to print). For each row or column, stars are printed based on four conditions (Read them carefully): 47 | 48 | * In the first or last row 49 | 50 | * In the first or last column 51 | 52 | * When the row number equals the column number 53 | 54 | * When the column number equals rowCount - currentRow + 1 (where currentRow is current row number) 55 | 56 | 57 | HINT: Use a nested loop (a loop inside of a loop). 58 | 59 | HINT: To print on the same line, use the print method instead of println, e.g. System.out.print(" "); prints a space and does not "move" to another line. 60 | 61 | HINT: To "move" to another line, you can use an empty println call, e.g. System.out.println(); . 62 | 63 | NOTE: The method printSquareStar should be defined as public static like we have been doing so far in the course. 64 | 65 | NOTE: Do not add a main method to the solution code. -------------------------------------------------------------------------------- /Coding Exercises 27 - Input Calculator/Exercise Description.txt: -------------------------------------------------------------------------------- 1 | Write a method called inputThenPrintSumAndAverage that does not have any parameters. 2 | 3 | The method should not return anything (void) and it needs to keep reading int numbers from the keyboard. 4 | 5 | When the user enters something that is not an int then it needs to print a message in the format "SUM = XX AVG = YY". 6 | 7 | XX represents the sum of all entered numbers of type int. 8 | YY represents the calculated average of all numbers of type long. 9 | 10 | EXAMPLES OF INPUT/OUTPUT: 11 | 12 | EXAMPLE 1: 13 | 14 | INPUT: 15 | 16 | 1 17 | 2 18 | 3 19 | 4 20 | 5 21 | a 22 | 23 | OUTPUT 24 | 25 | SUM = 15 AVG = 3 26 | 27 | 28 | EXAMPLE 2: 29 | 30 | INPUT: 31 | 32 | hello 33 | 34 | OUTPUT: 35 | 36 | SUM = 0 AVG = 0 37 | 38 | 39 | TIP: Use Scanner to read an input from the user. 40 | 41 | TIP: Use casting when calling the round method since it needs double as a parameter. 42 | 43 | NOTE: Use the method Math.round to round the calculated average (double). The method round returns long. 44 | 45 | NOTE: Be mindful of spaces in the printed message. 46 | 47 | NOTE: Be mindful of users who may type an invalid input right away (see example above). 48 | 49 | NOTE: The method inputThenPrintSumAndAverage should be defined as public static like we have been doing so far in the course. 50 | 51 | NOTE: Do not add the main method to the solution code. -------------------------------------------------------------------------------- /Coding Exercises 27 - Input Calculator/InputCalculator.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class InputCalculator { 4 | // Write your code here 5 | public static void inputThenPrintSumAndAverage(){ 6 | int sum = 0, count = 0; 7 | double avg =0; 8 | Scanner sc = new Scanner(System.in); 9 | 10 | while (true) { 11 | boolean number = sc.hasNextInt(); 12 | 13 | if (number) { 14 | int data = sc.nextInt(); 15 | sum = sum + data; 16 | count++; 17 | } else if (count == 0){ 18 | System.out.println("SUM = 0 AVG = 0"); 19 | break; 20 | } else { 21 | avg = (double)sum/count; 22 | avg = Math.round(avg); 23 | System.out.println("SUM = " + sum + " AVG = " + (int)avg); 24 | break; 25 | } 26 | sc.nextLine(); 27 | } 28 | // sc.close(); 29 | } 30 | } -------------------------------------------------------------------------------- /Coding Exercises 28 - Paint Job/Exercise Description.txt: -------------------------------------------------------------------------------- 1 | Bob is a wall painter and he needs your help. You have to write a program that helps Bob calculate how many buckets of paint he needs to buy before going to work. Bob might also have some extra buckets at home. He also knows the area that he can cover with one bucket of paint. 2 | 3 | 1. Write a method named getBucketCount with 4 parameters. The first parameter should be named width of type double. This parameter represents the width of the wall. 4 | 5 | The second parameter should be named height of type double. This parameter represents the height of the wall. 6 | 7 | The third parameter should be named areaPerBucket. This parameter represents the area that can be covered with one bucket of paint. 8 | 9 | The fourth parameter should be named extraBuckets. This parameter represents the bucket count that Bob has at home. 10 | 11 | The method needs to return a value of type int that represents the number of buckets that Bob needs to buy before going to work. To calculate the bucket count, refer to the notes below. 12 | 13 | If one of the parameters width, height or areaPerBucket is less or equal to 0 or if extraBuckets is less than 0, the method needs to return -1 to indicate an invalid value. 14 | 15 | If all parameters are valid, the method needs to calculate the number of buckets and return it. 16 | 17 | 18 | Examples of input/output: 19 | 20 | *getBucketCount(-3.4, 2.1, 1.5, 2); → should return -1 since the width parameter is invalid 21 | 22 | *getBucketCount(3.4, 2.1, 1.5, 2); → should return 3 since the wall area is 7.14, a single bucket can cover an area of 1.5 and Bob has 2 extra buckets home. 23 | 24 | *getBucketCount(2.75, 3.25, 2.5, 1); → should return 3 since the wall area is 8.9375, a single bucket can cover an area of 2.5 and Bob has 1 extra bucket at home. 25 | 26 | 27 | 28 | 2. Bob does not like to enter 0 for the extraBuckets parameter so he needs another method. 29 | 30 | Write another overloaded method named getBucketCount with 3 parameters namely width, height, and areaPerBucket (all of type double). 31 | 32 | This method needs to return a value of type int that represents the number of buckets that Bob needs to buy before going to work. To calculate the bucket count, refer to the notes below. 33 | 34 | If one of the parameters width, height or areaPerBucket is less or equal to 0, the method needs to return -1 to indicate an invalid value. 35 | 36 | If all parameters are valid, the method needs to calculate the number of buckets and return it. 37 | 38 | 39 | Examples of input/output: 40 | 41 | *getBucketCount(-3.4, 2.1, 1.5); → should return -1 since the width parameter is invalid 42 | 43 | *getBucketCount(3.4, 2.1, 1.5); → should return 5 since the wall area is 7.14, and a single bucket can cover an area of 1.5. 44 | 45 | *getBucketCount(7.25, 4.3, 2.35); → should return 14 since the wall area is 31.175, and a single bucket can cover an area of 2.35. 46 | 47 | 48 | 3. In some cases, Bob does not know the width and height of the wall but he knows the area of a wall. He needs you to write another method. 49 | 50 | Write another overloaded method named getBucketCount with 2 parameters namely, area and areaPerBucket (both of type double). 51 | 52 | The method needs to return a value of type int that represents the number of buckets that Bob needs to buy before going to work. To calculate the bucket count, refer to the notes below. 53 | 54 | If one of the parameters area or areaPerBucket is less or equal to 0, the method needs to return -1to indicate an invalid value. 55 | 56 | If all parameters are valid, the method needs to calculate the number of buckets and return it. 57 | 58 | 59 | Examples of input/output: 60 | 61 | *getBucketCount(3.4, 1.5); → should return 3 since the area is 3.4 and a single bucket can cover an area of 1.5 62 | 63 | *getBucketCount(6.26, 2.2); → should return 3 since the wall area is 6.26 and a single bucket can cover an area of 2.2. 64 | 65 | *getBucketCount(3.26, 0.75); → should return 5 since the wall area is 3.26, and a single bucket can cover an area of 0.75 . 66 | 67 | Do your best to help Bob. 68 | 69 | 70 | NOTE: Use the method Math.ceil to round the number of calculated buckets (double) then convert it into an int before returning the value from the methods. 71 | 72 | NOTE: All methods should be defined as public static like we have been doing so far in the course. 73 | 74 | NOTE: Do not add the main method to the solution code. -------------------------------------------------------------------------------- /Coding Exercises 28 - Paint Job/PaintJob.java: -------------------------------------------------------------------------------- 1 | public class PaintJob { 2 | // write your code here 3 | public static int getBucketCount(double width,double height,double areaPerBucket,int extraBucket){ 4 | double area; 5 | double count; 6 | if(width>0.0 && height>0.0 && areaPerBucket>0.0 && extraBucket>=0){ 7 | area = height*width; 8 | count = area/areaPerBucket; 9 | count = count-extraBucket; 10 | count = count+1; 11 | return (int)count; 12 | } 13 | return -1; 14 | } 15 | public static int getBucketCount(double width,double height,double areaPerBucket){ 16 | double area; 17 | double count; 18 | if(width>0 && height>0 && areaPerBucket>0){ 19 | area = height*width; 20 | count = area/areaPerBucket; 21 | // count = count-extraBucket; 22 | count = count+1; 23 | return (int)count; 24 | } 25 | return -1; 26 | } 27 | public static int getBucketCount(double area,double areaPerBucket){ 28 | double count; 29 | if(area>0 && areaPerBucket>0){ 30 | count = area/areaPerBucket; 31 | count = count+1; 32 | return (int)count; 33 | } 34 | return -1; 35 | } 36 | } -------------------------------------------------------------------------------- /Coding Exercises 29 - Sum Calculator/Exercise Description.txt: -------------------------------------------------------------------------------- 1 | Write a class with the name SimpleCalculator. The class needs two fields (instance variables) with names firstNumber and secondNumber both of type double. 2 | 3 | Write the following methods (instance methods): 4 | 5 | *Method named getFirstNumber without any parameters, it needs to return the value of firstNumber field. 6 | *Method named getSecondNumber without any parameters, it needs to return the value of secondNumber field. 7 | *Method named setFirstNumber with one parameter of type double, it needs to set the value of the firstNumber field. 8 | *Method named setSecondNumber with one parameter of type double, it needs to set the value of the secondNumberfield. 9 | *Method named getAdditionResult without any parameters, it needs to return the result of adding the field values of firstNumber and secondNumber. 10 | *Method named getSubtractionResult without any parameters, it needs to return the result of subtracting the field values of secondNumber from the firstNumber. 11 | *Method named getMultiplicationResult without any parameters, it needs to return the result of multiplying the field values of firstNumber and secondNumber. 12 | *Method named getDivisionResult without any parameters it needs to return the result of dividing the field values of firstNumber by the secondNumber. In case the value of secondNumber is 0 then return 0. 13 | 14 | TEST EXAMPLE 15 | 16 | TEST CODE: 17 | 18 | SimpleCalculator calculator = new SimpleCalculator(); 19 | calculator.setFirstNumber(5.0); 20 | calculator.setSecondNumber(4); 21 | System.out.println("add= " + calculator.getAdditionResult()); 22 | System.out.println("subtract= " + calculator.getSubtractionResult()); 23 | calculator.setFirstNumber(5.25); 24 | calculator.setSecondNumber(0); 25 | System.out.println("multiply= " + calculator.getMultiplicationResult()); 26 | System.out.println("divide= " + calculator.getDivisionResult()); 27 | 28 | OUTPUT 29 | 30 | add= 9.0 31 | subtract= 1.0 32 | multiply= 0.0 33 | divide= 0.0 34 | 35 | TIPS: 36 | 37 | *add= 9.0 is printed because 5.0 + 4 is 9.0 38 | *subtract= 1.0 is printed because 5.0 - 4 is 1.0 39 | *multiply= 0.0 is printed because 5.25 * 0 is 0.0 40 | *divide= 0.0 is printed because secondNumber is set to 0 41 | 42 | 43 | NOTE: All methods should be defined as public NOT public static. 44 | 45 | NOTE: In total, you have to write 8 methods. 46 | 47 | NOTE: Do not add the main method to the solution code. -------------------------------------------------------------------------------- /Coding Exercises 29 - Sum Calculator/SimpleCalculator.java: -------------------------------------------------------------------------------- 1 | public class SimpleCalculator { 2 | // write your code here 3 | private double firstNumber, secondNumber; 4 | public double getFirstNumber(){ 5 | return firstNumber; 6 | } 7 | public double getSecondNumber(){ 8 | return secondNumber; 9 | } 10 | public void setFirstNumber(double n){ 11 | firstNumber = n; 12 | } 13 | public void setSecondNumber(double m){ 14 | secondNumber = m; 15 | } 16 | public double getAdditionResult(){ 17 | return (firstNumber+secondNumber); 18 | } 19 | public double getSubtractionResult(){ 20 | return (firstNumber-secondNumber); 21 | } 22 | public double getMultiplicationResult(){ 23 | return (firstNumber*secondNumber); 24 | } 25 | public double getDivisionResult(){ 26 | if(secondNumber == 0){ 27 | return 0; 28 | } 29 | return (firstNumber/secondNumber); 30 | } 31 | } -------------------------------------------------------------------------------- /Coding Exercises 30 - Person/Exercise Description.txt: -------------------------------------------------------------------------------- 1 | Write a class with the name Person. The class needs three fields (instance variables) with the names firstName, lastName of type String and age of type int. 2 | 3 | Write the following methods (instance methods): 4 | 5 | *Method named getFirstName without any parameters, it needs to return the value of the firstName field. 6 | *Method named getLastName without any parameters, it needs to return the value of the lastName field. 7 | *Method named getAge without any parameters, it needs to return the value of the age field. 8 | *Method named setFirstName with one parameter of type String, it needs to set the value of the firstName field. 9 | *Method named setLastName with one parameter of type String, it needs to set the value of the lastName field. 10 | *Method named setAge with one parameter of type int, it needs to set the value of the age field. If the parameter is less than 0 or greater than 100, it needs to set the age field value to 0. 11 | *Method named isTeen without any parameters, it needs to return true if the value of the age field is greater than 12 and less than 20, otherwise, return false. 12 | *Method named getFullName without any parameters, it needs to return the full name of the person. 13 | *In case both firstName and lastName fields are empty, Strings return an empty String. 14 | *In case lastName is an empty String, return firstName. 15 | *In case firstName is an empty String, return lastName. 16 | 17 | To check if s String is empty, use the method isEmpty from the String class. For example, firstName.isEmpty() returns true if the String is empty or in other words, when the String does not contain any characters. 18 | 19 | 20 | TEST EXAMPLE 21 | 22 | TEST CODE: 23 | 24 | Person person = new Person(); 25 | person.setFirstName(""); // firstName is set to empty string 26 | person.setLastName(""); // lastName is set to empty string 27 | person.setAge(10); 28 | System.out.println("fullName= " + person.getFullName()); 29 | System.out.println("teen= " + person.isTeen()); 30 | person.setFirstName("John"); // firstName is set to John 31 | person.setAge(18); 32 | System.out.println("fullName= " + person.getFullName()); 33 | System.out.println("teen= " + person.isTeen()); 34 | person.setLastName("Smith"); // lastName is set to Smith 35 | System.out.println("fullName= " + person.getFullName()); 36 | 37 | OUTPUT 38 | 39 | fullName= 40 | teen= false 41 | fullName= John 42 | teen= true 43 | fullName= John Smith 44 | 45 | 46 | NOTE: All methods should be defined as public NOT public static. 47 | 48 | NOTE: In total, you have to write 8 methods. 49 | 50 | NOTE: Do not add the main method to the solution code. -------------------------------------------------------------------------------- /Coding Exercises 30 - Person/Person.java: -------------------------------------------------------------------------------- 1 | public class Person { 2 | // write your code here 3 | private String firstName, lastName; 4 | private int age; 5 | 6 | public String getFirstName(){ 7 | return firstName; 8 | } 9 | 10 | public String getLastName(){ 11 | return lastName; 12 | } 13 | 14 | public int getAge(){ 15 | return age; 16 | } 17 | 18 | public void setFirstName(String n){ 19 | firstName = n; 20 | } 21 | 22 | public void setLastName(String l){ 23 | lastName = l; 24 | } 25 | 26 | public void setAge(int a){ 27 | if(a<0 || a>100){ 28 | age = 0; 29 | }else{ 30 | age = a; 31 | } 32 | } 33 | 34 | public boolean isTeen(){ 35 | if(age>12 && age<20){ 36 | return true; 37 | } 38 | return false; 39 | } 40 | 41 | public String getFullName(){ 42 | String empty = ""; 43 | if(firstName.isEmpty() && lastName.isEmpty()){ 44 | return empty; 45 | }else if(firstName.isEmpty() && !lastName.isEmpty()){ 46 | return lastName; 47 | }else if(!firstName.isEmpty() && lastName.isEmpty()){ 48 | return firstName; 49 | } 50 | return (firstName+" "+lastName); 51 | } 52 | } -------------------------------------------------------------------------------- /Coding Exercises 31 - Wall Area/Exercise Description.txt: -------------------------------------------------------------------------------- 1 | Write a class with the name Wall. The class needs two fields (instance variables) with name width and height of type double. 2 | 3 | The class needs to have two constructors. The first constructor does not have any parameters (no-arg constructor). The second constructor has parameters width and height of type double and it needs to initialize the fields. In case the width is less than 0 it needs to set the width field value to 0, in case the height parameter is less than 0 it needs to set the height field value to 0. 4 | 5 | Write the following methods (instance methods): 6 | * Method named getWidth without any parameters, it needs to return the value of width field. 7 | * Method named getHeight without any parameters, it needs to return the value of height field. 8 | * Method named setWidth with one parameter of type double, it needs to set the value of the width field. If the parameter is less than 0 it needs to set the width field value to 0. 9 | * Method named setHeight with one parameter of type double, it needs to set the value of the height field. If the parameter is less than 0 it needs to set the height field value to 0. 10 | * Method named getArea without any parameters, it needs to return the area of the wall. 11 | 12 | 13 | TEST EXAMPLE 14 | 15 | → TEST CODE: 16 | 17 | 1 Wall wall = new Wall(5,4); 18 | 2 System.out.println("area= " + wall.getArea()); 19 | 3 20 | 4 wall.setHeight(-1.5); 21 | 5 System.out.println("width= " + wall.getWidth()); 22 | 6 System.out.println("height= " + wall.getHeight()); 23 | 7 System.out.println("area= " + wall.getArea()); 24 | 25 | → OUTPUT: 26 | 27 | area= 20.0 28 | width= 5.0 29 | height= 0.0 30 | area= 0.0 31 | 32 | 33 | NOTE: All methods should be defined as public NOT public static. 34 | 35 | NOTE: In total, you have to write 5 methods and 2 constructors. 36 | 37 | NOTE: Do not add a main method to the solution code. -------------------------------------------------------------------------------- /Coding Exercises 31 - Wall Area/Wall.java: -------------------------------------------------------------------------------- 1 | public class Wall { 2 | // write your code here 3 | private double width, height; 4 | 5 | public Wall(){ 6 | 7 | } 8 | 9 | public Wall(double width, double height){ 10 | if(width<0){ 11 | this.width = 0; 12 | }else{ 13 | this.width = width; 14 | } 15 | if(height<0){ 16 | this.height = 0; 17 | }else{ 18 | this.height = height; 19 | } 20 | } 21 | 22 | public double getWidth(){ 23 | return width; 24 | } 25 | 26 | public double getHeight(){ 27 | return height; 28 | } 29 | 30 | public void setWidth(double width){ 31 | if(width<0){ 32 | this.width = 0; 33 | }else{ 34 | this.width = width; 35 | } 36 | } 37 | 38 | public void setHeight(double height){ 39 | if(height<0){ 40 | this.height = 0; 41 | }else{ 42 | this.height = height; 43 | } 44 | } 45 | 46 | public double getArea(){ 47 | return (width*height); 48 | } 49 | } -------------------------------------------------------------------------------- /Coding Exercises 32 - Point/Exercise Description.txt: -------------------------------------------------------------------------------- 1 | You have to represent a point in 2D space. Write a class with the name Point. The class needs two fields (instance variables) with name x and y of type int. 2 | 3 | The class needs to have two constructors. The first constructor does not have any parameters (no-arg constructor). The second constructor has parameters x and y of type int and it needs to initialize the fields. 4 | 5 | Write the following methods (instance methods): 6 | * Method named getX without any parameters, it needs to return the value of x field. 7 | * Method named getY without any parameters, it needs to return the value of y field. 8 | * Method named setX with one parameter of type int, it needs to set the value of the x field. 9 | * Method named setY with one parameter of type int, it needs to set the value of the y field. 10 | * Method named distance without any parameters, it needs to return the distance between this Point and Point 0,0 as double. 11 | * Method named distance with two parameters x, y both of type int, it needs to return the distance between this Point and Point x,y as double. 12 | * Method named distance with parameter another of type Point, it needs to return the distance between this Point and another Point as double. 13 | 14 | How to find the distance between two points?To find a distance between points A(xA,yA) and B(xB,yB), we use the formula: 15 | 16 | d(A,B)=√ (xB − xA) * (xB - xA) + (yB − yA) * (yB - yA) 17 | 18 | Where √ represents square root. 19 | 20 | 21 | 22 | 23 | TEST EXAMPLE 24 | 25 | → TEST CODE: 26 | 27 | Point first = new Point(6, 5); 28 | Point second = new Point(3, 1); 29 | System.out.println("distance(0,0)= " + first.distance()); 30 | System.out.println("distance(second)= " + first.distance(second)); 31 | System.out.println("distance(2,2)= " + first.distance(2, 2)); 32 | Point point = new Point(); 33 | System.out.println("distance()= " + point.distance()); 34 | 35 | OUTPUT 36 | 37 | distance(0,0)= 7.810249675906654 38 | distance(second)= 5.0 39 | distance(2,2)= 5.0 40 | distance()= 0.0 41 | 42 | NOTE: Use Math.sqrt to calculate the square root √. 43 | 44 | NOTE: Try to avoid duplicated code. 45 | 46 | NOTE: All methods should be defined as public NOT public static. 47 | 48 | NOTE: In total, you have to write 7 methods. 49 | 50 | NOTE: Do not add a main method to the solution code. -------------------------------------------------------------------------------- /Coding Exercises 32 - Point/Point.java: -------------------------------------------------------------------------------- 1 | public class Point { 2 | // write your code here 3 | private int x, y; 4 | 5 | public Point(){ 6 | 7 | } 8 | 9 | public Point(int x, int y){ 10 | this.x = x; 11 | this.y = y; 12 | } 13 | 14 | public int getX(){ 15 | return x; 16 | } 17 | 18 | public int getY(){ 19 | return y; 20 | } 21 | 22 | public void setX(int x){ 23 | this.x = x; 24 | } 25 | 26 | public void setY(int y){ 27 | this.y = y; 28 | } 29 | 30 | public double distance(){ 31 | return Math.sqrt((x*x)+(y*y)); 32 | } 33 | 34 | public double distance(int Ax, int Ay){ 35 | return Math.sqrt((x-Ax)*(x-Ax)+(y-Ay)*(y-Ay)); 36 | } 37 | 38 | public double distance(Point pt){ 39 | return Math.sqrt((x-pt.x)*(x-pt.x)+(y-pt.y)*(y-pt.y)); 40 | } 41 | } -------------------------------------------------------------------------------- /Coding Exercises 33 - Carpet Cost Calculator/Calculator.java: -------------------------------------------------------------------------------- 1 | public class Calculator { 2 | // write your code here 3 | private Floor floor; 4 | private Carpet carpet; 5 | 6 | public Calculator(Floor floor, Carpet carpet){ 7 | this.floor = floor; 8 | this.carpet = carpet; 9 | } 10 | 11 | public double getTotalCost(){ 12 | return (floor.getArea() * carpet.getCost()); 13 | } 14 | } -------------------------------------------------------------------------------- /Coding Exercises 33 - Carpet Cost Calculator/Carpet.java: -------------------------------------------------------------------------------- 1 | public class Carpet { 2 | // write your code here 3 | private double cost; 4 | 5 | public Carpet(double cost){ 6 | if(cost<0){ 7 | this.cost = 0; 8 | }else{ 9 | this.cost = cost; 10 | } 11 | } 12 | 13 | public double getCost(){ 14 | return cost; 15 | } 16 | } -------------------------------------------------------------------------------- /Coding Exercises 33 - Carpet Cost Calculator/Exercise Description.txt: -------------------------------------------------------------------------------- 1 | The Carpet Company has asked you to write an application that calculates the price of carpeting for rectangular rooms. To calculate the price, you multiply the area of the floor (width times length) by the price per square meter of carpet. For example, the area of the floor that is 12 meters long and 10 meters wide is 120 square meters. To cover the floor with a carpet that costs $8 per square meter would cost $960. 2 | 3 | 1. Write a class with the name Floor. The class needs two fields (instance variables) with name width and length of type double. 4 | 5 | The class needs to have one constructor with parameters width and length of type double and it needs to initialize the fields. 6 | 7 | In case the width parameter is less than 0 it needs to set the width field value to 0, in case the length parameter is less than 0 it needs to set the length field value to 0. 8 | 9 | Write the following methods (instance methods): 10 | 11 | * Method named getArea without any parameters, it needs to return the calculated area (width * length). 12 | 13 | 14 | 2. Write a class with the name Carpet. The class needs one field (instance variable) with name cost of type double. 15 | 16 | The class needs to have one constructor with parameter cost of type double and it needs to initialize the field. 17 | 18 | In case the cost parameter is less than 0 it needs to set the cost field value to 0. 19 | 20 | Write the following methods (instance methods): 21 | 22 | * Method named getCost without any parameters, it needs to return the value of cost field 23 | 24 | 25 | 3. Write a class with the name Calculator. The class needs two fields (instance variables) with name floor of type Floor and carpet of type Carpet. 26 | 27 | The class needs to have one constructor with parameters floor of type Floor and carpet of type Carpet and it needs to initialize the fields. 28 | 29 | Write the following methods (instance methods): 30 | 31 | * Method named getTotalCost without any parameters, it needs to return the calculated total cost to cover the floor with a carpet. 32 | 33 | 34 | TEST EXAMPLE 35 | 36 | → TEST CODE: 37 | 38 | Carpet carpet = new Carpet(3.5); 39 | Floor floor = new Floor(2.75, 4.0); 40 | Calculator calculator = new Calculator(floor, carpet); 41 | System.out.println("total= " + calculator.getTotalCost()); 42 | carpet = new Carpet(1.5); 43 | floor = new Floor(5.4, 4.5); 44 | calculator = new Calculator(floor, carpet); 45 | System.out.println("total= " + calculator.getTotalCost()); 46 | 47 | → OUTPUT 48 | 49 | total= 38.5 50 | total= 36.45 51 | 52 | 53 | NOTE: All methods should be defined as public NOT public static. 54 | 55 | NOTE: In total, you have to write 3 classes. 56 | 57 | NOTE: Do not add a main method to the solution code. -------------------------------------------------------------------------------- /Coding Exercises 33 - Carpet Cost Calculator/Floor.java: -------------------------------------------------------------------------------- 1 | public class Floor { 2 | // write your code here 3 | private double width, length; 4 | 5 | public Floor(double width, double length){ 6 | if(width<0){ 7 | this.width = 0; 8 | }else{ 9 | this.width = width; 10 | } 11 | if(length<0){ 12 | this.length = 0; 13 | }else{ 14 | this.length = length; 15 | } 16 | } 17 | 18 | public double getArea(){ 19 | return (width*length); 20 | } 21 | } -------------------------------------------------------------------------------- /Coding Exercises 34 - Complex Operation/ComplexNumber.java: -------------------------------------------------------------------------------- 1 | public class ComplexNumber { 2 | // write your code here 3 | private double real, imaginary; 4 | 5 | public ComplexNumber(double real, double imaginary){ 6 | this.real = real; 7 | this.imaginary = imaginary; 8 | } 9 | 10 | public double getReal(){ 11 | return real; 12 | } 13 | 14 | public double getImaginary(){ 15 | return imaginary; 16 | } 17 | 18 | public void add(double real, double imaginary){ 19 | this.real = this.real + real; 20 | this.imaginary = this.imaginary + imaginary; 21 | } 22 | 23 | public void add(ComplexNumber complex){ 24 | this.real = this.real + complex.getReal(); 25 | this.imaginary = this.imaginary + complex.getImaginary(); 26 | } 27 | 28 | public void subtract(double real, double imaginary){ 29 | this.real = this.real - real; 30 | this.imaginary = this.imaginary - imaginary; 31 | } 32 | 33 | public void subtract(ComplexNumber complex){ 34 | this.real = this.real - complex.getReal(); 35 | this.imaginary = this.imaginary - complex.getImaginary(); 36 | } 37 | } -------------------------------------------------------------------------------- /Coding Exercises 34 - Complex Operation/Exercise Description.txt: -------------------------------------------------------------------------------- 1 | A complex number is a number that can be expressed in the form a + bi, where a and b are real numbers, and i is a solution of the equation x2 = −1. Because no real number satisfies this equation, i is called an imaginary number. For the complex number a + bi, a is called the real part, and b is called the imaginary part. To add or subtract two complex numbers, just add or subtract the corresponding real and imaginary parts. For instance, the sum of 5 + 3i and 4 + 2i is 9 + 5i. For another, the sum of 3 + i and –1 + 2i is 2 + 3i. 2 | 3 | Write a class with the name ComplexNumber. The class needs two fields (instance variables) with name real and imaginary of type double. It represents the Complex Number. 4 | 5 | The class needs to have one constructor. The constructor has parameters real and imaginary of type double and it needs to initialize the fields. 6 | 7 | Write the following methods (instance methods): 8 | * Method named getReal without any parameters, it needs to return the value of real field. 9 | * Method named getImaginary without any parameters, it needs to return the value of imaginary field. 10 | * Method named add with two parameters real and imaginary of type double, it needs to add parameters to fields. In other words, it needs to do a complex number add operation as described above. 11 | * Method named add with one parameter of type ComplexNumber. It needs to add the ComplexNumber parameter to the corresponding instance variables. 12 | * Method named subtract with two parameters real and imaginary of type double, it needs to subtract parameters from fields, in other words, it needs to do a complex number subtract operation as described above. 13 | * Method named subtract with one parameter other of type ComplexNumber. It needs to subtract the other parameter from this complex number. 14 | 15 | 16 | TEST EXAMPLE 17 | 18 | → TEST CODE: 19 | 20 | ComplexNumber one = new ComplexNumber(1.0, 1.0); 21 | ComplexNumber number = new ComplexNumber(2.5, -1.5); 22 | one.add(1,1); 23 | System.out.println("one.real= " + one.getReal()); 24 | System.out.println("one.imaginary= " + one.getImaginary()); 25 | one.subtract(number); 26 | System.out.println("one.real= " + one.getReal()); 27 | System.out.println("one.imaginary= " + one.getImaginary()); 28 | number.subtract(one); 29 | System.out.println("number.real= " + number.getReal()); 30 | System.out.println("number.imaginary= " + number.getImaginary()); 31 | 32 | → OUTPUT 33 | 34 | one.real= 2.0 35 | one.imaginary= 2.0 36 | one.real= -0.5 37 | one.imaginary= 3.5 38 | number.real= 3.0 39 | number.imaginary= -5.0 40 | 41 | 42 | NOTE: Try to avoid duplicated code. 43 | 44 | NOTE: All methods should be defined as public NOT public static. 45 | 46 | NOTE: In total, you have to write 6 methods. 47 | 48 | NOTE: Do not add a main method to the solution code. -------------------------------------------------------------------------------- /Coding Exercises 35 - Cylinder/Circle.java: -------------------------------------------------------------------------------- 1 | public class Circle { 2 | // write your code here 3 | private double radius; 4 | 5 | public Circle(double radius){ 6 | if(radius<0){ 7 | this.radius = 0; 8 | }else{ 9 | this.radius = radius; 10 | } 11 | } 12 | 13 | public double getRadius(){ 14 | return radius; 15 | } 16 | 17 | public double getArea(){ 18 | return (radius*radius*Math.PI); 19 | } 20 | } -------------------------------------------------------------------------------- /Coding Exercises 35 - Cylinder/Cylinder.java: -------------------------------------------------------------------------------- 1 | public class Cylinder extends Circle{ 2 | // write your code here 3 | private double height; 4 | 5 | public Cylinder(double radius, double height){ 6 | super(radius); 7 | if(height<0){ 8 | this.height = 0; 9 | }else{ 10 | this.height = height; 11 | } 12 | } 13 | 14 | public double getHeight(){ 15 | return height; 16 | } 17 | 18 | public double getVolume(){ 19 | return (getArea()*height); 20 | } 21 | } -------------------------------------------------------------------------------- /Coding Exercises 35 - Cylinder/Exercise Description.txt: -------------------------------------------------------------------------------- 1 | 1. Write a class with the name Circle. The class needs one field (instance variable) with name radius of type double. 2 | 3 | The class needs to have one constructor with parameter radius of type double and it needs to initialize the fields. 4 | 5 | In case the radius parameter is less than 0 it needs to set the radius field value to 0. 6 | 7 | Write the following methods (instance methods): 8 | * Method named getRadius without any parameters, it needs to return the value of radius field. 9 | * Method named getArea without any parameters, it needs to return the calculated area (radius * radius * PI). For PI use Math.PI constant. 10 | 11 | 12 | 2. Write a class with the name Cylinder that extends Circle class. The class needs one field (instance variable) with name height of type double. 13 | 14 | The class needs to have one constructor with two parameters radius and height both of type double. It needs to call parent constructor and initialize a height field. 15 | 16 | In case the height parameter is less than 0 it needs to set the height field value to 0. 17 | 18 | Write the following methods (instance methods): 19 | * Method named getHeight without any parameters, it needs to return the value of height field. 20 | * Method named getVolume without any parameters, it needs to return the calculated volume. To calculate volume multiply the area with height. 21 | 22 | 23 | 24 | TEST EXAMPLE 25 | 26 | → TEST CODE: 27 | 28 | Circle circle = new Circle(3.75); 29 | System.out.println("circle.radius= " + circle.getRadius()); 30 | System.out.println("circle.area= " + circle.getArea()); 31 | Cylinder cylinder = new Cylinder(5.55, 7.25); 32 | System.out.println("cylinder.radius= " + cylinder.getRadius()); 33 | System.out.println("cylinder.height= " + cylinder.getHeight()); 34 | System.out.println("cylinder.area= " + cylinder.getArea()); 35 | System.out.println("cylinder.volume= " + cylinder.getVolume()); 36 | 37 | → OUTPUT 38 | 39 | circle.radius= 3.75 40 | circle.area= 44.178646691106465 41 | cylinder.radius= 5.55 42 | cylinder.height= 7.25 43 | cylinder.area= 96.76890771219959 44 | cylinder.volume= 701.574580913447 45 | 46 | 47 | NOTE: All methods should be defined as public NOT public static. 48 | 49 | NOTE: In total, you have to write 2 classes. 50 | 51 | NOTE: Do not add a main method to the solution code. -------------------------------------------------------------------------------- /Coding Exercises 36 - Pool Area/Cuboid.java: -------------------------------------------------------------------------------- 1 | public class Cuboid extends Rectangle{ 2 | // write your code here 3 | private double height; 4 | 5 | public Cuboid(double width, double length, double height){ 6 | super(width,length); 7 | if(height<0){ 8 | this.height = 0; 9 | }else{ 10 | this.height = height; 11 | } 12 | } 13 | 14 | public double getHeight(){ 15 | return height; 16 | } 17 | 18 | public double getVolume(){ 19 | return (getArea() * height); 20 | } 21 | } -------------------------------------------------------------------------------- /Coding Exercises 36 - Pool Area/Exercise Description.txt: -------------------------------------------------------------------------------- 1 | The Swimming Company has asked you to write an application that calculates the volume of cuboid shaped pools. 2 | 3 | 4 | 1. Write a class with the name Rectangle. The class needs two fields (instance variable) with name width and length both of type double. 5 | 6 | The class needs to have one constructor with parameters width and length both of type double and it needs to initialize the fields. 7 | 8 | In case the width parameter is less than 0 it needs to set the width field value to 0. 9 | 10 | In case the length parameter is less than 0 it needs to set the length field value to 0. 11 | 12 | Write the following methods (instance methods): 13 | * Method named getWidth without any parameters, it needs to return the value of width field. 14 | * Method named getLength without any parameters, it needs to return the value of length field. 15 | * Method named getArea without any parameters, it needs to return the calculated area (width * length). 16 | 17 | 18 | 2. Write a class with the name Cuboid that extends Rectangle class. The class needs one field (instance variable) with name height of type double. 19 | 20 | The class needs to have one constructor with three parameters width, length, and height all of type double. It needs to call parent constructor and initialize a height field. 21 | 22 | In case the height parameter is less than 0 it needs to set the height field value to 0. 23 | 24 | Write the following methods (instance methods): 25 | * Method named getHeight without any parameters, it needs to return the value of height field. 26 | * Method named getVolume without any parameters, it needs to return the calculated volume. To calculate volume multiply the area with height. 27 | 28 | 29 | 30 | TEST EXAMPLE 31 | 32 | → TEST CODE: 33 | 34 | Rectangle rectangle = new Rectangle(5, 10); 35 | System.out.println("rectangle.width= " + rectangle.getWidth()); 36 | System.out.println("rectangle.length= " + rectangle.getLength()); 37 | System.out.println("rectangle.area= " + rectangle.getArea()); 38 | Cuboid cuboid = new Cuboid(5,10,5); 39 | System.out.println("cuboid.width= " + cuboid.getWidth()); 40 | System.out.println("cuboid.length= " + cuboid.getLength()); 41 | System.out.println("cuboid.area= " + cuboid.getArea()); 42 | System.out.println("cuboid.height= " + cuboid.getHeight()); 43 | System.out.println("cuboid.volume= " + cuboid.getVolume()); 44 | 45 | → OUTPUT 46 | 47 | rectangle.width= 5.0 48 | rectangle.length= 10.0 49 | rectangle.area= 50.0 50 | cuboid.width= 5.0 51 | cuboid.length= 10.0 52 | cuboid.area= 50.0 53 | cuboid.height= 5.0 54 | cuboid.volume= 250.0 55 | 56 | 57 | NOTE: All methods should be defined as public NOT public static. 58 | 59 | NOTE: In total, you have to write 2 classes. 60 | 61 | NOTE: Do not add a main method to the solution code. -------------------------------------------------------------------------------- /Coding Exercises 36 - Pool Area/Rectangle.java: -------------------------------------------------------------------------------- 1 | public class Rectangle { 2 | // write your code here 3 | private double width , length; 4 | 5 | public Rectangle(double width, double length){ 6 | if(width<0){ 7 | this.width = 0; 8 | }else{ 9 | this.width = width; 10 | } 11 | 12 | if(length<0){ 13 | this.length = 0; 14 | }else{ 15 | this.length = length; 16 | } 17 | } 18 | 19 | public double getWidth(){ 20 | return width; 21 | } 22 | 23 | public double getLength(){ 24 | return length; 25 | } 26 | 27 | public double getArea(){ 28 | return (width*length); 29 | } 30 | } -------------------------------------------------------------------------------- /Coding Exercises 37 - Composition/Bed.java: -------------------------------------------------------------------------------- 1 | public class Bed { 2 | private String style; 3 | private int pillows, height, sheets, quilt; 4 | 5 | public Bed(String style, int pillows, int height, int sheets, int quilt){ 6 | this.style = style; 7 | this.pillows = pillows; 8 | this.height = height; 9 | this.sheets = sheets; 10 | this.quilt = quilt; 11 | } 12 | public void make(){ 13 | System.out.println("Bed is being made"); 14 | } 15 | 16 | public String getStyle(){ 17 | return style; 18 | } 19 | 20 | public int getPillows(){ 21 | return pillows; 22 | } 23 | 24 | public int getHeight(){ 25 | return height; 26 | } 27 | 28 | public int getSheets(){ 29 | return sheets; 30 | } 31 | 32 | public int getQuilt(){ 33 | return quilt; 34 | } 35 | } -------------------------------------------------------------------------------- /Coding Exercises 37 - Composition/Bedroom.java: -------------------------------------------------------------------------------- 1 | public class Bedroom { 2 | private String name; 3 | private Wall wall1, wall2, wall3, wall4; 4 | private Ceiling ceiling; 5 | private Bed bed; 6 | private Lamp lamp; 7 | 8 | public Bedroom(String name, Wall wall1, Wall wall2, Wall wall3, Wall wall4, Ceiling ceiling, Bed bed, Lamp lamp){ 9 | this.name = name; 10 | this.wall1 = wall1; 11 | this.wall2 = wall2; 12 | this.wall3 = wall3; 13 | this.wall4 = wall4; 14 | this.ceiling = ceiling; 15 | this.bed = bed; 16 | this.lamp = lamp; 17 | } 18 | 19 | public Lamp getLamp(){ 20 | return lamp; 21 | } 22 | 23 | public void makeBed(){ 24 | System.out.println("The bed is being made"); 25 | bed.make(); 26 | } 27 | } -------------------------------------------------------------------------------- /Coding Exercises 37 - Composition/Ceiling.java: -------------------------------------------------------------------------------- 1 | public class Ceiling { 2 | private int height, paintedColor; 3 | 4 | public Ceiling(int height, int paintedColor){ 5 | this.height = height; 6 | this.paintedColor = paintedColor; 7 | } 8 | 9 | public int getHeight(){ 10 | return height; 11 | } 12 | 13 | public int getPaintedColor(){ 14 | return paintedColor; 15 | } 16 | } -------------------------------------------------------------------------------- /Coding Exercises 37 - Composition/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("The Lamp is being turned 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 | } -------------------------------------------------------------------------------- /Coding Exercises 37 - Composition/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 | } -------------------------------------------------------------------------------- /Coding Exercises 38 - Encapsulation/Printer.java: -------------------------------------------------------------------------------- 1 | public class Printer { 2 | private int tonerLevel, pagesPrinted; 3 | private boolean duplex; 4 | 5 | public Printer(int tonerLevel, boolean duplex){ 6 | if(tonerLevel>-1 || tonerLevel<=100){ 7 | this.tonerLevel = tonerLevel; 8 | }else{ 9 | this.tonerLevel = -1; 10 | } 11 | 12 | this.duplex = duplex; 13 | 14 | this.pagesPrinted = 0; 15 | } 16 | 17 | public int addToner(int tonerAmount){ 18 | if(tonerAmount>0 && tonerAmount<=100){ 19 | if((tonerLevel + tonerAmount) > 100){ 20 | return -1; 21 | } 22 | tonerLevel += tonerAmount; 23 | return tonerLevel; 24 | 25 | }else{ 26 | return -1; 27 | } 28 | 29 | } 30 | 31 | public int printPages(int pages){ 32 | int pagesToPrint = pages; 33 | 34 | if(duplex){ 35 | pagesToPrint = (pages/2)+(pages%2); 36 | } 37 | this.pagesPrinted = pagesPrinted + pagesToPrint; 38 | return pagesToPrint; 39 | } 40 | 41 | public int getPagesPrinted(){ 42 | return pagesPrinted; 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /Coding Exercises 39 - Polymorphism/Car.java: -------------------------------------------------------------------------------- 1 | public class Car { 2 | private boolean engine; 3 | private int cylinders; 4 | private String name; 5 | private int wheels; 6 | 7 | public Car(int cylinders, String name){ 8 | this.cylinders = cylinders; 9 | this.name = name; 10 | this.engine = true; 11 | this.wheels = wheels; 12 | } 13 | 14 | public String startEngine(){ 15 | return ("Engine "+this.name+" is starting"); 16 | } 17 | 18 | public String accelerate(){ 19 | return ("Car "+this.name+" is accelerating"); 20 | } 21 | 22 | public String brake(){ 23 | return ("Car "+this.name+" is braking"); 24 | } 25 | 26 | public String getName(){ 27 | return name; 28 | } 29 | 30 | public int getCylinders(){ 31 | return cylinders; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Coding Exercises 39 - Polymorphism/Ford.java: -------------------------------------------------------------------------------- 1 | public class Ford extends Car{ 2 | public Ford(int cylinders,String name){ 3 | super(cylinders,name); 4 | } 5 | 6 | public String startEngine(){ 7 | return ("Engine "+getName()+" is starting"); 8 | } 9 | 10 | public String accelerate(){ 11 | return ("Car "+getName()+" is accelerating"); 12 | } 13 | 14 | public String brake(){ 15 | return ("Car "+getName()+" is braking"); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Coding Exercises 39 - Polymorphism/Holden.java: -------------------------------------------------------------------------------- 1 | public class HealthyBurger extends Hamburger{ 2 | private String healthyExtra1Name , healthyExtra2Name; 3 | private double healthyExtra1Price, healthyExtra2Price; 4 | 5 | public HealthyBurger(String meat, double price){ 6 | super("Healthy",meat,price,""); 7 | } 8 | 9 | public void addHealthyAddition1(String addition1Name, double addition1Price){ 10 | this.healthyExtra1Name = addition1Name; 11 | this.healthyExtra1Price = addition1Price; 12 | } 13 | 14 | public void addHealthyAddition2(String addition2Name, double addition2Price){ 15 | this.healthyExtra2Name = addition2Name; 16 | this.healthyExtra2Price = addition2Price; 17 | } 18 | 19 | public double itemizeHamburger() { 20 | double burgerPrice = super.itemizeHamburger(); 21 | 22 | if (this.healthyExtra1Name != null) { 23 | burgerPrice += this.healthyExtra1Price; 24 | System.out.println("Added " + this.healthyExtra1Name + " for an extra " + this.healthyExtra1Price); 25 | } 26 | 27 | if (this.healthyExtra2Name != null) { 28 | burgerPrice += this.healthyExtra2Price; 29 | System.out.println("Added " + this.healthyExtra2Name + " for an extra " + this.healthyExtra2Price); 30 | } 31 | 32 | return burgerPrice; 33 | } 34 | } -------------------------------------------------------------------------------- /Coding Exercises 39 - Polymorphism/Mitsubishi.java: -------------------------------------------------------------------------------- 1 | public class Mitsubishi extends Car { 2 | public Mitsubishi(int cylinders,String name){ 3 | super(cylinders,name); 4 | } 5 | 6 | public String startEngine(){ 7 | return ("Mitsubishi Engine "+getName()); 8 | } 9 | 10 | public String accelerate(){ 11 | return ("Mitsubishi Car "+getName()+" is accelerating"); 12 | } 13 | 14 | public String brake(){ 15 | return ("Mitsubishi Car "+getName()+" is braking"); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Coding Exercises 40 - Bill's Burgers/DeluxeBurger.java: -------------------------------------------------------------------------------- 1 | public class DeluxeBurger extends Hamburger{ 2 | public DeluxeBurger(){ 3 | super("basic","chicken",10.10,"white"); 4 | super.addHamburgerAddition1("Chips", 5); 5 | super.addHamburgerAddition2("Drink", 4); 6 | } 7 | 8 | public void addHamburgerAddition1(String addition1Name, double addition1Price){ 9 | System.out.println("Cannot add additional items to a deluxe burger."); 10 | } 11 | 12 | public void addHamburgerAddition2(String addition2Name, double addition2Price){ 13 | System.out.println("Cannot add additional items to a deluxe burger."); 14 | } 15 | 16 | public void addHamburgerAddition3(String addition3Name, double addition3Price){ 17 | System.out.println("Cannot add additional items to a deluxe burger."); 18 | } 19 | 20 | public void addHamburgerAddition4(String addition4Name, double addition4Price){ 21 | System.out.println("Cannot add additional items to a deluxe burger."); 22 | } 23 | } -------------------------------------------------------------------------------- /Coding Exercises 40 - Bill's Burgers/Exercise Description.txt: -------------------------------------------------------------------------------- 1 | Description: 2 | 3 | The purpose of this application is to help a company called Bill's Burgers manage the process of selling their hamburgers. And in order to match Bill's menu, you will need to create three(3) classes, Hamburger, DeluxeBurger, and HealthyBurger. 4 | 5 | For the base Hamburger class, there will need to be four variables to represent the four basic ingredients of the hamburger, name, meat, price, and breadRollType. The price variable should be of type double, while the other three are of type String. A constructor will be needed to accept these four values as parameters when creating a new hamburger. 6 | 7 | There will also need to be separate variables for four(4) possible additions to the hamburger. Those should be declared with these names: addition1Name, addition1Price, addition2Name, addition2Price, addition3Name, addition3Price, addition4Name, and addition4Price. The name variables should be of type String and the price variables should be of type double. 8 | 9 | Five(5) methods are also needed inside the Hamburger class. Four(4) for adding up to four additions to the hamburger and one(1) for printing out an itemized listing of the final hamburger with addons, if any, and the total price. Remember that a name and price must be accepted as parameters in the first four methods so that the price of the hamburger is adjusted accordingly. These methods should be named addHamburgerAddition1, addHamburgerAddition2, addHamburgerAddition3, addHamburgerAddition4, and itemizehamburger. The first four methods do not return values, but the last method does return the total price of the hamburger of type double, which includes the base price of the hamburger plus any additional items. 10 | 11 | For the second class, DeluxeBurger, there are no additional member variables, and the constructor accepts no parameters. Instead, the constructor creates a deluxe burger with all the fixings and chips and a drink for a base price of $19.10. The constructor can be configured in any way, as long as chips and drink are added for the total price just mentioned. In this class, the four(4) methods defined in the Hamburger class for including additional toppings must each be overridden so that a message is printed stating that no additional items can be added to a deluxe burger. 12 | 13 | And for the third class, HealthyBurger, there will be four(4) additional member variables called healthyExtra1Name, healthyExtra1Price, healthyExtra2Name, and healthyExtra2Price. The names are type String and the prices are type double. The constructor for this class accepts two(2) parameters for meat and price. Those are set in the constructor along with an appropriate name for the type of burger. 14 | 15 | Two methods, addHealthyAddition1 and addHealthyAddition2 should be created that each accept a name and price for the addition, allowing for up to two(2) addons to the basic healthy burger. And finally the itemizeHamburger method created in the Hamburger class should be overridden to generate a message appropriate to the type of burger along with any addons. The method also returns the total price of the healthy burger of type double. 16 | 17 | Example input: 18 | 19 | Hamburger hamburger = new Hamburger("Basic", "Sausage", 3.56, "White"); 20 | hamburger.addHamburgerAddition1("Tomato", 0.27); 21 | hamburger.addHamburgerAddition2("Lettuce", 0.75); 22 | hamburger.addHamburgerAddition3("Cheese", 1.13); 23 | System.out.println("Total Burger price is " + hamburger.itemizeHamburger()); 24 | 25 | HealthyBurger healthyBurger = new HealthyBurger("Bacon", 5.67); 26 | healthyBurger.addHamburgerAddition1("Egg", 5.43); 27 | healthyBurger.addHealthyAddition1("Lentils", 3.41); 28 | System.out.println("Total Healthy Burger price is " + healthyBurger.itemizeHamburger()); 29 | 30 | DeluxeBurger db = new DeluxeBurger(); 31 | db.addHamburgerAddition3("Should not do this", 50.53); 32 | System.out.println("Total Deluxe Burger price is " + db.itemizeHamburger()); 33 | 34 | Example output: 35 | 36 | Basic hamburger on a White roll with Sausage, price is 3.56 37 | Added Tomato for an extra 0.27 38 | Added Lettuce for an extra 0.75 39 | Added Cheese for an extra 1.13 40 | Total Burger price is 5.71 41 | Healthy hamburger on a Brown rye roll with Bacon, price is 5.67 42 | Added Egg for an extra 5.43 43 | Added Lentils for an extra 3.41 44 | Total Healthy Burger price is 14.51 45 | Cannot not add additional items to a deluxe burger 46 | Deluxe hamburger on a White roll with Sausage & Bacon, price is 14.54 47 | Added Chips for an extra 2.75 48 | Added Drink for an extra 1.81 49 | Total Deluxe Burger price is 19.10 50 | -------------------------------------------------------------------------------- /Coding Exercises 40 - Bill's Burgers/Hamburger.java: -------------------------------------------------------------------------------- 1 | public class Hamburger { 2 | private String name, meat, breadRollType; 3 | private double price; 4 | private String addition1Name, addition2Name, addition3Name, addition4Name; 5 | private double addition1Price, addition2Price, addition3Price, addition4Price; 6 | 7 | public Hamburger(String name,String meat,double price,String breadRollType){ 8 | this.name = name; 9 | this.meat = meat; 10 | this.price = price; 11 | this.breadRollType = breadRollType; 12 | } 13 | 14 | public void addHamburgerAddition1(String addition1Name, double addition1Price){ 15 | this.addition1Name = addition1Name; 16 | this.addition1Price = addition1Price; 17 | } 18 | 19 | public void addHamburgerAddition2(String addition2Name, double addition2Price){ 20 | this.addition2Name = addition2Name; 21 | this.addition2Price = addition2Price; 22 | } 23 | 24 | public void addHamburgerAddition3(String addition3Name, double addition3Price){ 25 | this.addition3Name = addition3Name; 26 | this.addition3Price = addition3Price; 27 | } 28 | 29 | public void addHamburgerAddition4(String addition4Name, double addition4Price){ 30 | this.addition4Name = addition4Name; 31 | this.addition4Price = addition4Price; 32 | } 33 | 34 | public double itemizeHamburger() { 35 | double burgerPrice = this.price; 36 | System.out.println(this.name + " hamburger on a " + this.breadRollType + " roll with " + this.meat + ", price is " + this.price); 37 | 38 | if (this.addition1Name != null) { 39 | burgerPrice += this.addition1Price; 40 | System.out.println("Added " + this.addition1Name + " for an extra " + this.addition1Price); 41 | } 42 | 43 | if (this.addition2Name != null) { 44 | burgerPrice += this.addition2Price; 45 | System.out.println("Added " + this.addition2Name + " for an extra " + this.addition2Price); 46 | } 47 | 48 | if (this.addition3Name != null) { 49 | burgerPrice += this.addition3Price; 50 | System.out.println("Added " + this.addition3Name + " for an extra " + this.addition3Price); 51 | } 52 | 53 | if (this.addition4Name != null) { 54 | burgerPrice += this.addition4Price; 55 | System.out.println("Added " + this.addition4Name + " for an extra " + this.addition4Price); 56 | } 57 | 58 | return burgerPrice; 59 | } 60 | } -------------------------------------------------------------------------------- /Coding Exercises 40 - Bill's Burgers/HealthyBurger.java: -------------------------------------------------------------------------------- 1 | public class HealthyBurger extends Hamburger{ 2 | private String healthyExtra1Name , healthyExtra2Name; 3 | private double healthyExtra1Price, healthyExtra2Price; 4 | 5 | public HealthyBurger(String meat, double price){ 6 | super("Healthy",meat,price,""); 7 | } 8 | 9 | public void addHealthyAddition1(String addition1Name, double addition1Price){ 10 | this.healthyExtra1Name = addition1Name; 11 | this.healthyExtra1Price = addition1Price; 12 | } 13 | 14 | public void addHealthyAddition2(String addition2Name, double addition2Price){ 15 | this.healthyExtra2Name = addition2Name; 16 | this.healthyExtra2Price = addition2Price; 17 | } 18 | 19 | public double itemizeHamburger() { 20 | double burgerPrice = super.itemizeHamburger(); 21 | 22 | if (this.healthyExtra1Name != null) { 23 | burgerPrice += this.healthyExtra1Price; 24 | System.out.println("Added " + this.healthyExtra1Name + " for an extra " + this.healthyExtra1Price); 25 | } 26 | 27 | if (this.healthyExtra2Name != null) { 28 | burgerPrice += this.healthyExtra2Price; 29 | System.out.println("Added " + this.healthyExtra2Name + " for an extra " + this.healthyExtra2Price); 30 | } 31 | 32 | return burgerPrice; 33 | } 34 | } -------------------------------------------------------------------------------- /Coding Exercises 41 - Sorted Array/Exercise Description.txt: -------------------------------------------------------------------------------- 1 | Create a program using arrays that sorts a list of integers in descending order. 2 | 3 | Descending order is highest value to lowest. 4 | 5 | In other words if the array had the values in it [106, 26, 81, 5, 15] your program should ultimately have an array with [106, 81, 26, 15, 5] in it. 6 | 7 | Set up the program so that the numbers to sort are read in from the keyboard (Scanner). 8 | 9 | Implement the following methods: 10 | 11 | getIntegers has one parameter of type int which is the size of the array. It returns an array of entered integers from the keyboard. 12 | 13 | printArray accepts an array and prints out the contents of the array. It should be printed in the following format: 14 | 15 | Element 0 contents 106 16 | Element 1 contents 81 17 | Element 2 contents 26 18 | Element 3 contents 15 19 | Element 4 contents 5 20 | 21 | sortIntegers accepts the unsorted array. It should sort the array and return a new array containing the sorted numbers. 22 | 23 | The scenario is: 24 | 25 | 1. getIntegers() is called. 26 | 27 | 2. The returned array from getIntegers() is then used to call sortIntegers(). 28 | 29 | 3. The returned array from sortIntegers() is then printed to the console. 30 | 31 | [Do not try and implement this. It is to give you an idea of how the methods will be used] 32 | 33 | TIP: you will have to figure out how to copy the array elements from the passed array into a new array and sort them and return the new sorted array. 34 | 35 | TIP: Instantiate (create) the Scanner object inside the method. 36 | 37 | TIP: Be extremely careful about spaces in the printed message. 38 | 39 | TIP: Make sure the Scanner class is imported. 40 | 41 | NOTE: All methods should be defined as public static NOT public. 42 | 43 | NOTE: Do not add a main method to the solution code. -------------------------------------------------------------------------------- /Coding Exercises 41 - Sorted Array/SortedArray.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | public class SortedArray { 3 | // write code here 4 | 5 | public static int[] getIntegers(int num){ 6 | Scanner scanner = new Scanner(System.in); 7 | int[] arr = new int[num]; 8 | for(int i=0;i "+contact.getPhoneNumber()); 71 | } 72 | } 73 | } -------------------------------------------------------------------------------- /Coding Exercises 45 - Banking/Bank.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | public class Bank { 3 | // write code here 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 | return false; 15 | } 16 | this.branches.add(new Branch(branchName)); 17 | return true; 18 | } 19 | 20 | public boolean addCustomer(String branchName, String customerName, double initialTrans){ 21 | Branch branch = findBranch(branchName); 22 | if(branch != null){ 23 | return branch.newCustomer(customerName,initialTrans); 24 | // return true; 25 | } 26 | return false; 27 | } 28 | public boolean addCustomerTransaction(String branchName, String customerName, double transaction){ 29 | Branch branch = findBranch(branchName); 30 | if(branch != null){ 31 | return branch.addCustomerTransaction(customerName,transaction); 32 | // return true; 33 | 34 | } 35 | return false; 36 | } 37 | 38 | private Branch findBranch(String branchName){ 39 | for(int i=0;i branchCustomers = branch.getCustomers(); 53 | for(int i=0;i transactions = branchCustomer.getTransactions(); 60 | for(int j=0;j customers; 6 | 7 | public Branch(String branchName){ 8 | this.name = branchName; 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 transaction){ 21 | Customer customer = findCustomer(customerName); 22 | if(customer == null){ 23 | this.customers.add(new Customer(customerName,transaction)); 24 | return true; 25 | } 26 | return false; 27 | } 28 | 29 | public boolean addCustomerTransaction(String customerName, double transaction){ 30 | 31 | Customer customer = findCustomer(customerName); 32 | if(customer != null){ 33 | customer.addTransaction(transaction); 34 | return true; 35 | } 36 | return false; 37 | } 38 | 39 | private Customer findCustomer(String customerName){ 40 | for(int i=0;i transactions; 6 | 7 | public Customer(String name,double transaction){ 8 | this.name = name; 9 | this.transactions = new ArrayList(); 10 | addTransaction(transaction); 11 | } 12 | 13 | public String getName(){ 14 | return name; 15 | } 16 | 17 | public ArrayList getTransactions(){ 18 | return transactions; 19 | } 20 | 21 | public void addTransaction(double transaction){ 22 | this.transactions.add(transaction); 23 | } 24 | } -------------------------------------------------------------------------------- /Coding Exercises 45 - Banking/Exercise Description.txt: -------------------------------------------------------------------------------- 1 | Your job is to create a simple banking application. 2 | 3 | Implement the following classes: 4 | 5 | 1.  Bank 6 | 7 | -  It has two fields, A String called name and an ArrayList that holds objects of type Branch called branches. 8 | 9 | -  A constructor that takes a String (name of the bank). It initialises name and instantiates branches. 10 | 11 | -  And five methods, they are (their functions are in their names): 12 | 13 |     -  addBranch(), has one parameter of type String (name of the branch) and returns a boolean. It returns true if the branch was added successfully or false otherwise. 14 | 15 |     -  addCustomer(), has three parameters of type String (name of the branch), String (name of the customer), double (initial transaction) and returns a boolean. It returns true if the customer was added successfully or false otherwise. 16 | 17 |     -  addCustomerTransaction(), has three parameters of type String (name of the branch), String (name of the customer), double (transaction) and returns a boolean. It returns true if the customers transaction was added successfully or false otherwise. 18 | 19 |     -  findBranch(), has one parameter of type String (name of the Branch) and returns a Branch. Return the Branch if it exists or null otherwise. 20 | 21 |     -  listCustomers(), has two parameters of type String (name of the Branch), boolean (print transactions) and returns a boolean. Return true if the branch exists or false otherwise. This method prints out a list of customers. 22 | 23 | → TEST CODE 24 | 25 | Bank bank = new Bank("National Australia Bank"); 26 | 27 | bank.addBranch("Adelaide"); 28 | 29 | bank.addCustomer("Adelaide", "Tim", 50.05); 30 | bank.addCustomer("Adelaide", "Mike", 175.34); 31 | bank.addCustomer("Adelaide", "Percy", 220.12); 32 | 33 | bank.addCustomerTransaction("Adelaide", "Tim", 44.22); 34 | bank.addCustomerTransaction("Adelaide", "Tim", 12.44); 35 | bank.addCustomerTransaction("Adelaide", "Mike", 1.65); 36 | 37 | bank.listCustomers("Adelaide", true); 38 | 39 | → OUTPUT 40 | 41 | The list of customers should be printed out in the following format if boolean parameter is true: 42 | 43 | Customer details for branch Adelaide 44 | Customer: Tim[1] 45 | Transactions 46 | [1] Amount 50.05 47 | [2] Amount 44.22 48 | [3] Amount 12.44 49 | Customer: Mike[2] 50 | Transactions 51 | [1] Amount 175.34 52 | [2] Amount 1.65 53 | Customer: Percy[3] 54 | Transactions 55 | [1] Amount 220.12 56 | 57 | and if false, only the customers - no transactions: 58 | 59 | bank.listCustomers("Adelaide", false); 60 | 61 | Customer details for branch Adelaide 62 | Customer: Tim[1] 63 | Customer: Mike[2] 64 | Customer: Percy[3] 65 | 66 | 2.  Branch 67 | 68 |     -  It has two fields, A String called name and an ArrayList that holds objects of type Customer called customers. 69 | 70 |     -  A constructor that takes a String (name of the branch). It initialises name and instantiates customers. 71 | 72 |     -  And five methods, they are (their functions are in their names): 73 | 74 |         -  getName(), getter for name. 75 | 76 |         -  getCustomers(), getter for customers. 77 | 78 |         -  newCustomer(), has two parameters of type String (name of customer), double (initial transaction) and returns a boolean. Returns true if the customer was added successfully or false otherwise. 79 | 80 |         -  addCustomerTransaction(), has two parameters of type String (name of customer), double (transaction) and returns a boolean. Returns true if the customers transaction was added successfully or false otherwise. 81 | 82 |         -  findCustomer(), has one parameter of type String (name of customer) and returns a Customer. Return the Customer if they exist, null otherwise. 83 | 84 | 3.  Customer 85 | 86 |     -  It has two fields, A String called name and an ArrayList that holds objects of type Double called transactions. 87 | 88 |     -  A constructor that takes a  String (name of customer) and a double (initial transaction). It initialises name and instantiates transactions. 89 | 90 |     -  And three methods, they are (their functions are in their names): 91 | 92 |         -  getName(), getter for name. 93 | 94 |         -  getTransactions(), getter for transactions. 95 | 96 |         -  addTransaction(), has one parameter of type double (transaction) and doesn't return anything. 97 | 98 | TIP:  In Bank, use the findBranch() method in each of the other four methods to validate a branch. Do the same thing in Branch with findCustomer() - except for the two getters. 99 | 100 | TIP:  In Customer, think about what else you need to do in the constructor when you instantiate a Customer object. 101 | 102 | TIP:  Think about what methods you need to call from another class when implementing a method. 103 | 104 | TIP:  Be extremely careful with the spelling of the names of the fields, constructors and methods. 105 | 106 | TIP:  Be extremely careful about spaces and spelling in the printed output. 107 | 108 | NOTE:  All transactions are deposits (no withdraws/balances). 109 | 110 | NOTE:  All fields are private. 111 | 112 | NOTE:  All constructors are public. 113 | 114 | NOTE:  All methods are public (except for findBranch() and findCustomer() which are private). 115 | 116 | NOTE:  There are no static members. 117 | 118 | NOTE:  Do not add a main method to the solution code. 119 | 120 | NOTE:  If you get an error from the Evaluate class, it's most likely the constructor. Check if you've added a constructor or if the constructor has the right arguments. -------------------------------------------------------------------------------- /Coding Exercises 46 - Playlist/Album.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.LinkedList; 3 | 4 | public class Album { 5 | // write code here 6 | private String name, 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 boolean addSong(String title, double duration){ 16 | if(findSong(title) == null){ 17 | songs.add(new Song(title,duration)); 18 | return true; 19 | } 20 | return false; 21 | } 22 | 23 | private Song findSong(String title){ 24 | for(int i=0;i playlist){ 34 | int count = track - 1; 35 | if (count >= 0 && count <= songs.size()) { 36 | playlist.add(songs.get(count)); 37 | return true; 38 | } 39 | return false; 40 | } 41 | 42 | public boolean addToPlayList(String title,LinkedList playlist){ 43 | Song song = findSong(title); 44 | if(song != null){ 45 | playlist.add(song); 46 | return true; 47 | } 48 | return false; 49 | } 50 | } -------------------------------------------------------------------------------- /Coding Exercises 46 - Playlist/Exercise Description.txt: -------------------------------------------------------------------------------- 1 | Create a program that implements a playlist of songs. 2 | 3 | To start you off, implement the following classes: 4 | 5 | 1.  Album 6 | 7 |     -  It has three fields, two Strings called name and artist, and an ArrayList that holds objects of type Song called songs. 8 | 9 |     -  A constructor that accepts two Strings (name of the album and artist). It initialises the fields and instantiates songs. 10 | 11 |     -  And three methods, they are: 12 | 13 |         -  addSong(), has two parameters of type String (title of song), double (duration of song) and returns a boolean. Returns true if the song was added successfully or false otherwise. 14 | 15 |         -  findSong(), has one parameter of type String (title of song) and returns a Song. Returns the Song if it exists, null if it doesn't exists. 16 | 17 |         -  addToPlayList(), has two parameters of type int (track number of song in album) and LinkedList (the playlist) that holds objects of type Song, and returns a boolean. Returns true if it exists and it was added successfully using the track number, or false otherwise. 18 | 19 |         -  addToPlayList(), has two parameters of type String (title of song) and LinkedList (the playlist) that holds objects of type Song, and returns a boolean. Returns true if it exists and it was added successfully using the name of the song, or false otherwise. 20 | 21 | 2.  Song 22 | 23 |     -   It has two fields, a String called title and a double called duration. 24 | 25 |     -  A constructor that accepts a String (title of the song) and a double (duration of the song). It initialises title and duration. 26 | 27 |     -  And two methods, they are: 28 | 29 |         -  getTitle(), getter for title. 30 | 31 |         -  toString(), Songs overriding toString method. Returns a String in the following format: "title: duration" 32 | 33 | ->  SAMPLE INPUT 34 | 35 | ArrayList albums = new ArrayList<>(); 36 | 37 | Album album = new Album("Stormbringer", "Deep Purple"); 38 | album.addSong("Stormbringer", 4.6); 39 | album.addSong("Love don't mean a thing", 4.22); 40 | album.addSong("Holy man", 4.3); 41 | album.addSong("Hold on", 5.6); 42 | album.addSong("Lady double dealer", 3.21); 43 | album.addSong("You can't do it right", 6.23); 44 | album.addSong("High ball shooter", 4.27); 45 | album.addSong("The gypsy", 4.2); 46 | album.addSong("Soldier of fortune", 3.13); 47 | albums.add(album); 48 | 49 | album = new Album("For those about to rock", "AC/DC"); 50 | album.addSong("For those about to rock", 5.44); 51 | album.addSong("I put the finger on you", 3.25); 52 | album.addSong("Lets go", 3.45); 53 | album.addSong("Inject the venom", 3.33); 54 | album.addSong("Snowballed", 4.51); 55 | album.addSong("Evil walks", 3.45); 56 | album.addSong("C.O.D.", 5.25); 57 | album.addSong("Breaking the rules", 5.32); 58 | album.addSong("Night of the long knives", 5.12); 59 | albums.add(album); 60 | 61 | LinkedList playList = new LinkedList(); 62 | albums.get(0).addToPlayList("You can't do it right", playList); 63 | albums.get(0).addToPlayList("Holy man", playList); 64 | albums.get(0).addToPlayList("Speed king", playList); // Does not exist 65 | albums.get(0).addToPlayList(9, playList); 66 | albums.get(1).addToPlayList(3, playList); 67 | albums.get(1).addToPlayList(2, playList); 68 | albums.get(1).addToPlayList(24, playList); // There is no track 24 69 | 70 | TIP:  In Album, use the findSong() method in addSong() and addToPlayList(String, LinkedList) to check if a song exists before proceeding. 71 | 72 | TIP:  Be extremely careful with the spelling of the names of the fields, constructors and methods. 73 | 74 | TIP:  Be extremely careful about spaces and spelling in the returned String from the toString() method. 75 | 76 | NOTE:  All fields are private. 77 | 78 | NOTE:  All constructors are public. 79 | 80 | NOTE:  All methods are public (except for findSong() which is private). 81 | 82 | NOTE:  There are no static members. 83 | 84 | NOTE:  Do not add a main method to the solution code. 85 | 86 | NOTE:  If you get an error from the Evaluate class, it's most likely the constructor. Check if you've added a constructor or if the constructor has the right arguments. -------------------------------------------------------------------------------- /Coding Exercises 46 - Playlist/Song.java: -------------------------------------------------------------------------------- 1 | public class Song { 2 | // write code here 3 | private String title; 4 | private double duration; 5 | 6 | public Song(String title, double duration){ 7 | this.title = title; 8 | this.duration = duration; 9 | } 10 | 11 | public String getTitle(){ 12 | return title; 13 | } 14 | 15 | public String toString(){ 16 | return (""+title+": "+duration); 17 | } 18 | } -------------------------------------------------------------------------------- /Coding Exercises 47 - Interface/Exercise Description.txt: -------------------------------------------------------------------------------- 1 | Create a simple interface that allows an object to be saved to some sort of storage medium. 2 | 3 | Implement the following: 4 | 5 | 1.  ISaveable (interface) 6 | 7 |     -  It has two methods: 8 | 9 |         -  write(), takes no arguments and returns a List containing objects of type String. 10 | 11 |         -  read(), takes a List of type String and doesn't return anything. 12 | 13 | 2.  Player (class) 14 | 15 |     -  It has four fields. Two Strings called name and weapon. Two ints called hitPoints and strength. 16 | 17 |     -  A constructor that accepts a String (name) and two ints (hitPoints and strength). It initialises name, hitPoints and strength with the newly passed in values. It initialises weapon with the default weapon "Sword". 18 | 19 |     -  And eleven methods: 20 | 21 |         -  Getters and setters for all four fields. 22 | 23 |         -  write(), same as interface. Return a List of the fields in the order they appear in toString(). 24 | 25 |         -  read(), same as interface. Store the values in the List, in the order they appear in toString(). Make sure the List is not null and the size() is greater than 0 before storing the values. 26 | 27 |         -  toString(), Players overriding toString() method. It takes no arguments and returns a String in the following format: 28 | 29 | Player{name='Tim', hitPoints=10, strength=15, weapon='Sword'} 30 | 31 | 3.  Monster (class) 32 | 33 |     -  It has three fields. One String called name and Two ints called hitPoints and strength. 34 | 35 |     -  A constructor that accepts a String (name) and two ints (hitPoints and strength). It initialises name, hitPoints and strength with the newly passed in values. 36 | 37 |     -  And six methods: 38 | 39 |         -  Only getters for the three fields. 40 | 41 |         -  write(), same as interface. Return a List of the fields in the order they appear in toString(). 42 | 43 |         -  read(), same as interface. Store the values in the List, in the order they appear in toString(). Make sure the List is not null and the size() is greater than 0 before storing the values. 44 | 45 |         -  toString(), Monsters overriding toString() method. It takes no arguments and returns a String in the following format: 46 | 47 | Monster{name='Werewolf', hitPoints=20, strength=40} 48 | 49 | TIP:  Player and Monster need to implement ISaveable. 50 | 51 | TIP:  Be extremely careful with the spelling of the names of the fields, constructors and methods. 52 | 53 | TIP:  Be extremely careful about spaces and spelling in the returned String from the toString() method. 54 | 55 | NOTE:  All fields are private. 56 | 57 | NOTE:  Both constructors are public. 58 | 59 | NOTE:  All methods are public. 60 | 61 | NOTE:  There are no static members. 62 | 63 | NOTE:  Do not add a main method to the solution code. 64 | 65 | NOTE:  If you get an error from the Evaluate class, it's most likely the constructor. Check if you've added a constructor or if the constructor has the right arguments. -------------------------------------------------------------------------------- /Coding Exercises 47 - Interface/ISaveable.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | import java.util.ArrayList; 3 | 4 | public interface ISaveable { 5 | // write code here 6 | List write(); 7 | 8 | void read(List lst); 9 | } 10 | -------------------------------------------------------------------------------- /Coding Exercises 47 - Interface/Monster.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | import java.util.ArrayList; 3 | 4 | public class Monster implements ISaveable{ 5 | // write code here 6 | private String name; 7 | private int hitPoints, strength; 8 | 9 | public Monster(String name, int hitPoints, int strength){ 10 | this.name = name; 11 | this.hitPoints = hitPoints; 12 | this.strength = strength; 13 | } 14 | 15 | public String getName(){ 16 | return name; 17 | } 18 | 19 | public int getHitPoints(){ 20 | return hitPoints; 21 | } 22 | 23 | public int getStrength(){ 24 | return strength; 25 | } 26 | 27 | @Override 28 | public List write(){ 29 | List values = new ArrayList(); 30 | values.add(0,this.name); 31 | values.add(1,""+this.hitPoints); 32 | values.add(2,""+this.strength); 33 | return values; 34 | } 35 | 36 | @Override 37 | public void read(List values){ 38 | if(values != null && values.size()>0){ 39 | this.name = values.get(0); 40 | this.hitPoints = Integer.parseInt(values.get(1)); 41 | this.strength = Integer.parseInt(values.get(2)); 42 | } 43 | } 44 | 45 | @Override 46 | public String toString(){ 47 | return ("Monster{name='"+this.name+"', hitPoints="+this.hitPoints+", strength="+this.strength+"}"); 48 | } 49 | } -------------------------------------------------------------------------------- /Coding Exercises 47 - Interface/Player.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | import java.util.ArrayList; 3 | 4 | public class Player implements ISaveable{ 5 | // write code here 6 | private String name, weapon; 7 | private int hitPoints, strength; 8 | 9 | public Player(String name, int hitPoints, int strength){ 10 | this.name = name; 11 | this.hitPoints = hitPoints; 12 | this.strength = strength; 13 | this.weapon = "Sword"; 14 | } 15 | 16 | public String getName(){ 17 | return name; 18 | } 19 | 20 | public void setName(String name){ 21 | this.name = name; 22 | } 23 | 24 | public String getWeapon(){ 25 | return weapon; 26 | } 27 | 28 | public void setWeapon(String weapon){ 29 | this.weapon = weapon; 30 | } 31 | 32 | public int getStrength(){ 33 | return strength; 34 | } 35 | 36 | public void setStrength(int strength){ 37 | this.strength = strength; 38 | } 39 | 40 | public int getHitPoints(){ 41 | return hitPoints; 42 | } 43 | 44 | public void setHitPoints(int hitPoints){ 45 | this.hitPoints = hitPoints; 46 | } 47 | 48 | @Override 49 | public List write(){ 50 | List values = new ArrayList(); 51 | values.add(0,this.name); 52 | values.add(1,""+this.hitPoints); 53 | values.add(2,""+this.strength); 54 | values.add(3,this.weapon); 55 | return values; 56 | } 57 | 58 | @Override 59 | public void read(List values){ 60 | if(values != null && values.size()>0){ 61 | this.name = values.get(0); 62 | this.hitPoints = Integer.parseInt(values.get(1)); 63 | this.strength = Integer.parseInt(values.get(2)); 64 | this.weapon = values.get(3); 65 | } 66 | } 67 | 68 | @Override 69 | public String toString(){ 70 | return ("Player{name='"+this.name+"', hitPoints="+this.hitPoints+", strength="+this.strength+", weapon='"+this.weapon+"'}"); 71 | } 72 | } -------------------------------------------------------------------------------- /Coding Exercises 48 - Playlist - Inner Class/Album.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.LinkedList; 3 | 4 | public class Album { 5 | // write code here 6 | private String name, 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 boolean addSong(String title, double duration){ 16 | return this.songs.add(new Song(title,duration)); 17 | } 18 | 19 | public boolean addToPlayList(int track,LinkedList playlist){ 20 | Song checkSong = songs.findSong(track); 21 | if(checkSong != null){ 22 | playlist.add(checkSong); 23 | return true; 24 | } 25 | return false; 26 | } 27 | 28 | public boolean addToPlayList(String title,LinkedList playlist){ 29 | Song checkSong = songs.findSong(title); 30 | if(checkSong != null){ 31 | playlist.add(checkSong); 32 | return true; 33 | } 34 | return false; 35 | } 36 | 37 | public static class SongList{ 38 | private ArrayList songs; 39 | 40 | 41 | private SongList(){ 42 | songs = new ArrayList(); 43 | } 44 | 45 | private boolean add(Song song){ 46 | if(songs.contains(song)){ 47 | return false; 48 | } 49 | songs.add(song); 50 | return true; 51 | } 52 | 53 | private Song findSong(String title){ 54 | for(int i=0;i0 && count playList = new LinkedList(); 46 | albums.get(0).addToPlayList("You can't do it right", playList); 47 | albums.get(0).addToPlayList("Holy man", playList); 48 | albums.get(0).addToPlayList("Speed king", playList); // Does not exist 49 | albums.get(0).addToPlayList(9, playList); 50 | albums.get(1).addToPlayList(8, playList); 51 | albums.get(1).addToPlayList(3, playList); 52 | albums.get(1).addToPlayList(2, playList); 53 | albums.get(1).addToPlayList(24, playList); // There is no track 24 54 | 55 | Example output: 56 | 57 | The song Speed king is not in this album 58 | This album does not have a track 24 59 | -------------------------------------------------------------------------------- /Coding Exercises 48 - Playlist - Inner Class/Song.java: -------------------------------------------------------------------------------- 1 | public class Song { 2 | // write code here 3 | private String title; 4 | private double duration; 5 | 6 | public Song(String title, double duration){ 7 | this.title = title; 8 | this.duration = duration; 9 | } 10 | 11 | public String getTitle(){ 12 | return title; 13 | } 14 | 15 | public String toString(){ 16 | return (""+title+": "+duration); 17 | } 18 | } -------------------------------------------------------------------------------- /Coding Exercises 49 - Abstract Class/Exercise Description.txt: -------------------------------------------------------------------------------- 1 | Create an abstract class to define items that can be stored in a tree. 2 | 3 | Implement the following: 4 | 5 | 1.  ListItem (abstract class) 6 | 7 |     -  It has three protected fields. Two ListItems called rightLink and leftLink, and an Object called value. 8 | 9 |     -  A constructor that takes an Object and initialises the field value with the parameter that was passed in. 10 | 11 |     -  And seven methods: 12 | 13 |         -  next(), setNext(), previous(), setPrevious() and compareTo() which are package-private and abstract (see child class for declaration). 14 | 15 |         -  getValue(), takes no parameters and returns its value. 16 | 17 |         -  setValue(), takes an Object and assigns it to value. 18 | 19 |         20 | 21 | 2.  Node (concrete class) 22 | 23 |     -  It extends ListItem. 24 | 25 |     -  It has a constructor that takes an Object, then calls its parent constructor with the parameter that was passed in. 26 | 27 |     -  And five methods which are package-private: 28 | 29 |         -  next(), takes no parameters and returns the ListItem to its right. 30 | 31 |         -  setNext(), takes a ListItem and sets it as its rightLink, then it returns rightLink. 32 | 33 |         -  previous(), takes no parameters and returns the ListItem to its left. 34 | 35 |         -  setPrevious(), takes a ListItem and sets it as its leftLink, then it returns leftLink. 36 | 37 |         -  compareTo(), takes a ListItem and compares it to the ListItem that called this method. Use value from ListItem for comparison. If this value is greater than the value that was passed in, then it should return a number greater than zero. If vice versa, then it should return a number less than zero, and zero if equal. 38 | 39 | 3.  MyLinkedList (concrete class) 40 | 41 |     -  It implements NodeList. 42 | 43 |     -  It has one field of type ListItem called root. 44 | 45 |     -  A constructor that takes a ListItem and initialises the field root with the newly passed in parameter. 46 | 47 |     -  And four methods: 48 | 49 |         -  getRoot(), getter for root. 50 | 51 |         -  addItem(), takes a ListItem and returns true if it was added successfully or false otherwise. If the item is already present, it doesn't get added. Use compareTo() to place the item in its proper order. 52 | 53 |         -  removeItem(), takes a ListItem and returns true if it was removed successfully or false otherwise. 54 | 55 |         -  traverse(), takes the root as an argument and does not return anything. If the root is null it prints out: The list is empty, otherwise print each value on a separate line. 56 | 57 | 4.  NodeList (interface) 58 | 59 |     -  It has four methods: 60 | 61 |         -  getRoot(), addItem(), removeItem() and traverse() which are package-private and abstract (see child class for declaration). 62 | 63 | 5.  SearchTree (concrete class) 64 | 65 |     -  It implements NodeList. 66 | 67 |     -  It has one field of type ListItem called root. 68 | 69 |     -  A constructor that takes a ListItem and initialises the field root with the newly passed in parameter. 70 | 71 |     -  And five methods: 72 | 73 |         -  getRoot(), getter for root. 74 | 75 |         -  addItem(), same as MyLinkedList. 76 | 77 |         -  removeItem(), same as MyLinkedList. 78 | 79 |         -  performRemoval(), takes two ListItems, the item to be removed and its parent. It doesn't return anything and is declared as private. Call this method from removeItem() when the item is found. 80 | 81 |         -  traverse(), takes the root as an argument and does not return anything. It uses recursion to visit all the branches in the tree (Inorder). Print each value on a seperate line. 82 | 83 | TIP:  The rules for adding an item to the linked tree are:  84 | 85 |           If the head of the tree is null, make the head refer to the item to be added. 86 | 87 |           If the item to be added is less than the current item in the tree, add the item before the current item (i.e., make the previous item's "next" refer to the new item, and the new item's "next" refer to the current item). 88 | 89 |           If the item to be added is greater than the current item, move onto the next item and compare again (if there is no next item, then that is where the new item belongs). 90 | 91 | TIP:  When adding items to a Binary Search Tree, if the item to be added is less than the current item - then move to the left. 92 | 93 |          If it is greater than the current item - then move to the right. 94 | 95 |          The new item is added when an attempt to move in the required direction would involve following a null reference. 96 | 97 |          Once again, duplicates are not allowed. 98 | 99 | TIP:  Inorder = print the previous node, then the parent node, and then the next node (left -> node -> right). 100 | 101 | TIP:  Be extremely careful with the spelling of the names of the fields, constructors and methods. 102 | 103 | TIP:  Be extremely careful about spaces and spelling in the printed output from the traverse() method. 104 | 105 | NOTE:  All fields are private (unless stated otherwise). 106 | 107 | NOTE:  All constructors are public. 108 | 109 | NOTE:  All methods are public (unless stated otherwise). 110 | 111 | NOTE:  Do not add a main method to the solution code. -------------------------------------------------------------------------------- /Coding Exercises 49 - Abstract Class/ListItem.java: -------------------------------------------------------------------------------- 1 | public abstract class ListItem { 2 | // write code here 3 | protected ListItem rightLink, leftLink; 4 | protected Object value; 5 | 6 | public ListItem(Object value){ 7 | this.value = value; 8 | } 9 | 10 | abstract ListItem next(); 11 | abstract ListItem setNext(ListItem rightLink); 12 | abstract ListItem previous(); 13 | abstract ListItem setPrevious(ListItem leftLink); 14 | abstract int compareTo(ListItem item); 15 | 16 | public Object getValue(){ 17 | return value; 18 | } 19 | 20 | public void setValue(Object value){ 21 | this.value = value; 22 | } 23 | } -------------------------------------------------------------------------------- /Coding Exercises 49 - Abstract Class/MyLinkedList.java: -------------------------------------------------------------------------------- 1 | public class MyLinkedList implements NodeList{ 2 | // write code here 3 | private ListItem root = null; 4 | 5 | public MyLinkedList(ListItem root) { 6 | this.root = root; 7 | } 8 | 9 | @Override 10 | public ListItem getRoot() { 11 | return this.root; 12 | } 13 | 14 | @Override 15 | public boolean addItem(ListItem newItem) { 16 | if (this.root == null) { 17 | this.root = newItem; 18 | return true; 19 | } 20 | 21 | ListItem currentItem = this.root; 22 | while (currentItem != null) { 23 | int comparison = (currentItem.compareTo(newItem)); 24 | if (comparison < 0) { 25 | if (currentItem.next() != null) { 26 | currentItem = currentItem.next(); 27 | } else { 28 | currentItem.setNext(newItem).setPrevious(currentItem); 29 | return true; 30 | } 31 | } else if (comparison > 0) { 32 | if (currentItem.previous() != null) { 33 | currentItem.previous().setNext(newItem).setPrevious(currentItem.previous()); 34 | newItem.setNext(currentItem).setPrevious(newItem); 35 | } else { 36 | newItem.setNext(this.root).setPrevious(newItem); 37 | this.root = newItem; 38 | } 39 | return true; 40 | } else { 41 | System.out.println(newItem.getValue() + " is already present, not added."); 42 | return false; 43 | } 44 | } 45 | return false; 46 | } 47 | 48 | @Override 49 | public boolean removeItem(ListItem item) { 50 | if (item != null) { 51 | System.out.println("Deleting item " + item.getValue()); 52 | } 53 | 54 | ListItem currentItem = this.root; 55 | while (currentItem != null) { 56 | int comparison = currentItem.compareTo(item); 57 | if (comparison == 0) { 58 | if (currentItem == this.root) { 59 | this.root = currentItem.next(); 60 | } else { 61 | currentItem.previous().setNext(currentItem.next()); 62 | if (currentItem.next() != null) { 63 | currentItem.next().setPrevious(currentItem.previous()); 64 | } 65 | } 66 | return true; 67 | } else if (comparison < 0) { 68 | currentItem = currentItem.next(); 69 | } else { // comparison > 0 70 | return false; 71 | } 72 | } 73 | return false; 74 | } 75 | 76 | @Override 77 | public void traverse(ListItem root) { 78 | if (root == null) { 79 | System.out.println("The list is empty"); 80 | }else { 81 | while (root != null) { 82 | System.out.println(root.getValue()); 83 | root = root.next(); 84 | } 85 | } 86 | } 87 | } -------------------------------------------------------------------------------- /Coding Exercises 49 - Abstract Class/Node.java: -------------------------------------------------------------------------------- 1 | public class Node extends ListItem{ 2 | // write code here 3 | public Node(Object value) { 4 | super(value); 5 | } 6 | 7 | @Override 8 | ListItem next() { 9 | return this.rightLink; 10 | } 11 | 12 | @Override 13 | ListItem setNext(ListItem item) { 14 | this.rightLink = item; 15 | return this.rightLink; 16 | } 17 | 18 | @Override 19 | ListItem previous() { 20 | return this.leftLink; 21 | } 22 | 23 | @Override 24 | ListItem setPrevious(ListItem item) { 25 | this.leftLink=item; 26 | return this.leftLink; 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 | } -------------------------------------------------------------------------------- /Coding Exercises 49 - Abstract Class/NodeList.java: -------------------------------------------------------------------------------- 1 | public interface NodeList { 2 | // write code here 3 | ListItem getRoot(); 4 | boolean addItem(ListItem item); 5 | boolean removeItem(ListItem item); 6 | void traverse(ListItem root); 7 | } -------------------------------------------------------------------------------- /Coding Exercises 49 - Abstract Class/SearchTree.java: -------------------------------------------------------------------------------- 1 | public class SearchTree implements NodeList{ 2 | // write code here 3 | private ListItem root = null; 4 | 5 | public SearchTree(ListItem root) { 6 | this.root = root; 7 | } 8 | 9 | @Override 10 | public ListItem getRoot() { 11 | return this.root; 12 | } 13 | 14 | @Override 15 | public boolean addItem(ListItem newItem) { 16 | if (this.root == null) { 17 | this.root = newItem; 18 | return true; 19 | } 20 | 21 | ListItem currentItem = this.root; 22 | while (currentItem != null) { 23 | int comparison = (currentItem.compareTo(newItem)); 24 | if (comparison < 0) { 25 | if (currentItem.next() != null) { 26 | currentItem = currentItem.next(); 27 | } else { 28 | currentItem.setNext(newItem); 29 | return true; 30 | } 31 | } else if (comparison > 0) { 32 | if (currentItem.previous() != null) { 33 | currentItem = currentItem.previous(); 34 | } else { 35 | currentItem.setPrevious(newItem); 36 | return true; 37 | } 38 | } else { 39 | System.out.println(newItem.getValue() + " is already present"); 40 | return false; 41 | } 42 | } 43 | return false; 44 | } 45 | 46 | @Override 47 | public boolean removeItem(ListItem item) { 48 | if (item != null) { 49 | System.out.println("Deleting item " + item.getValue()); 50 | } 51 | ListItem currentItem = this.root; 52 | ListItem parentItem = currentItem; 53 | 54 | while (currentItem != null) { 55 | int comparison = (currentItem.compareTo(item)); 56 | if (comparison < 0) { 57 | parentItem = currentItem; 58 | currentItem = currentItem.next(); 59 | } else if (comparison > 0) { 60 | parentItem = currentItem; 61 | currentItem = currentItem.previous(); 62 | } else { 63 | // equal: we've found the item so remove it 64 | performRemoval(currentItem, parentItem); 65 | return true; 66 | } 67 | } 68 | return false; 69 | } 70 | 71 | 72 | private void performRemoval(ListItem item, ListItem parent) { 73 | if (item.next() == null) { 74 | if (parent.next() == item) { 75 | parent.setNext(item.previous()); 76 | } else if (parent.previous() == item) { 77 | parent.setPrevious(item.previous()); 78 | } else { 79 | this.root = item.previous(); 80 | } 81 | } else if (item.previous() == null) { 82 | if (parent.next() == item) { 83 | parent.setNext(item.next()); 84 | } else if (parent.previous() == item) { 85 | parent.setPrevious(item.next()); 86 | } else { 87 | this.root = item.next(); 88 | } 89 | } else { 90 | 91 | ListItem current = item.next(); 92 | ListItem leftmostParent = item; 93 | while (current.previous() != null) { 94 | leftmostParent = current; 95 | current = current.previous(); 96 | } 97 | item.setValue(current.getValue()); 98 | if (leftmostParent == item) { 99 | item.setNext(current.next()); 100 | } else { 101 | leftmostParent.setPrevious(current.next()); 102 | } 103 | } 104 | } 105 | 106 | @Override 107 | public void traverse(ListItem root) { 108 | if (root != null) { 109 | traverse(root.previous()); 110 | System.out.println(root.getValue()); 111 | traverse(root.next()); 112 | } 113 | } 114 | } -------------------------------------------------------------------------------- /Coding Exercises 50 - Adventure Game/Exercise Description.txt: -------------------------------------------------------------------------------- 1 | Implement the command() method in the Main class to allow players to type full words, or phrases, then move to the correct location based upon their input. 2 | 3 | The player should be able to type commands such as "Go West", "run South", "I need to Quit this game" or just "East" and the program will move to the appropriate location if there is one. 4 | 5 | The console should display its current location, then it should prompt the user with: "Available exits are ", and its available exits. For example: 6 | 7 | You are standing at the end of a road before a small brick building 8 | 9 | Available exits are Q, S, E, N, W, 10 | 11 | A move in a valid direction should print (keep in mind N, S, E and W variants - showing N below): 12 | 13 | You are standing at the end of a road before a small brick building 14 | 15 | Available exits are Q, S, E, N, W, 16 | 17 | You are in the forest 18 | 19 | Available exits are Q, S, W, 20 | 21 | An attempt to move in an invalid direction should print a message and remain in the same place. The printed message should be: "You cannot go in that direction". For Example: 22 | 23 | You are standing at the end of a road before a small brick building 24 | 25 | Available exits are Q, S, E, N, W, 26 | 27 | You cannot go in that direction 28 | 29 | You are standing at the end of a road before a small brick building 30 | 31 | Available exits are Q, S, E, N, W, 32 | 33 | Output for quit (Q) command should be displayed as: 34 | 35 | You are standing at the end of a road before a small brick building 36 | 37 | Available exits are Q, S, E, N, W, 38 | 39 | You are sitting in front of a computer learning Java 40 | 41 | Single letter commands (N, W, S, E, Q) should still be available. 42 | 43 | TIP: Declare a Map called vocabulary as a field with private access modifier, the object is of type HashMap. Create its key-value pair in the constructor by using the put() method. Both key and value are of type String. Use vocabulary to store the original commands aliases (eg. NORTH = N, SOUTH = S, ...). 44 | 45 | TIP: Instantiate (create) the Scanner object inside the method. 46 | 47 | NOTE: Ignore "No line found" in the output if you get an error message. It is not the reason for the error. Instead, check spelling/spaces/format in the printed message. -------------------------------------------------------------------------------- /Coding Exercises 50 - Adventure Game/Location.java: -------------------------------------------------------------------------------- 1 | /* 2 | Do not change anything in this class 3 | */ 4 | 5 | import java.util.HashMap; 6 | import java.util.Map; 7 | 8 | public class Location { 9 | private final int locationID; 10 | private final String description; 11 | private final Map exits; 12 | 13 | public Location(int locationID, String description) { 14 | this.locationID = locationID; 15 | this.description = description; 16 | this.exits = new HashMap(); 17 | this.exits.put("Q", 0); 18 | } 19 | 20 | public void addExit(String direction, int location) { 21 | exits.put(direction, location); 22 | } 23 | public int getLocationID() { 24 | return locationID; 25 | } 26 | 27 | public String getDescription() { 28 | return description; 29 | } 30 | 31 | public Map getExits() { 32 | return new HashMap(exits); 33 | } 34 | } -------------------------------------------------------------------------------- /Coding Exercises 50 - Adventure Game/Main.java: -------------------------------------------------------------------------------- 1 | /* 2 | Only add/edit code where it is stated in the description. 3 | */ 4 | 5 | import java.util.HashMap; 6 | import java.util.Map; 7 | import java.util.Scanner; 8 | 9 | public class Main { 10 | private Map locations = new HashMap(); 11 | private Map vocabulary = new HashMap(); 12 | 13 | public Main() { 14 | locations.put(0, new Location(0, "You are sitting in front of a computer learning Java")); 15 | locations.put(1, new Location(1, "You are standing at the end of a road before a small brick building")); 16 | locations.put(2, new Location(2, "You are at the top of a hill")); 17 | locations.put(3, new Location(3, "You are inside a building, a well house for a small spring")); 18 | locations.put(4, new Location(4, "You are in a valley beside a stream")); 19 | locations.put(5, new Location(5, "You are in the forest")); 20 | 21 | locations.get(1).addExit("W", 2); 22 | locations.get(1).addExit("E", 3); 23 | locations.get(1).addExit("S", 4); 24 | locations.get(1).addExit("N", 5); 25 | 26 | locations.get(2).addExit("N", 5); 27 | 28 | locations.get(3).addExit("W", 1); 29 | 30 | locations.get(4).addExit("N", 1); 31 | locations.get(4).addExit("W", 2); 32 | 33 | locations.get(5).addExit("S", 1); 34 | locations.get(5).addExit("W", 2); 35 | } 36 | 37 | public void command() { 38 | // write code here 39 | Scanner scanner = new Scanner(System.in); 40 | 41 | vocabulary.put("QUIT", "Q"); 42 | vocabulary.put("NORTH", "N"); 43 | vocabulary.put("SOUTH", "S"); 44 | vocabulary.put("EAST", "E"); 45 | vocabulary.put("WEST", "W"); 46 | int loc = 1; 47 | while (true) { 48 | System.out.println(locations.get(loc).getDescription()); 49 | if (loc == 0) { 50 | break; 51 | } 52 | 53 | Map exits = locations.get(loc).getExits(); 54 | System.out.print("Available exits are "); 55 | for (String exit : exits.keySet()) { 56 | System.out.print(exit + ", "); 57 | } 58 | System.out.println(); 59 | 60 | String[] words = scanner.nextLine().toUpperCase().split(" "); 61 | String direction = ""; 62 | for (String word : words) { 63 | if (vocabulary.containsKey(word)) { 64 | direction = vocabulary.get(word); 65 | break; 66 | } 67 | } 68 | if (exits.containsKey(direction)) { 69 | loc = exits.get(direction); 70 | } else { 71 | System.out.println("You cannot go in that direction"); 72 | } 73 | } 74 | } 75 | } -------------------------------------------------------------------------------- /Coding Exercises 51 - Immutable Class/Exercise Description.txt: -------------------------------------------------------------------------------- 1 | Make the Location class an Immutable Class. 2 | 3 | The strategy for creating an Immutable Class is: 4 | 5 |     Steps: 6 | 7 |     1. Don't provide setters. 8 | 9 |     2. Make all fields final and private 10 | 11 |     3. Don't allow the class to be subclassed. 12 | 13 |     4. If the instance fields include references to mutable objects, don't allow those objects to be changed:    14 | 15 |             -  Don't provide methods that modify the mutable objects. 16 | 17 |             -  Don't share references to the mutable objects. 18 | 19 | As an added Task, handle the case where exits is null when passed to the constructor. 20 | 21 | NOTE: Not all classes documented as "immutable" follow these rules. However, the steps above are the basis of an Immutable Class. 22 | 23 | -------------------------------------------------------------------------------- /Coding Exercises 51 - Immutable Class/Location.java: -------------------------------------------------------------------------------- 1 | /* 2 | Do not change anything in this class 3 | */ 4 | 5 | import java.util.HashMap; 6 | import java.util.Map; 7 | 8 | public final class Location { 9 | private final int locationID; 10 | private final String description; 11 | private final Map exits; 12 | 13 | public Location(int locationID, String description, Map exits) { 14 | this.locationID = locationID; 15 | this.description = description; 16 | if(exits != null) 17 | { 18 | this.exits = new HashMap(exits); 19 | 20 | } else { 21 | this.exits = new HashMap(); 22 | } 23 | this.exits.put("Q", 0); 24 | } 25 | 26 | 27 | public int getLocationID() { 28 | return locationID; 29 | } 30 | 31 | public String getDescription() { 32 | return description; 33 | } 34 | 35 | public Map getExits() { 36 | try { 37 | Map exitsClone = new HashMap(exits); 38 | 39 | return (Map) exitsClone; 40 | } catch (Exception e) { 41 | return null; 42 | } 43 | } 44 | 45 | } -------------------------------------------------------------------------------- /Coding Exercises 52 - Sets/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 | -------------------------------------------------------------------------------- /Coding Exercises 52 - Sets/HeavenlyBody.java: -------------------------------------------------------------------------------- 1 | import java.util.HashSet; 2 | import java.util.Set; 3 | 4 | public abstract class HeavenlyBody { 5 | private final Key key; 6 | private final double orbitalPeriod; 7 | private final Set satellites; 8 | 9 | public enum BodyTypes { 10 | PLANET, 11 | DWARF_PLANET, 12 | MOON 13 | } 14 | 15 | public HeavenlyBody(String name, double orbitalPeriod, BodyTypes bodyType) { 16 | this.orbitalPeriod = orbitalPeriod; 17 | this.satellites = new HashSet<>(); 18 | this.key = new Key(name, bodyType); 19 | } 20 | 21 | public double getOrbitalPeriod() { 22 | return orbitalPeriod; 23 | } 24 | 25 | public boolean addSatellite (HeavenlyBody moon) { 26 | return this.satellites.add(moon); 27 | } 28 | 29 | public Set getSatellites() { 30 | return new HashSet<>(this.satellites); 31 | } 32 | 33 | public Key getKey () { 34 | return key; 35 | } 36 | 37 | @Override 38 | public final boolean equals (Object obj) { 39 | if (this == obj) { 40 | return true; 41 | } 42 | if (obj instanceof HeavenlyBody) { 43 | HeavenlyBody theObject = (HeavenlyBody) obj; 44 | return this.key.equals(theObject.getKey()); 45 | } 46 | return false; 47 | } 48 | 49 | @Override 50 | public final int hashCode () { 51 | return this.key.hashCode(); 52 | } 53 | 54 | public static Key makeKey(String name, BodyTypes bodyType) { 55 | return new Key(name, bodyType); 56 | } 57 | 58 | @Override 59 | public String toString () { 60 | return this.key.name + ": " + this.key.bodyType + ", " + this.orbitalPeriod; 61 | } 62 | 63 | public static final class Key { 64 | private String name; 65 | private BodyTypes bodyType; 66 | 67 | private Key(String name, BodyTypes bodyType) { 68 | this.name = name; 69 | this.bodyType = bodyType; 70 | } 71 | 72 | public String getName () { 73 | return name; 74 | } 75 | 76 | public BodyTypes getBodyType () { 77 | return bodyType; 78 | } 79 | 80 | @Override 81 | public int hashCode () { 82 | return this.name.hashCode() + 13 + this.bodyType.hashCode(); 83 | } 84 | 85 | @Override 86 | public boolean equals (Object obj) { 87 | Key key = (Key) obj; 88 | if (this.name.equals(key.getName())) { 89 | return (this.bodyType == key.getBodyType()); 90 | } 91 | return false; 92 | } 93 | 94 | @Override 95 | public String toString() { 96 | return this.name + ": " + this.bodyType; 97 | } 98 | } 99 | } -------------------------------------------------------------------------------- /Coding Exercises 52 - Sets/Moon.java: -------------------------------------------------------------------------------- 1 | public class Moon extends HeavenlyBody { 2 | 3 | public Moon (String name, double orbitalPeriod) { 4 | super(name, orbitalPeriod, BodyTypes.MOON); 5 | } 6 | } -------------------------------------------------------------------------------- /Coding Exercises 52 - Sets/Planet.java: -------------------------------------------------------------------------------- 1 | 2 | public class Planet extends HeavenlyBody { 3 | public Planet (String name, double orbitalPeriod) { 4 | super(name, orbitalPeriod, BodyTypes.PLANET); 5 | } 6 | 7 | @Override 8 | public boolean addSatellite (HeavenlyBody moon) { 9 | if (moon.getKey().getBodyType() == BodyTypes.MOON) { 10 | return super.addSatellite(moon); 11 | } else { 12 | return false; 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # JAVA 2 | # UDEMY - Java Programming Masterclass for Software Developers 3 | # Instructor - Tim Buchalka 4 | --------------------------------------------------------------------------------