├── AreaCalculator.java ├── Array ├── ArrayList │ ├── Contact.java │ ├── GroceryList.java │ ├── Main.java │ └── MobilePhone.java ├── Challenge100 │ └── Main.java └── Main.java ├── BarkingDog.java ├── CODE_OF_CONDUCT.md ├── Code-Exercise 35: Cylinder ├── Circle.java ├── Cylinder.java └── Main.java ├── CodeExercise32 ├── Main.java └── Point.java ├── Coding-Exercise-35: Pool Area ├── Cuboid.java ├── Main.java └── Rectangle.java ├── Composition in Java ├── Bed.java ├── Bedroom.java ├── Car.java ├── Case.java ├── Ceiling.java ├── Dimension.java ├── Lamp.java ├── Main.java ├── Monitor.java ├── Motherboard.java ├── PC.java ├── Resolution.java ├── Vehicle.java └── Wall.java ├── DecimalComparator.java ├── DiagonalStar.java ├── Encapsulation └── Challenges1 │ ├── Main.java │ └── Printer.java ├── EqualSumChecker.java ├── EvenDigitSum.java ├── FactorPrinter.java ├── FirstLastDigitSum.java ├── FlourPack.java ├── ForLoopSum.java ├── GreatestCommonDivisor.java ├── Inheritance-Challenge ├── Car.java ├── Main.java ├── Outlander.java └── Vehicle.java ├── InputCalculator.java ├── IntEqualPrinter.java ├── LargestPrime.java ├── LastDigitChecker.java ├── LeapYearCalculator.java ├── MegaBytesConver.java ├── MinutesToYearsDaysCalculator.java ├── NumberPalindrome.java ├── NumberTwoWords.java ├── OOP-Part1&2 ├── Animal.java ├── Dog.java ├── Fish.java └── Main.java ├── PaintJob.java ├── PerfectNumber.java ├── Person.java ├── PlayingCat.java ├── Polymorphism ├── Challenge │ ├── Forgetable.java │ ├── IndependenceDay.java │ ├── Jaws.java │ ├── Main.java │ ├── MazeRunner.java │ ├── Movie.java │ └── StarWars.java └── Challenge2 │ ├── Car.java │ └── Main.java ├── README.md ├── SECURITY.md ├── SharedDigit.java ├── SimpleCalculator.java ├── SpeedConverter.java ├── SumOddRange.java ├── TeenNumberChecker.java └── Wall ├── Main.java └── Wall.java /AreaCalculator.java: -------------------------------------------------------------------------------- 1 | /****************************************************************CODING EXERCISE 8: AREA CALCULATOR*************************************************** 2 | Description Exercise: 3 | Method1: 4 | - Write a method named area with one double parameter named radius. 5 | - The method needs to return a double value that represents the area of a circle. 6 | - If the parameter radius is negative then return -1.0 to represent an invalid value. 7 | Method2: 8 | - Write another overloaded method with 2 parameters x and y (both doubles), where x and y represent the sides of a rectangle. 9 | - The method needs to return an area of a rectangle 10 | - If either or both parameters is/are a negative return -1.0 to indicate an invalid value. 11 | TIPS/NOTES: 12 | - The formula for calculating the area of a rectangle is x * y. 13 | - The formula for calculating a circle area is radius * radius * Math.PI. 14 | - All methods need to be defined as a public static 15 | - This code solution does not contain a main method. 16 | *******************************************************************************CODE*******************************************************************/ 17 | 18 | public class AreaCalculator { 19 | 20 | public static double area (double radius) { 21 | 22 | if (radius < 0) { 23 | 24 | return -1.0; 25 | 26 | } 27 | return (radius * radius * Math.PI); 28 | 29 | } 30 | 31 | public static double area (double x, double y) { 32 | 33 | if (x < 0 || y < 0) { 34 | 35 | return -1.0; 36 | 37 | } 38 | return (x * y); 39 | 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /Array/ArrayList/Contact.java: -------------------------------------------------------------------------------- 1 | public class Contact { 2 | 3 | private String name; 4 | private String phoneNumber; 5 | 6 | public Contact(String name, String phoneNumber) { 7 | this.name = name; 8 | this.phoneNumber = phoneNumber; 9 | } 10 | 11 | public String getName() { 12 | return name; 13 | } 14 | 15 | public String getPhoneNumber() { 16 | return phoneNumber; 17 | } 18 | 19 | public static Contact createContact(String name, String phoneNumber) { 20 | return new Contact(name, phoneNumber); 21 | } 22 | 23 | } // class Contact 24 | -------------------------------------------------------------------------------- /Array/ArrayList/GroceryList.java: -------------------------------------------------------------------------------- 1 | public class GroceryList { 2 | 3 | } 4 | -------------------------------------------------------------------------------- /Array/ArrayList/Main.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class Main { 4 | 5 | private static Scanner scanner = new Scanner(System.in); 6 | private static MobilePhone 7 | 8 | 9 | }// Main Class 10 | -------------------------------------------------------------------------------- /Array/ArrayList/MobilePhone.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class MobilePhone { 4 | 5 | private String myNumber; 6 | private ArrayListmyContacts; 7 | 8 | // constructor 9 | public MobilePohne(String myNumber){ 10 | this.myNumber = myNumber; 11 | this.myContacts = new ArrayList(); 12 | } 13 | // addNewContact method 14 | public boolean addNewContact(Contact contact){ 15 | if(findContact(contact.getname()) >= 0) { 16 | System.out.println("Contact isi already on file"); 17 | return false; 18 | } 19 | 20 | myContacts.add(contact); 21 | return true; 22 | } 23 | //updateContact method 24 | public boolean updateContact(Contact oldContact, Contact newContact) { 25 | int findPosition = findContact(oldContact); 26 | if(foundPosition < 0) { 27 | System.out.println(oldContact.getName() + ", was not found"); 28 | return false; 29 | }else if(findContact(newContact.getName()) != -1) { 30 | System.out.println("Contact with name " + newContact.getName() + " already exists. Update was not successefully."); 31 | return false; 32 | } 33 | 34 | this.myContacts.set(foundPosition, newContact); 35 | System.out.println(oldContact.getName() + ", was replaced with " + newContact.getName()); 36 | return true; 37 | } 38 | 39 | // removeContact method 40 | public boolean removeContact(Contact contact) { 41 | int foundPosition = findContact(contact); 42 | if(foundPosition < 0) { 43 | System.out.println(contact.getName() + " was not found."); 44 | return false; 45 | } 46 | this.myContacts.remove(foundPosition); 47 | System.out.println(contact.getName() + ", was deleted."); 48 | return true; 49 | } 50 | 51 | //findContact method 52 | private int findContact(Contact contact){ 53 | return this.myContacts.indexOf(contact); 54 | } 55 | 56 | private int findContact(String contactName){ 57 | for(int i=0; i= 0){ 69 | return contact.getName(); 70 | } 71 | return null; 72 | } 73 | 74 | public Contact queryContact(String name) { 75 | int position = findContact(name); 76 | if(position >= 0) { 77 | return this.myContacts.get(position); 78 | } 79 | return null; 80 | } 81 | 82 | public void printContacts(){ 83 | System.out.println("Contact List"); 84 | for(int i=0; i " + this.myContacts.get(i).getPhoneNumber()); 86 | } 87 | } 88 | 89 | }// class MobilePhone 90 | -------------------------------------------------------------------------------- /Array/Challenge100/Main.java: -------------------------------------------------------------------------------- 1 | /* 2 | CODE CHALLENGE DESCRIPTION: 3 | - Create a program using arrays that sorts a list of integers in descending order. 4 | - Descending orders is the highest value to lowest 5 | - In other words if the array had the valuees in it 106,26,8,5,15 your program should ultimately have an array with 106,81,26,15,5, in it. 6 | - Set up the program so that the numbers to sort are read in from the keyboard. 7 | - Implement the following methods - getIntegers, printArray, and sortIntegers 8 | - getIntegers - returns an array of entered integers from keyboard 9 | - printArray - prints out the contents of the array 10 | - and sortArray - should sort the array and return a new array containing the sorted numbers 11 | - you'll 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 12 | */ 13 | //libraries 14 | import java.util.Arrays; 15 | import java.util.Scanner; 16 | 17 | //Main class 18 | public class Main{ 19 | //Scanner 20 | private static Scanner scanner = new Scanner(System.in); 21 | 22 | public static void main(String [] args){ 23 | 24 | int[] myIntegers = getIntegers(5); 25 | int[] sorted = sortIntegers(myIntegers); 26 | printArray(sorted); 27 | } // Main method 28 | 29 | public static int[] getIntegers(int capacity) { 30 | 31 | int[] array = new int[capacity]; 32 | System.out.println("Enter " + capacity +" integer values: \r); 33 | for(int i=0; i 23) { 26 | return false; 27 | } 28 | else if (hourOfDay < 8 || hourOfDay > 22) { 29 | return true; 30 | } 31 | else { 32 | return false; 33 | } 34 | else { 35 | return false; 36 | } 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at . All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /Code-Exercise 35: Cylinder/Circle.java: -------------------------------------------------------------------------------- 1 | public class Circle { 2 | 3 | private double radius; 4 | 5 | public Circle(double radius) { 6 | this.radius = radius < 0 ? 0 : radius; 7 | } 8 | 9 | public double getRadius() { 10 | return radius; 11 | } 12 | 13 | public double getArea() { 14 | return (radius * radius * Math.PI); 15 | } 16 | } 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /Code-Exercise 35: Cylinder/Cylinder.java: -------------------------------------------------------------------------------- 1 | public class Cylinder extends Circle{ 2 | 3 | private double height; 4 | 5 | public Cylinder(double radius, double height) { 6 | super(radius); 7 | this.height = height < 0 ? 0 : height; 8 | } 9 | 10 | public double getHeight() { 11 | return height; 12 | } 13 | 14 | public double getVolume() { 15 | return getArea() * height; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Code-Exercise 35: Cylinder/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | 5 | //Test Code: 6 | Circle circle = new Circle(3.75); 7 | System.out.println("circle.radius = " + circle.getRadius()); 8 | System.out.println("circle.area = " + circle.getArea()); 9 | 10 | Cylinder cyclinder = new Cylinder(5.55, 7.25); 11 | System.out.println("cylinder.radium = " + cylinder.getRadius()); 12 | System.out.println("cylinder.height = " + cylinder.getHeight()); 13 | System.out.println("cylinder.area = " + cyclinder.getArea()); 14 | System.out.println("cylinder.volume = " + cyclinder.getVolume()); 15 | 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /CodeExercise32/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String [] args) { 4 | 5 | Point first = new Point(6, 5); 6 | Point second = new Point(3, 1); 7 | 8 | System.out.println("distance(0,0)= " + first.distance()); 9 | System.out.println("distance(second)= " + first.distance(second)); 10 | System.out.println("distance(2,2)= " + first.distance(2, 2)); 11 | 12 | Point point = new Point(); 13 | 14 | System.out.println("distance()= " + point.distance()); 15 | 16 | 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /CodeExercise32/Point.java: -------------------------------------------------------------------------------- 1 | /************************************CODING EXERCISE 32: POINT***************************************** 2 | CODE DESCRIPTION EXERCISE: 3 | 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. 4 | 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. 5 | 6 | Write the following methods (instance methods): 7 | * Method named getX without any parameters, it needs to return the value of x field. 8 | * Method named getY without any parameters, it needs to return the value of y field. 9 | * Method named setX with one parameter of type int, it needs to set the value of the x field. 10 | * Method named setY with one parameter of type int, it needs to set the value of the y field. 11 | * Method named distance without any parameters, it needs to return the distance between this Point and Point 0,0 as double. 12 | * 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. 13 | * Method named distance with parameter another of type Point, it needs to return the distance between this Point and another Point as double. 14 | 15 | 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: 16 | d(A,B)=√ (xB − xA) * (xB - xA) + (yB − yA) * (yB - yA) 17 | Where √ represents square root. 18 | TEST EXAMPLE 19 | → TEST CODE: 20 | Point first = new Point(6, 5); 21 | Point second = new Point(3, 1); 22 | System.out.println("distance(0,0)= " + first.distance()); 23 | System.out.println("distance(second)= " + first.distance(second)); 24 | System.out.println("distance(2,2)= " + first.distance(2, 2)); 25 | Point point = new Point(); 26 | System.out.println("distance()= " + point.distance()); 27 | 28 | OUTPUT 29 | distance(0,0)= 7.810249675906654 30 | distance(second)= 5.0 31 | distance(2,2)= 5.0 32 | distance()= 0.0 33 | 34 | NOTE: 35 | * Use Math.sqrt to calculate the square root √. 36 | * Try to avoid duplicated code. 37 | * All methods should be defined as public NOT public static. 38 | * In total, you have to write 7 methods. 39 | *****************************************************************************************************/ 40 | public class Point { 41 | // write your code here 42 | private int x; 43 | private int y; 44 | 45 | // constructors 46 | public Point(){} // no-arg constructor 47 | public Point(int x, int y){ // Parameterized constructor 48 | this.x = x; 49 | this.y = y; 50 | } 51 | 52 | // instance methods 53 | //getters 54 | public int getX(){ 55 | return x; 56 | } 57 | public int getY(){ 58 | return y; 59 | } 60 | //setters 61 | public void setX(int x){ 62 | this.x = x; 63 | } 64 | public void setY(int y){ 65 | this.y = y; 66 | } 67 | public double distance(){ // method without parameters 68 | return distance(0,0); 69 | } 70 | public double distance(int x, int y){ // returns distance btn this points(x,y) 71 | return Math.sqrt((x - this.x) * (x - this.x) + (y - this.y) * (y - this.y)); 72 | } 73 | public double distance(Point another) {// returns distance btn this point & another point 74 | return distance(another.x, another.y); 75 | }// end of instance methods 76 | 77 | }// end of Point class 78 | -------------------------------------------------------------------------------- /Coding-Exercise-35: Pool Area/Cuboid.java: -------------------------------------------------------------------------------- 1 | public class Cuboid extends Rectangle { 2 | 3 | private double height; 4 | 5 | public Cuboid(double width, double length, double height) { 6 | super(width, length); 7 | this.height = height < 0 ? 0 : height; 8 | } 9 | 10 | public double getHeight() { 11 | return height; 12 | } 13 | 14 | public double getVolume() { 15 | return getArea() * height; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Coding-Exercise-35: Pool Area/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | 5 | // Test Code: 6 | Rectangle rectangle = new Rectangle(5, 10); 7 | System.out.println("rectangle.width = " + rectangle.getWidth()); 8 | System.out.println("rectangle.length = " + rectangle.getLength()); 9 | System.out.println("rectangle.area = " + rectangle.getArea()); 10 | 11 | Cuboid cuboid = new Cuboid(5, 10, 5); 12 | System.out.println("cuboid.width = " + cuboid.getWidth()); 13 | System.out.println("cuboid.length = " + cuboid.getLength()); 14 | System.out.println("cuboid.area = " + cuboid.getArea()); 15 | System.out.println("cuboid.height " + cuboid.getHeight()); 16 | System.out.println("cuboid.volume " + cuboid.getVolume()); 17 | 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Coding-Exercise-35: Pool Area/Rectangle.java: -------------------------------------------------------------------------------- 1 | public class Rectangle { 2 | 3 | private double width; 4 | private double length; 5 | 6 | public Rectangle(double width, double length) { 7 | this.width = width < 0 ? 0 : width; 8 | this.length = length < 0 ? 0 : length; 9 | } 10 | 11 | public double getWidth() { 12 | return width; 13 | } 14 | 15 | public double getLength() { 16 | return length; 17 | } 18 | 19 | public double getArea() { 20 | return width * length; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Composition in Java/Bed.java: -------------------------------------------------------------------------------- 1 | publi class Bed { 2 | 3 | 4 | } 5 | -------------------------------------------------------------------------------- /Composition in Java/Bedroom.java: -------------------------------------------------------------------------------- 1 | public class Bedroom { 2 | 3 | 4 | 5 | } 6 | -------------------------------------------------------------------------------- /Composition in Java/Car.java: -------------------------------------------------------------------------------- 1 | public class Car extends Vehicle { 2 | 3 | private int doors; 4 | private int engineCapacity; 5 | 6 | public Car(String name, int doors, int engineCapacity){ 7 | super(name); 8 | this.doors = doors; 9 | this.engineCapcity = engineCapacity; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Composition in Java/Case.java: -------------------------------------------------------------------------------- 1 | public class Case { 2 | private String model; 3 | private String manufacturer; 4 | private String powerSupply; 5 | private Dimensions dimensions; 6 | 7 | public Case(String model, String manufacturer, String powerSupply, Dimensions dimensions){ 8 | this.model = model, 9 | this.manufacturer manufacturer; 10 | this.powerSupply = powerSupply; 11 | this.dimensions = dimensions; 12 | } 13 | 14 | public void pressPowerButton(){ 15 | System.out.println("Power button pressed"); 16 | } 17 | 18 | //getters 19 | public String getModel(){ 20 | return model; 21 | } 22 | public String getManufacturer(){ 23 | return manufacturer; 24 | } 25 | public String getPowerSupply(){ 26 | return powerSupply; 27 | } 28 | public Dimensions getDimensions(){ 29 | return dimensions; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Composition in Java/Ceiling.java: -------------------------------------------------------------------------------- 1 | public class Ceiling { 2 | 3 | 4 | } 5 | -------------------------------------------------------------------------------- /Composition in Java/Dimension.java: -------------------------------------------------------------------------------- 1 | public class Dimension { 2 | private int width; 3 | private int height; 4 | private int depth; 5 | 6 | 7 | public Dimension(int width, int height, int depth){ 8 | this.width = width; 9 | this.height = height; 10 | this.depth = depth; 11 | } 12 | 13 | //getters 14 | public int getWidth(){ 15 | return width; 16 | } 17 | public int getHeight(){ 18 | return height; 19 | } 20 | public int getDepth(){ 21 | return depth; 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /Composition in Java/Lamp.java: -------------------------------------------------------------------------------- 1 | public class Lamb { 2 | 3 | 4 | } 5 | -------------------------------------------------------------------------------- /Composition in Java/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String [] args) { 4 | 5 | // TEST CODE 6 | 7 | Dimensions dimensions = new Dimensions(20, 20, 5); 8 | Case theCase = new Case("220B", "Dell", "240", dimensions); 9 | 10 | Monitor theMonitor = new Monitor("27inch Beast", "Acer", 27, new Resolution(2540, 1440)); 11 | 12 | Motherboard = theMotherboard = Motherboard("BJ-200", "Asus", 4, 6, "v2.44"); 13 | 14 | PC thePC = new PC(theCase, theMonitor, theMotherboard); 15 | the.PC.powerUP(); 16 | 17 | /* COMPOSITION CHALLENGE: 18 | - Create a single room of a house using composition 19 | - Think about the things that sould be included in the room 20 | - May be physical parts of the house but furniture as well 21 | - Add at least one method to access one object via getters and 22 | - then that objects public methods as you saw in the previous video 23 | - then add at least one method to hide the object e.g. not using a getter 24 | - but to access the object used in composition within the main class 25 | */ 26 | 27 | Wall wall1 = new Wall("West"); 28 | Wall wall2 = new Wall("East"); 29 | Wall wall3 = new Wall("South"); 30 | Wall wall4 = new Wall("North"); 31 | 32 | Ceiling ceiling = new Ceiling(12, 55); 33 | 34 | Bed bed = new Bed("Modern", 4, 3, 2, 1); 35 | 36 | Lamp lamp = new Lamp("Classic", false, 75); 37 | 38 | Bedroom bedRoom = new Bedroom("Tims", wall1, wall2, wall3, wall4, ceiling, bed, lamp); 39 | bedRoom.makeBed(0); 40 | bedRoom.getLamp().turnOn(); 41 | 42 | 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /Composition in Java/Monitor.java: -------------------------------------------------------------------------------- 1 | public class Monitor { 2 | 3 | private String model; 4 | private String manufacturer; 5 | privat int size; 6 | private Resolution nativeResolution; 7 | 8 | public Monitor(String model, String manufacturer, int size, Resolution nativeResolution) { 9 | this.model = model; 10 | this.manufacturer = manufacturer; 11 | this.size = size; 12 | this.nativeResolution = nativeResolution; 13 | } 14 | 15 | public void drawPixelAt(int x, int y, String color) { 16 | System.out.println("Drawing pixel at " x + "," = y + " in color " + color); 17 | } 18 | 19 | public String getModel() { 20 | return model; 21 | } 22 | 23 | public String getManufacturer() { 24 | return manufacturer; 25 | } 26 | 27 | public int getSize() { 28 | return size; 29 | } 30 | 31 | public Resolution getNativeResolution(){ 32 | return nativeResolution; 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /Composition in Java/Motherboard.java: -------------------------------------------------------------------------------- 1 | public class Motherboard { 2 | 3 | private String model; 4 | private String manufacturer; 5 | private int ramSlots; 6 | private int cardSlots; 7 | private String bios; 8 | 9 | public Motherboard(String model, String manufacturer, int ramSlots, int cardSlots, String bios){ 10 | this.model = model; 11 | this.manufacturer = manufacturer; 12 | this.ramSlots = ramSlots; 13 | this.cardSlots = cardSlots; 14 | this.bios = bios; 15 | } 16 | 17 | public void loadProgram(String programName){ 18 | System.out.println("Program " + programName + " is now loading..."); 19 | } 20 | // getters 21 | public String getModel(){ 22 | return model; 23 | } 24 | public String getManufacturer(){ 25 | return manufacturer; 26 | } 27 | public int getRamSlots(){ 28 | return ramSlots; 29 | } 30 | public int getCardSlots(){ 31 | return cardSlots; 32 | } 33 | public String getBios(){ 34 | return bios; 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /Composition in Java/PC.java: -------------------------------------------------------------------------------- 1 | public class PC { 2 | 3 | private Case theCase; 4 | private Monitor monitor; 5 | private Motherboard motherboard; 6 | 7 | public PC(Case theCase, Monitor monitor, Motherboard motherboard) { 8 | this.theCase = theCase; 9 | this.monitor = monitor; 10 | this.motherboard = motherboard; 11 | } 12 | 13 | public void powerUP(){ 14 | theCase.pressPowerButton(); 15 | drawLogo(); 16 | } 17 | public void drawLogo(){ 18 | //Fancy graphs 19 | monitor.drawPixelAt(1200, 50, "yellow"); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /Composition in Java/Resolution.java: -------------------------------------------------------------------------------- 1 | public class Resolution { 2 | 3 | private int width; 4 | private int height; 5 | 6 | public Resolution(int width, int height){ 7 | this.width = width; 8 | this.height = height; 9 | } 10 | 11 | public int getWidth(){ 12 | return width; 13 | } 14 | public int getHeight(){ 15 | return height; 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /Composition in Java/Vehicle.java: -------------------------------------------------------------------------------- 1 | public class Vehicle { 2 | 3 | private String name; 4 | 5 | public Vehicle(String name){ 6 | this.name = name; 7 | } 8 | 9 | } 10 | -------------------------------------------------------------------------------- /Composition in Java/Wall.java: -------------------------------------------------------------------------------- 1 | public class Wall { 2 | 3 | 4 | } 5 | -------------------------------------------------------------------------------- /DecimalComparator.java: -------------------------------------------------------------------------------- 1 | /*******************************************************CODE EXERCISE 5: DECIMAL COMPARATOR************************************************************* 2 | Description Exercise: 3 | - Write a method areEqualByThreeDecimalPlaces with two parameters of type double 4 | - The method should return boolean and it needs to return if two double numbers are the same up to three decimal places. Otherwise return false. 5 | TIPS/NOTES: 6 | - Use casting 7 | - The areEqualByThreeDecimalPlaces method needs to be defined as a public static 8 | - This code solution does not contain main method. 9 | **************************************************************************CODE**************************************************************************/ 10 | 11 | public class DecimalComparator { 12 | 13 | public static boolean areEqualByThreeDecimalPlaces (double a, double b) { 14 | 15 | a = (int) (a * 1000); 16 | b = (int) (b * 1000); 17 | 18 | if (a == b) { 19 | 20 | return true; 21 | 22 | } 23 | else { 24 | 25 | return false; 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /DiagonalStar.java: -------------------------------------------------------------------------------- 1 | /******************************************************************CODING EXERCISE 26: DIAGONAL STAR******************************************************************* 2 | DESCRIPTION EXERCISE: 3 | 4 | Write a method named printSquareStar with one parameter of type int named number. 5 | 6 | If number is < 5, the method should print "Invalid Value". 7 | 8 | The method should print diagonals to generate a rectangular pattern composed of stars (*). This should be accomplished by using loops (see examples below). 9 | 10 | 11 | EXAMPLE INPUT/OUTPUT: 12 | 13 | EXAMPLE 1 14 | 15 | printSquareStar(5); should print the following: 16 | 17 | → NOTE: For text in Code Blocks below, use code icon {...} on Udemy 18 | 19 | ***** 20 | ** ** 21 | * * * 22 | ** ** 23 | ***** 24 | 25 | 26 | Explanation: 27 | 28 | ***** 5 stars 29 | ** ** 2 stars space 2 stars 30 | * * * 1 star space 1 star space 1 star 31 | ** ** 2 stars space 2 stars 32 | ***** 5 stars 33 | 34 | 35 | EXAMPLE 2 36 | 37 | printSquareStar(8); should print the following: 38 | 39 | ******** 40 | ** ** 41 | * * * * 42 | * ** * 43 | * ** * 44 | * * * * 45 | ** ** 46 | ******** 47 | 48 | 49 | 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): 50 | 51 | * In the first or last row 52 | 53 | * In the first or last column 54 | 55 | * When the row number equals the column number 56 | 57 | * When the column number equals rowCount - currentRow + 1 (where currentRow is current row number) 58 | 59 | 60 | HINT: Use a nested loop (a loop inside of a loop). 61 | 62 | 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. 63 | 64 | HINT: To "move" to another line, you can use an empty println call, e.g. System.out.println(); . 65 | 66 | NOTE: The method printSquareStar should be defined as public static like we have been doing so far in the course. 67 | 68 | NOTE: Do not add a main method to the solution code. 69 | 70 | *******************************************************************************CODE************************************************************************************/ 71 | 72 | public class DiagonalStar { 73 | /* 74 | public static void main(String [] args){ 75 | System.out.println(printSquareStar(5)); 76 | System.out.println(printSquareStar(8)); 77 | } 78 | */ 79 | // write your code here 80 | public static void printSquareStar(int number) { 81 | 82 | if (number < 5) { 83 | System.out.println("Invalid Value"); 84 | } else { 85 | int rowCount; 86 | int columnCount; 87 | int currentRow; 88 | rowCount = columnCount = number; 89 | for (int row = 0; row < rowCount; row++) { 90 | currentRow = row; 91 | for (int column = 0; column < columnCount; column++) { 92 | if (row == 0 || column == 0 || row == rowCount - 1 || column == columnCount - 1 || column == row || 93 | column == (rowCount - currentRow - 1)) { 94 | System.out.print("*"); 95 | } else { 96 | System.out.print(" "); 97 | } 98 | } 99 | System.out.println(); 100 | } 101 | } 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /Encapsulation/Challenges1/Main.java: -------------------------------------------------------------------------------- 1 | /* 2 | CHALLENGE DESCRIPTION: 3 | - Create a class and demonstrate proper encapsulation techniques 4 | - the class will be Printer 5 | - It will simulate a real Computer Printer 6 | - It should have fields for the toner Level, number of pages printed, and 7 | - also whether its a duplex printer (capable of printing on both sides of the paper). 8 | - Add methods to fill up the toner (up to a maximum 100%), another method to simulate printing a page(which should increase the number of pages printed) 9 | - Decide on the scope, whether to use constructors, and anything else you think is needed. 10 | */ 11 | pubblic class Main { 12 | 13 | public static void main(String [] args) { 14 | 15 | Printer printer = new Printer(50, false); 16 | System.out.printlin("Initial page count = " + printer.getPagesPrinted()); 17 | 18 | int pagesPrinted = printer.printerPages(4); 19 | System.out.println("Pages printed was " + pagesPrinted + " new total print count for printer = " printer = " + printer.getPagesPrinted()); 20 | 21 | pagesPrinted = printer.printPages(2); 22 | System.out.println("Page printed was " + pagesPrinted + " new total print count for printer = " + printer.getPagesPrinted()); 23 | 24 | } 25 | 26 | 27 | }// Main class - Testing code 28 | -------------------------------------------------------------------------------- /Encapsulation/Challenges1/Printer.java: -------------------------------------------------------------------------------- 1 | public class Printer { 2 | 3 | private int tonerLevel; 4 | private int pagesPrinted; 5 | private boolean duplex; 6 | 7 | public Printer(int tonerlevel, boolean duplex) { 8 | 9 | if(tonerLevel > -1 && tonerLevel <= 100) { 10 | this.tonerLevel = tonerLevel; 11 | }else { 12 | this.tonerLevel = -1; 13 | } 14 | this.duplex = duplex; 15 | this.pagesPrinted = 0; 16 | } 17 | 18 | public int addToner(int tonerAmmount){ 19 | if(tonerAmount > 0 && tonerAmount <= 100){ 20 | if(this.tonerlevel + tonerAmount > 100) { 21 | return -1; 22 | } 23 | this.tonerLevel += tonerAmount; 24 | return this.tonerLevel; 25 | }else { 26 | return -1; 27 | } 28 | } 29 | 30 | public int printPages(int pages){ 31 | int pagesToPrint = pages; 32 | if(this.duplex) { 33 | pagesToPrint = (pages / 2) + (pages % 2); 34 | System.out.println("Printing in duplex mode"); 35 | } 36 | this.pagesPrinted += pagesToPrint; 37 | return pagesToPrint; 38 | } 39 | 40 | public int getPagesPrinted() { 41 | return pagesPrinted; 42 | } 43 | 44 | }// Printer class 45 | -------------------------------------------------------------------------------- /EqualSumChecker.java: -------------------------------------------------------------------------------- 1 | /***********************************************************CODE EXERCISE 6: EQUAL SUM CHECKER********************************************************** 2 | Description Exercise: 3 | - Write a method hasEqualSum with 3 parameters of type int 4 | - 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. 5 | - Otherwise, return false. 6 | 7 | NOTES: 8 | - The hasEqualSum methodneeds to be defined as public static 9 | - This code solution does not contain main method. 10 | *********************************************************************************CODE******************************************************************/ 11 | 12 | public class EqualSumChecker { 13 | 14 | public static boolean hasEqualSum (int num1, int num2, int num3) { 15 | 16 | if ((num1 + num2) == num3){ 17 | 18 | return true; 19 | 20 | } 21 | else { 22 | 23 | return false; 24 | 25 | } 26 | 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /EvenDigitSum.java: -------------------------------------------------------------------------------- 1 | /*******************************************************************CODING EXERCISE 17: EVEN DIGIT SUM************************************************************* 2 | DESCRIPTION EXERCISE: 3 | - Write a method named getEvenDigitSum with one parameter of type int called number 4 | - The method should return the sume of the even digits within the number 5 | - If the number is negative, the method should return -1 to indicate an invalid value 6 | NOTE: 7 | - The method getEvenDigitSum should be defined as public static like 8 | 9 | *****************************************************************************CODE**********************************************************************************/ 10 | 11 | public class EvenDigtSum { 12 | 13 | public static void main(String [] args){ 14 | 15 | System.out.println(getEvenDigitSum(number: 252)); 16 | 17 | } 18 | public static int getEvenDigitSum(int number) { 19 | int sumEvenDigits = 0; 20 | if (number < 0) 21 | return -1; 22 | 23 | while (number > 0) { 24 | int evenDigits = number % 10; 25 | if (evenDigits % 2 == 0 ) 26 | sumEvenDigits += evenDigits; 27 | number /= 10; 28 | } 29 | return sumEvenDigits; 30 | }//end of getEvenDigitSum method 31 | 32 | }//end of main class 33 | -------------------------------------------------------------------------------- /FactorPrinter.java: -------------------------------------------------------------------------------- 1 | /************************************************CODING EXERCISE 21: ALL FACTORS******************************************* 2 | DESCRIPTION EXERCISE: 3 | - Write a method named printerFactors with 1 parameter of type int named number 4 | - If number < 1, the method should print "Invalid Value" 5 | - The method should print all factors of the number. A factor of a number is an integer which divides that numbers wholy 6 | (i.e. without leaving a remainder) 7 | HINT: 8 | - Use a while or for loop statement 9 | NOTE: 10 | - When printing numbers, each number can be in its own line. They don't have to be separated by a space 11 | - The method printFactors shoud be defined as a public static 12 | *********************************************************CODE*************************************************************/ 13 | public class FactorPrinter { 14 | 15 | public static void main(String [] args) { 16 | 17 | System.out.println(printFactors(6)); 18 | 19 | } 20 | public static void printFactors(int number) { 21 | 22 | if(number < 1) { 23 | 24 | System.out.println("Invalid Value"); 25 | 26 | } 27 | int factor = 0; 28 | for(int i = 1; i <= number; i++) { 29 | 30 | if(number % i == 0){ 31 | 32 | factor = i; 33 | System.out.println(factor); 34 | 35 | } 36 | 37 | } 38 | 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /FirstLastDigitSum.java: -------------------------------------------------------------------------------- 1 | /************************************************************CODING EXERCISE 16: FIRST AND LAST DIGIT SUM******************************************************* 2 | DESCRIPTION EXERCISE: 3 | - Write a method named sumFirstAndLastDigit with one parameter of type int called number 4 | - The method needs to find the first and last digit of the parameter number passed to the method, using a loop and return the sum of the first and the last 5 | digit of that number 6 | - If the number is negative then the method needs to return -1 to indicate an invalid value 7 | NOTE: 8 | - The method sumFirstAndLastDigit needs to be defined as public static 9 | - As per the exercise solution solution, do not add a main method 10 | ********************************************************************************CODE*************************************************************************** 11 | 12 | public class FirstLastDigitSum { 13 | 14 | public static void main (String [] args) { 15 | 16 | System.out.println(sumFirstAndLastDigit (number: 252) ); 17 | 18 | }// end of main method 19 | 20 | public static int sumFirstAndLastDigit( int number){ 21 | 22 | if (number < 0){ 23 | return -1; 24 | } 25 | 26 | int lastDigit = number % 10; 27 | 28 | while( number >= 10){ 29 | number /= 10; 30 | 31 | } 32 | 33 | return (number + lastDigit); 34 | 35 | } // end of sumFirstAndLastDigit method 36 | 37 | }// end of main class 38 | -------------------------------------------------------------------------------- /FlourPack.java: -------------------------------------------------------------------------------- 1 | /***************************************************CODING EXERCISE 24: FLOUR PACK********************************************************* 2 | DESCRIPTION EXERCISE: 3 | - Write a method named canPack with 3 parameters of type int named bigCount, smallCount and goal 4 | - The parameter bigCount represents the count of big flour bags(5 kilos each) 5 | - The parameter smallCount represents the count of small flour bag (1 kilo each) 6 | - The parameter goal represents the goal amount of kilos of flour needed to assemble a package 7 | - Therefore, the sum of kilos of bigCount and smallCount must be at least eqaul to the value of goal. The method should return true if it 8 | is possible to make a package with goal kilos of flour 9 | - If the sum is greater than goal, ensure that only full bags are used towards the goal amount. 10 | - If any of the parameters are negative, return false. 11 | NOTE: The method canPack shoulde be defined as a public static 12 | ********************************************************************CODE*****************************************************************/ 13 | public class FlourPack { 14 | 15 | public static void main(String [] args) { 16 | 17 | System.out.println(canPack(1, 0, 4)); 18 | 19 | } 20 | public static boolean canPack(in bigCount, int smallCount, int goal) { 21 | 22 | int sumOfKilos = 0; 23 | bigCount *= 5; 24 | sumOfKilos = bigCount + smallCount; 25 | 26 | if(bigCount < 0 || smallCount < 0 || goal < 0 || sumOfKilos < goal) { 27 | 28 | return false; 29 | 30 | } else if(sumOfKilos == goal) { 31 | 32 | return true; 33 | 34 | } 35 | if(smallCount == 0){ 36 | 37 | if(bigCount % goal == 0) { 38 | 39 | return true; 40 | 41 | }else { 42 | 43 | return false; 44 | 45 | } 46 | 47 | } else { 48 | 49 | if(bigCount > goal && bigCount % goal != 0) { 50 | 51 | return true; 52 | 53 | }else { 54 | 55 | return false; 56 | 57 | } 58 | 59 | } 60 | 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /ForLoopSum.java: -------------------------------------------------------------------------------- 1 | /*************************************************CHALLENGE:FOR LOOP - SUM 3 AND 5********************************************************************************* 2 | DESCRIPTION CHALLENGE: 3 | - Create a for statement using a range of numbers from 1 to 1000 inclusive. 4 | - Sum all the numbers that can be divided with both 3 and also with 5. 5 | - For those numbers tha met the above conditions, print out the number. 6 | - Break out of the loop once you find 5 numbers that met the above conditions. 7 | - After breaking out of the loop print the sum of the numbers that met the above conditions. 8 | NOTE: Type all code in main method. 9 | *************************************************************************CODE************************************************************************************** 10 | 11 | public class ForLoopSum { 12 | 13 | public static void main(String [] args) { 14 | 15 | int count = 0; 16 | int sum = 0; 17 | 18 | for(int i = 1; i <= 1000; i++) { 19 | if((i % 3 == 0) && (i % 5 == 0)) { 20 | count++; 21 | sum += i; 22 | System.out.println("Found number = " + i); 23 | } 24 | if(count == 5) { 25 | break; 26 | } 27 | } 28 | System.out.println("Sum = " + sum); 29 | 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /GreatestCommonDivisor.java: -------------------------------------------------------------------------------- 1 | /********************************************CODING EXERCISE 20: GREATEST COMMON DIVISOR************************************** 2 | DESCRIPTION EXERCISE: 3 | - Write a method named getGreatestCommonDivisor with 2 parameters of type int named first and second 4 | - If one of the parameters < 10, the method should return -1 to indicate an invalid value. 5 | - The method should return the greatest common divisor of the two numbers (int) 6 | - The greatest common divisor is the largest positive integer that can fully divide each of the integers(i.e. without leaving 7 | a remainder) 8 | HINT: 9 | - Use a while or for loop statement and check if both numbers can be divided without a remainder 10 | - Find the minimum of the two numbers. 11 | NOTE: 12 | - The method getGreatestCommonDivisor should be defined as a public static 13 | *************************************************************CODE*************************************************************/ 14 | public class GreatestCommonDivisor { 15 | 16 | public static void main(String [] args) { 17 | 18 | System.out.println(getGreatestCommonDivisor(25,15)); 19 | 20 | } 21 | public static int getGreatestCommonDivisor(int first, int second) { 22 | 23 | if(first < 10 || second < 10) { 24 | 25 | return -1; 26 | 27 | } 28 | while(first != second) { 29 | 30 | if(first > second) { 31 | 32 | first -= second; 33 | 34 | } 35 | else { 36 | 37 | second -= first; 38 | 39 | } 40 | 41 | } 42 | return first; 43 | 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /Inheritance-Challenge/Car.java: -------------------------------------------------------------------------------- 1 | public class Car extends Vehicle { 2 | 3 | private int wheels; 4 | private int doors; 5 | private int gears; 6 | private boolean isManual; 7 | 8 | public Car(String name, String size, int wheels, int doors, int gears, boolean isManual) { 9 | 10 | super(name, size); 11 | this.wheels = wheels; 12 | this.doors = doors; 13 | this.gears = gears; 14 | this.isManual = isManual; 15 | this.currentGear 16 | 17 | } 18 | 19 | public void changeGear(int currentGeare) { 20 | this.currentGear = currentGear; 21 | System.out.println("Car.setCurrentGear(): Changed to " + this.currentGear + " gear."); 22 | 23 | } 24 | 25 | public void changeVelocity(int speed, int direction0 { 26 | System.out.println("Car.changeVelocity() : Velocity " + speed + " direction " + direction); 27 | move(speed, direction); 28 | 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /Inheritance-Challenge/Main.java: -------------------------------------------------------------------------------- 1 | /**********************************************************Inheritance Challenge******************************************************************** 2 | Challenge Description: 3 | - Start with a base class of a Vehicle, then create a Car class that inherits from this base class 4 | - Finally, create another class, a specific type of Car that inherits from the Car class 5 | - You should be able to hand steering, change gear, and moving(Speed in other words). 6 | - You'll want to decide where to put the appropriate state and behaviors (fields and methods) 7 | - As mentioned above, changing gears, increasing/decreasing speed should be included 8 | - For you specific type of vehicle, you'll want to add something for that type of car 9 | ****************************************************************************************************************************************************/ 10 | 11 | public class Main { 12 | 13 | public static void main(String[] args){ 14 | 15 | Outlander outlander = new Outlander(36); 16 | outlander.steer(45); 17 | outlander.accelerate(30); 18 | outlander.accelerate(20); 19 | outlander.accelerate(-42); 20 | 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /Inheritance-Challenge/Outlander.java: -------------------------------------------------------------------------------- 1 | public class Outlander extends Car { 2 | 3 | private int roadServiceMonths; 4 | 5 | public Outlander(int roadServiceMonths) { 6 | 7 | super("Outlander", "4WD", 5, 5, 6, false); 8 | this.roadServiceMonths = roadServiceMonths; 9 | 10 | } 11 | 12 | public void accelerate(int rate) { 13 | 14 | int newVelocity = getCurrentVelocity() + rate; 15 | if(newVelocity == 0) { 16 | stop(); 17 | changeGear(1); 18 | } else if(newVelocity > 0 && newVelocity <= 10) { 19 | changeGear(1); 20 | }else if(newVelocity > 10 && newVelocity <= 20) { 21 | changeGear(2); 22 | }else if(newVelocity > 20 && newVelocity <= 30) { 23 | changeGear(3); 24 | }else { 25 | changeGear(4); 26 | } 27 | 28 | if(newVelocity > 0) { 29 | changeVelocity(newVelocity, getCurrentDirection()); 30 | } 31 | 32 | 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /Inheritance-Challenge/Vehicle.java: -------------------------------------------------------------------------------- 1 | public class Vehicle{ 2 | 3 | private String name: 4 | private String size; 5 | 6 | private int currentVelocity; 7 | private int currentDirection; 8 | 9 | public Vehicle(String name, String size) { 10 | 11 | this.name = name; 12 | this.size = size; 13 | 14 | this.currentVelocity = 0; 15 | this.currentDirection = 0; 16 | 17 | } 18 | 19 | public void Steer(int direction){ 20 | 21 | this.currentDirection += direction; 22 | System.out.println("Vehicle .steer(): Steering at " + currentDirection + " in direction " degrees."); 23 | 24 | } 25 | 26 | public void move(int velocity, int direction) { 27 | 28 | currentVelocity = velocity; 29 | currentDirection = direction; 30 | System.out.println("Vehicle.move(): Moving at " + currentVelocity + " in direction " + currentDirection); 31 | 32 | } 33 | 34 | public String getName() { 35 | return name; 36 | } 37 | 38 | public String size() { 39 | return size; 40 | } 41 | 42 | public int getCurrentVelocity() { 43 | return currentVelocity; 44 | } 45 | 46 | public int getCurrentDirection() { 47 | return currentDirection; 48 | } 49 | 50 | public void stop() { 51 | this.currentVelocity = 0; 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /InputCalculator.java: -------------------------------------------------------------------------------- 1 | /***********************************************************************CODING EXERCISE 27: INPUT CALCULATOR************************************************************ 2 | DESCRIPTION EXERCISE: 3 | Write a method called inputThenPrintSumAndAverage that does not have any parameters. 4 | 5 | The method should not return anything (void) and it needs to keep reading int numbers from the keyboard. 6 | 7 | When the user enters something that is not an int then it needs to print a message in the format "SUM = XX AVG = YY". 8 | 9 | XX represents the sum of all entered numbers of type int. 10 | YY represents the calculated average of all numbers of type long. 11 | 12 | EXAMPLES OF INPUT/OUTPUT: 13 | 14 | EXAMPLE 1: 15 | 16 | INPUT: 17 | 18 | 1 19 | 2 20 | 3 21 | 4 22 | 5 23 | a 24 | 25 | OUTPUT 26 | 27 | SUM = 15 AVG = 3 28 | 29 | 30 | EXAMPLE 2: 31 | 32 | INPUT: 33 | 34 | hello 35 | 36 | OUTPUT: 37 | 38 | SUM = 0 AVG = 0 39 | 40 | 41 | TIP: Use Scanner to read an input from the user. 42 | 43 | TIP: Use casting when calling the round method since it needs double as a parameter. 44 | 45 | NOTE: Use the method Math.round to round the calculated average (double). The method round returns long. 46 | 47 | NOTE: Be mindful of spaces in the printed message. 48 | 49 | NOTE: Be mindful of users who may type an invalid input right away (see example above). 50 | 51 | NOTE: The method inputThenPrintSumAndAverage should be defined as public static like we have been doing so far in the course. 52 | 53 | NOTE: Do not add the main method to the solution code. 54 | 55 | ********************************************************************************CODE**********************************************************************************/ 56 | import java.util.Scanner; 57 | 58 | public class InputCalculator { 59 | // Write your code here 60 | public static void inputThenPrintSumAndAverage() { 61 | 62 | Scanner scanner = new Scanner(System.in); 63 | 64 | int sum = 0; 65 | int counter = 0; 66 | long average = 0; 67 | 68 | while (true) { 69 | 70 | boolean isAnInt = scanner.hasNextInt(); 71 | 72 | if (isAnInt) { 73 | int num = scanner.nextInt(); 74 | counter++; 75 | sum += num; 76 | average = Math.round((double) sum / counter); 77 | } else { 78 | break; 79 | } 80 | 81 | scanner.nextLine();// handles input keyboard 82 | } 83 | System.out.println("SUM = " + sum + " AVG = " + average); 84 | scanner.close(); 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /IntEqualPrinter.java: -------------------------------------------------------------------------------- 1 | /************************************************************CODING EXERCISE 9: EQUALITY PRINTER********************************************************** 2 | Description Exercise: 3 | - Write a method printEqual with 3 parameters of type int. 4 | - The method should not return anything (void). 5 | - If one of the parameters is less than 0, print text "Invalid Value" 6 | - If all numbers are equal print text "All numbers are equal" 7 | - If all numbers are different print text "All numbers are different" 8 | - Otherwise, print text "Neither all are equal or different" 9 | 10 | NOTES: 11 | - The method printEqual needs to be defined as a public static 12 | - This solution code does not contain a main method. 13 | ********************************************************************************CODE*********************************************************************/ 14 | 15 | public class IntEqualPrinter { 16 | 17 | public static void printEqual(int fNumber, int sNumber, int tNumber) { 18 | 19 | if (fNumber < 0 || sNumber 0 || tNumber < 0) { 20 | 21 | System.out.pintln("Invalid Value"); 22 | 23 | } 24 | else if (fNumber == sNumber && fNumber == tNumber && sNumber == tNumber) { 25 | 26 | System.out.println("All numbers are equal"); 27 | 28 | } 29 | else if (fNumber != sNumber && fNumber != tNumber && sNumber != tNumber) { 30 | 31 | System.out.println("All numbers are different"); 32 | 33 | } 34 | else { 35 | 36 | System.out.println("Neither all are equal or different"); 37 | 38 | } 39 | 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /LargestPrime.java: -------------------------------------------------------------------------------- 1 | /**********************************************************CODING EXERCISE 25: LARGEST PRIME**************************************************************************** 2 | 3 | DESCRIPTION EXERCISE 4 | 5 | Write a method named getLargestPrime with one parameter of type int named number. 6 | 7 | If the number is negative or does not have any prime numbers, the method should return -1 to indicate an invalid value. 8 | 9 | 10 | The method should calculate the largest prime factor of a given number and return it. 11 | 12 | 13 | EXAMPLE INPUT/OUTPUT: 14 | 15 | * getLargestPrime (21); should return 7 since 7 is the largest prime (3 * 7 = 21) 16 | 17 | * getLargestPrime (217); should return 31 since 31 is the largest prime (7 * 31 = 217) 18 | 19 | * getLargestPrime (0); should return -1 since 0 does not have any prime numbers 20 | 21 | * getLargestPrime (45); should return 5 since 5 is the largest prime (3 * 3 * 5 = 45) 22 | 23 | * getLargestPrime (-1); should return -1 since the parameter is negative 24 | 25 | 26 | HINT: Since the numbers 0 and 1 are not considered prime numbers, they cannot contain prime numbers. 27 | 28 | NOTE: The method getLargestPrime should be defined as public static like we have been doing so far in the course. 29 | 30 | NOTE: Do not add a main method to the solution code. 31 | 32 | ******************************************************************************************CODE***********************************************************************/ 33 | 34 | public class LargestPrime { 35 | // write your code here 36 | public static int getLargestPrime(int number) { 37 | 38 | if (number <= 0 || number <= 1) { 39 | return -1; 40 | } 41 | else { 42 | int largestPrime = 2; 43 | while (largestPrime < number) { 44 | if (number % largestPrime != 0) { 45 | largestPrime++; 46 | } else { 47 | number = number / largestPrime; 48 | 49 | } 50 | } 51 | return number; 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /LastDigitChecker.java: -------------------------------------------------------------------------------- 1 | /*********************************************CODING EXERCISE 19: LAST DIGIT CHECKER**************************************** 2 | DESCRIPTION EXERCISE: 3 | Method1: 4 | - Write a method named hasSameLastDigit with 3 parameters of type int. 5 | - Each number should be within the range of 10(inclusive) - 1000(inclusive). If one of the numbers is not within the range, 6 | the method should return false. 7 | - The method should return true if at least two of the numbers share the same rightmost digit; otherwise, it should return 8 | false. 9 | Method2: 10 | - Write another method named isValid with one parameter of type int 11 | - The method needs to return true if the number parameter is in range of 10(inclusive) - 1000(inclusive), otherwise, return 12 | false. 13 | NOTE: 14 | - All methods needs to be defined as a public static 15 | ***************************************************************CODE*********************************************************/ 16 | public class LastDigitChecker { 17 | 18 | public static void main(String [] args){ 19 | 20 | System.out.println(hasSamelastDigit (41,22,71); 21 | System.out.println(isValid (10)); 22 | 23 | } 24 | 25 | public static boolean hasSameLastDigit(int fDigit, int sDigit, int lDigit) { 26 | 27 | if((isValid(fDigit) && isValid(sDigit) && isValid(lDigit))) { 28 | 29 | if((fDigit % 10 == sDigit % 10 || (sDigit % 10 == lDigit % 10 == fDigit % 10))) { 30 | 31 | return true; 32 | 33 | } 34 | 35 | } 36 | return false; 37 | 38 | } 39 | public static boolean isValid(int number) { 40 | 41 | return(number >= 10 && number <= 1000)); 42 | 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /LeapYearCalculator.java: -------------------------------------------------------------------------------- 1 | /**************************************************CODE EXERCISE 4: LEAP YEAR CALCULATOR*************************************************************** 2 | Description Exercise: 3 | - Write a method isLeapYear with a parameter of type int named year. 4 | - The parameter needs to be greater than or equal to 1 and less than or equal to 9999. 5 | - If the parameter is not in that range retrn false. 6 | - 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. 7 | To determine whether a year is a leap year, follow these steps: 8 | 1. If the year is evenly divisible by 4, go to step 2. Otherwise, go to step 5 9 | 2. If the year is evenly divisible by 100, go to step 3. Otherwise, got to step 4 10 | 3. If the year is evenly divisible by 400, go to step 4. Otherwise, got to step 5 11 | 4. The year is a leap year (it has 365 days). The method isLeapYear needs to return true 12 | 5. The year is not a leap year(it has 365 days). The method isLeapYear needs to return false. 13 | The following years are not leap years because they are evenly divisible by 100 but not 400: 14 | 1700, 1800, 2100, 2200, 2300, 2500, 2600 15 | The following years are leap years because they are evenly divisible by 100 and 400: 16 | 1600, 2000, 2400 17 | 18 | NOTE: 19 | - The method isLeapYear needs to be defined as a public static 20 | - The code solution contains no main method. 21 | *************************************************************************CODE*************************************************************************/ 22 | // Recommended Solution 23 | public class LeapYearCalculator { 24 | 25 | public static boolean isLeapYear(int year) { 26 | 27 | return (year > 1 && year < 9999) ? ((year % 4 == 0 && year % 100 != 0) || (year % 100 == 0 && year % 400 == 0)):false; 28 | } 29 | } 30 | //public class LeapYearCalculator { 31 | 32 | // public static boolean isLeapYear (int year) { 33 | 34 | // if (year < 1 || year 9999) { 35 | 36 | // return false; 37 | // } 38 | // else if (year % 4 == 0 && year % 100 != 0) { 39 | 40 | // return true; 41 | // } 42 | // else if (year % 100 == 0 && year % 400 == 0) { 43 | 44 | // return true; 45 | // } 46 | // else { 47 | 48 | // return false; 49 | // } 50 | / } 51 | } 52 | -------------------------------------------------------------------------------- /MegaBytesConver.java: -------------------------------------------------------------------------------- 1 | /********************************************CODE EXERCISE 2: MEGABYTES CONVERTER**************************************************************** 2 | 3 | Description Exercise: 4 | Write a method printMegaBytesAndKilBytes that has 1 parameter of type int with the name kiloBytes. 5 | This method should not return anything(void) and it needs to calculate the megabytes and remaining kilobytes from the kilobytes parameter. 6 | Then it needs to print a message in the format "XX KB = YY MB and ZZ KB". 7 | XX represents the original value kilobytes 8 | YY represents the calculated megabytes 9 | ZZ represents the calculated remaining kilobytes 10 | 11 | TIPS/NOTES: 12 | - Use the remainder operator 13 | - 1 MB = 1024KB 14 | - Do not set kilobytes parameter value inside your method 15 | - The printMegaBytesAndKiloBytes method needs to be defined as public static 16 | 17 | In this code, main method is not included. 18 | 19 | ********************************************************************CODE**************************************************************************/ 20 | 21 | public class MegaBytesConverter { 22 | 23 | public static void printMegaBytesAndKiloBytes (int kiloBytes) { 24 | 25 | if (kiloBytes < 0) { 26 | System.out.println("Invalid Value"); 27 | } 28 | else { 29 | System.out.println(kiloBytes + " KB" + (kiloBytes " MB" " and" + (kiloBytes % 1024) + " kb"); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /MinutesToYearsDaysCalculator.java: -------------------------------------------------------------------------------- 1 | /****************************************************CODING EXERCISE 9: MINUTES TO YEARS AND DAYS CALCULATOR******************************************** 2 | Description Exercise: 3 | - Write a method printYearsAndDays with parameter of type long named minutes. 4 | - The method should not return anything (void) and it needs to calculate the years and days from the minutes parameter. 5 | - If the parameter is less than 0, print text 'Invalid Value". 6 | - Otherwise, if the parameter is valid then it needs to print a message in the format "XX min = YY y and ZZ d". 7 | - XX represents the original value minutes 8 | - YY represents the calculated years 9 | - ZZ represents the calculated days. 10 | 11 | TIPS/NOTES: 12 | - Use remainder operator (%) 13 | - 1hr =60min, 1day = 24hr, 1year = 365days 14 | - The printYearsAndDays methods needs to be defined as a public static 15 | - This code solution does not contain a main method. 16 | ***********************************************************************CODE*****************************************************************************/ 17 | 18 | public class MinutesToYearsDaysCalculator { 19 | 20 | public static void printYearsAndDays(long minutes) { 21 | 22 | if (minutes < 0) { 23 | 24 | System.out.println("Invalid Value"); 25 | 26 | } 27 | else { 28 | 29 | long years = (minutes / (365 * 24 * 60)); 30 | long remainingDays = ((minutes / (60 * 24)) % 365); 31 | System.out.println(minutes + " min = " + years + " y and " + remainingDays + " d "); 32 | 33 | } 34 | 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /NumberPalindrome.java: -------------------------------------------------------------------------------- 1 | /****************************************************************CODING EXERCISE 15: NUMBER PALINDROME**************************************************************** 2 | DESCRIPTION EXERCISE: 3 | - Write a method called isPalindrome with one int parameter called number 4 | - The method needs to return a boolean 5 | - It should return true if the number is a palindrome number otherwise it should return false 6 | - Check the tips below for more info about palindromes 7 | 8 | TIP: Logic to Check a Palindrome Number 9 | - Find the reverse of the given number. Store it in some variable say reverse. Compare the number withe reverse 10 | - If both are the same then the nmber is a palindrome otherwise it is not. 11 | TIP: Logic to Reverse a Number 12 | - Declare and initialize another variable to store the reverse of a number, for example reverse = 0 13 | - Extract the last digit of the given number by performing the modulo division (remainder). 14 | - Store the last digit to some variable say lastDigit = num % 10 15 | - Increase the place value of reverse by one 16 | - To increase place value multiply the reverse variable by 10. e.g. reverse = reverse * 10 17 | - Add lastDigit to reverse 18 | - Since the last digit of the number is processed, remove the last digit of num. To remove the last digit divide number by 10 19 | - Repeat steps until number is not equal to (or greater than) zero 20 | - A While loop would be good for this coding exercise 21 | 22 | - Be careful with negative numbers. They can also be a palindrome numbers 23 | - Be careful with reversing a number, you'll need a parameter for comparing a reversed number with the starting number(parameter) 24 | NOTE: The method isPalindrome needs to be defined as a public static 25 | *****************************************************************************CODE**********************************************************************************/ 26 | 27 | public class NumberPalindrome { 28 | 29 | public static void main(String [] args) { 30 | 31 | System.out.println(isPalindrome (number: 1221)); 32 | 33 | } 34 | 35 | public static boolean isPalindrome(int number){ 36 | 37 | int reverse = 0; 38 | int originalNumber = number; 39 | 40 | while (number !=0){ 41 | int lastDigit = number % 10; 42 | reverse = (reverse * 10) + lastDigit; 43 | number /= 10; 44 | } 45 | 46 | return originalNumber == reverse; 47 | 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /NumberTwoWords.java: -------------------------------------------------------------------------------- 1 | /*************************************************CODING EXERCISE 23: NUMBER TO WORDS****************************************** 2 | DESCRIPTION EXERCISE: 3 | Method1: 4 | - Write a method called numberToWords with 1 int parameter named number 5 | - The method should print out the passed number using word for the digits 6 | - If the number is negative, print "Invalid Value" 7 | Steps to Print the Number as Words: 8 | 1. Extract the last digit of the given number using the remainder operator 9 | 2. Convert the value of the digit found in Step 1 into a word. There are 10 possible values for that digit, those 10 | being 0,1,2,3,4,5,6,7,8,9. Print the corresponding word for each digit. e.g. print "Zero" if the digit is 0, "One" 11 | if the digit is 1, and so on. 12 | 3. Remove the last digit from the number 13 | 4. Repeat Step 2 through 4 until the number is 0 14 | Method 2: 15 | - The logic abobe is correct, but in its current state, the words will be printed in reverse order. For example, if the 16 | number is 234, the logic above will produce the output "Four Three Two" instead of "Two Three Four". To overcome this 17 | problem, write a second method called reverse. 18 | - The method reverse should have 1 int parameter and return the reversed number(int). For example, if the number passed 19 | is 234, then the reversed number would be 432. The method reverse should also reverse negative numbers 20 | - Use the method reverse within the method numberToWords in order to print the words in the correct order. 21 | - Another thing to keep in mind is any reversed number with leading zeroes (e.g. the reversed number for 100 is 001). 22 | The logic above for the metho numberToWords will print "One", but that is incorrect. It should print "OneZeroOne". To 23 | solve this problem, write a third method called getDigitCount 24 | Method 3: 25 | - The method getDigitCount should have 1 int parameter called number and return the count of the digits in that number. 26 | If the number is negative, return -1 to indicate an invalid value. 27 | - For example, if the number has a value of 100, the method getDigitCount should return 3 since the number 10 has 3 28 | digits (1,0,0). 29 | HINTS: 30 | - Use a for loop statement to print zeroes after reversing the number. As seen in a previous example, 100 reversed 31 | becomes 1, but the method numberToWords should print "OneZeroZero". To get the number of zeroes, check the difference 32 | between the digit count from the original number and the reversed number. 33 | NOTES: 34 | - When printing words, each word can be in its own line 35 | - They don't have to be separated by a space 36 | - The method numberToWords, getDigitCount, reverse should be defined as public static 37 | - In total, you've 3 methods 38 | *********************************************************CODE*****************************************************************/ 39 | public class NumberTwoWords { 40 | 41 | public static void main(String [] args) { 42 | 43 | System.out.println(getDigitCount(0)); 44 | System.out.println(reverse(1234)); 45 | System.out.println(numberToWords(123)); 46 | 47 | } 48 | // write your code here 49 | public static void numberToWords(int number){ 50 | if(number < 0){ 51 | System.out.println("Invalid Value"); 52 | } 53 | else{ 54 | int rev = reverse(number); 55 | int count = getDigitCount(number); 56 | 57 | while(count > 0) { 58 | int lastDigit = rev % 10; 59 | rev = rev / 10; 60 | count--; 61 | 62 | switch (lastDigit) { 63 | case 0: 64 | System.out.println("Zero"); 65 | break; 66 | case 1: 67 | System.out.println("One"); 68 | break; 69 | case 2: 70 | System.out.println("Two"); 71 | break; 72 | case 3: 73 | System.out.println("Three"); 74 | break; 75 | case 4: 76 | System.out.println("Four"); 77 | break; 78 | case 5: 79 | System.out.println("Five"); 80 | break; 81 | case 6: 82 | System.out.println("Six"); 83 | break; 84 | case 7: 85 | System.out.println("Seven"); 86 | break; 87 | case 8: 88 | System.out.println("Eight"); 89 | break; 90 | case 9: 91 | System.out.println("Nine"); 92 | break; 93 | default: 94 | System.out.println(); 95 | } 96 | } 97 | } 98 | } 99 | 100 | public static int reverse(int number){ 101 | int rev = 0; 102 | if(number < 0) { 103 | number = -1 * number; 104 | 105 | while (number > 0) { 106 | int lastDigit = number % 10; 107 | rev = lastDigit + rev * 10; 108 | number /= 10; 109 | } 110 | return - rev; 111 | } 112 | 113 | while (number > 0) { 114 | int lastDigit = number % 10; 115 | rev = lastDigit + rev * 10; 116 | number /= 10; 117 | } 118 | return rev; 119 | } 120 | 121 | public static int getDigitCount(int num){ 122 | if(num < 0){ 123 | return -1; 124 | } 125 | else if(num == 0){ 126 | return 1; 127 | } 128 | int count = 0; 129 | while(num > 0){ 130 | count++; 131 | num /= 10; 132 | } 133 | return count; 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /OOP-Part1&2/Animal.java: -------------------------------------------------------------------------------- 1 | package com.objectorientprogramming; 2 | 3 | public class Animal { 4 | 5 | private String name; 6 | private int brain; 7 | private int body; 8 | private int size; 9 | private int weight; 10 | 11 | public Animal(String name, int brain, int body, int size, int weight) { 12 | this.name = name; 13 | this.brain = brain; 14 | this.body = body; 15 | this.size = size; 16 | this.weight = weight; 17 | } 18 | 19 | public void eat() { 20 | System.out.println("Animal.eat() called"); 21 | 22 | } 23 | 24 | public void move(int speed) { 25 | System.out.println("Animal.move() called. Animal is moving at " +speed); 26 | 27 | } 28 | 29 | 30 | 31 | public String getName() { 32 | return name; 33 | } 34 | 35 | public int getBrain() { 36 | return brain; 37 | } 38 | 39 | public int getBody() { 40 | return body; 41 | } 42 | 43 | public int getSize() { 44 | return size; 45 | } 46 | 47 | public int getWeight() { 48 | return weight; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /OOP-Part1&2/Dog.java: -------------------------------------------------------------------------------- 1 | package com.objectorientedprogramming; 2 | 3 | public class Dog extends Animal { 4 | 5 | private int eyes; 6 | private int legs; 7 | private int tail; 8 | private int teeth; 9 | private String coat; 10 | 11 | public Dog(String name, int size, int weight, int eyes, int legs, int tail, int teeth, String coat) { 12 | super(name, 1, 1, size, weight); 13 | this.eyes = eyes; 14 | this.legs = legs; 15 | this.tail = tail; 16 | this.teeth = teeth; 17 | this.coat = coat; 18 | } 19 | 20 | private void chew() { 21 | System.out.println("Dog.chew() called"); 22 | } 23 | 24 | @Override 25 | public void eat() { 26 | System.out.println("Dog.eat() called"); 27 | chew(); 28 | super.eat(); 29 | } 30 | 31 | public void walk() { 32 | System.out.println("Dog.walk() called"); 33 | super.move(5); 34 | } 35 | 36 | public void run() { 37 | System.out.println("Dog.run() called"); 38 | move(10); 39 | 40 | } 41 | 42 | private void moveLegs(int speed) { 43 | System.out.println("Dog.moveLegs() called"); 44 | } 45 | @Override 46 | public void move(int speed) { 47 | System.out.println("Dog.move() called"); 48 | moveLegs(speed); 49 | super.move(speed); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /OOP-Part1&2/Fish.java: -------------------------------------------------------------------------------- 1 | package com.objectorientedprogramming; 2 | 3 | public class Fish extends Animal { 4 | 5 | private int gills; 6 | private int eyes; 7 | private int fins; 8 | 9 | public Fish(String name, int size, int weight, int gills, int eyes, int fins) { 10 | 11 | super(name, 1, 1, size, weight); 12 | this.gills = gills; 13 | this.eyes = eyes; 14 | this.fins = fins; 15 | } 16 | 17 | private void rest() { 18 | 19 | } 20 | 21 | private void moveMuscles() { 22 | 23 | } 24 | 25 | private void moveBackFin() { 26 | 27 | } 28 | 29 | private void swim(int speed) { 30 | moveMuscles(); 31 | moveBackFin(); 32 | super.move(speed); 33 | 34 | 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /OOP-Part1&2/Main.java: -------------------------------------------------------------------------------- 1 | /*********************************************************CODING CHALLENGE #23**************************************************************************** 2 | 3 | 4 | 5 | *******************************************************************CODE SOLUTION*************************************************************************** 6 | package com.objectorientedprogramming; 7 | 8 | public class Main { 9 | 10 | public static void main(String[] args) { 11 | Animal animal = new Animal("Animal", 1, 1, 5, 5); 12 | 13 | Dog dog = new Dog("Yorkie", 8, 20, 2, 4, 1, 20, "long silky"); 14 | // dog.eat(); 15 | dog.walk(); 16 | // dog.run(); 17 | 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /PaintJob.java: -------------------------------------------------------------------------------- 1 | /******************************************************************CODING EXERCISE 28: PAINT JOB********************************************************************** 2 | DESCRIPTION EXERCISE: 3 | 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. 4 | 5 | 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. 6 | 7 | The second parameter should be named height of type double. This parameter represents the height of the wall. 8 | 9 | The third parameter should be named areaPerBucket. This parameter represents the area that can be covered with one bucket of paint. 10 | 11 | The fourth parameter should be named extraBuckets. This parameter represents the bucket count that Bob has at home. 12 | 13 | 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. 14 | 15 | 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. 16 | 17 | If all parameters are valid, the method needs to calculate the number of buckets and return it. 18 | 19 | 20 | Examples of input/output: 21 | 22 | *getBucketCount(-3.4, 2.1, 1.5, 2); → should return -1 since the width parameter is invalid 23 | 24 | *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. 25 | 26 | *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. 27 | 28 | 29 | 30 | 2. Bob does not like to enter 0 for the extraBuckets parameter so he needs another method. 31 | 32 | Write another overloaded method named getBucketCount with 3 parameters namely width, height, and areaPerBucket (all of type double). 33 | 34 | 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. 35 | 36 | 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. 37 | 38 | If all parameters are valid, the method needs to calculate the number of buckets and return it. 39 | 40 | 41 | Examples of input/output: 42 | 43 | *getBucketCount(-3.4, 2.1, 1.5); → should return -1 since the width parameter is invalid 44 | 45 | *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. 46 | 47 | *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. 48 | 49 | 50 | 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. 51 | 52 | Write another overloaded method named getBucketCount with 2 parameters namely, area and areaPerBucket (both of type double). 53 | 54 | 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. 55 | 56 | If one of the parameters area or areaPerBucket is less or equal to 0, the method needs to return -1to indicate an invalid value. 57 | 58 | If all parameters are valid, the method needs to calculate the number of buckets and return it. 59 | 60 | 61 | Examples of input/output: 62 | 63 | *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 64 | 65 | *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. 66 | 67 | *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 . 68 | 69 | Do your best to help Bob. 70 | 71 | 72 | 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. 73 | 74 | NOTE: All methods should be defined as public static like we have been doing so far in the course. 75 | 76 | NOTE: Do not add the main method to the solution code. 77 | 78 | 79 | **********************************************************************************CODE**********************************************************************************/ 80 | 81 | public class PaintJob { 82 | // write your code here 83 | public static int getBucketCount(double width, double height, double areaPerBucket, int extraBuckets){ 84 | 85 | if(width <= 0 || height <= 0 || areaPerBucket <= 0 || extraBuckets < 0){ 86 | return -1; 87 | } 88 | int numOfBuckets = (int) Math.ceil((width * height) / areaPerBucket); 89 | numOfBuckets -= extraBuckets; 90 | return numOfBuckets; 91 | }// end of getBucketCount method 1 92 | 93 | public static int getBucketCount(double width, double height, double areaPerBucket){ 94 | 95 | if(width <= 0 || height <= 0 || areaPerBucket <= 0){ 96 | return -1; 97 | } 98 | 99 | int numOfBuckets = (int) Math.ceil((width * height) / areaPerBucket); 100 | return numOfBuckets; 101 | 102 | }// end of getBucketCount method 2 103 | 104 | public static int getBucketCount(double area, double areaPerBucket){ 105 | 106 | if(area <= 0 || areaPerBucket <= 0){ 107 | return -1; 108 | } 109 | int numOfBuckets = (int) Math.ceil(area / areaPerBucket); 110 | return numOfBuckets; 111 | } // end of getBucketCount method 3 112 | } 113 | -------------------------------------------------------------------------------- /PerfectNumber.java: -------------------------------------------------------------------------------- 1 | /*********************************************CODING EXERCISE 22: PERFECT NUMBER*********************************************** 2 | DESCRIPTION EXERCISE: 3 | - A perfect number is a positive integer which is equal to the sum of its proper positive divisors. 4 | - Proper positive divisors are positive integers that fully divide the perfect number without leaving a remainder and 5 | exclude the perfect number itself. 6 is a perfect number 6 | * Write a method named isPerfectNumber with 1 parameter of type int named number 7 | * If number is < 1, the method should return false 8 | * The method must calculate if the number is perfect. If the number is perfect, the method should retrun true; otherwise, 9 | it should return false. 10 | HINT: 11 | - Use a while or for loop statement 12 | - Use the remainder operator 13 | NOTE: 14 | - The method isPerfectNumber should be defined as public static 15 | *****************************************************************CODE*********************************************************/ 16 | public class PerfectNumber { 17 | 18 | public static void main(String [] args) { 19 | 20 | System.out.println(isPerfectNumber(6)); 21 | 22 | } 23 | 24 | public static boolean isPerfectNumber(int number) { 25 | 26 | if(number < 1) { 27 | 28 | return false; 29 | 30 | } 31 | int perfect = 0; 32 | for(int i = 1; i < number; i++) { 33 | 34 | if(number % i == 0) { 35 | 36 | perfect += i; 37 | 38 | } 39 | if(perfect == number) { 40 | 41 | return true; 42 | 43 | } 44 | 45 | } 46 | return false; 47 | 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /Person.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************CODING EXERCISE 30: PERSON********************************************************************** 2 | DESCRIPTION EXERCISE: 3 | 4 | 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. 5 | 6 | Write the following methods (instance methods): 7 | 8 | *Method named getFirstName without any parameters, it needs to return the value of the firstName field. 9 | *Method named getLastName without any parameters, it needs to return the value of the lastName field. 10 | *Method named getAge without any parameters, it needs to return the value of the age field. 11 | *Method named setFirstName with one parameter of type String, it needs to set the value of the firstName field. 12 | *Method named setLastName with one parameter of type String, it needs to set the value of the lastName field. 13 | *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. 14 | *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. 15 | *Method named getFullName without any parameters, it needs to return the full name of the person. 16 | *In case both firstName and lastName fields are empty, Strings return an empty String. 17 | *In case lastName is an empty String, return firstName. 18 | *In case firstName is an empty String, return lastName. 19 | 20 | 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. 21 | 22 | TEST EXAMPLE 23 | 24 | TEST CODE: 25 | 26 | Person person = new Person(); 27 | person.setFirstName(""); // firstName is set to empty string 28 | person.setLastName(""); // lastName is set to empty string 29 | person.setAge(10); 30 | System.out.println("fullName= " + person.getFullName()); 31 | System.out.println("teen= " + person.isTeen()); 32 | person.setFirstName("John"); // firstName is set to John 33 | person.setAge(18); 34 | System.out.println("fullName= " + person.getFullName()); 35 | System.out.println("teen= " + person.isTeen()); 36 | person.setLastName("Smith"); // lastName is set to Smith 37 | System.out.println("fullName= " + person.getFullName()); 38 | 39 | OUTPUT 40 | 41 | fullName= 42 | teen= false 43 | fullName= John 44 | teen= true 45 | fullName= John Smith 46 | 47 | 48 | NOTE: All methods should be defined as public NOT public static. 49 | 50 | NOTE: In total, you have to write 8 methods. 51 | 52 | NOTE: Do not add the main method to the solution code. 53 | ******************************************************************************************CODE*****************************************************************************/ 54 | 55 | public class Person { 56 | // write your code here 57 | private String firstName; 58 | private String lastName; 59 | private int age; 60 | 61 | public String getFirstName(){ 62 | return firstName; 63 | } 64 | 65 | public String getLastName(){ 66 | return lastName; 67 | } 68 | 69 | public int getAge(){ 70 | return age; 71 | } 72 | 73 | public void setFirstName(String firstName){ 74 | this.firstName = firstName; 75 | } 76 | 77 | public void setLastName (String lastName){ 78 | this.lastName = lastName; 79 | } 80 | 81 | public void setAge(int age) { 82 | if (age > 0 && age <= 100) { 83 | this.age = age; 84 | }else { 85 | this.age = 0; 86 | } 87 | } 88 | 89 | public boolean isTeen (){ 90 | if (age > 12 && age < 20){ 91 | return true; 92 | } 93 | return false; 94 | } 95 | 96 | public String getFullName (){ 97 | if (firstName.isEmpty()) { 98 | return lastName; 99 | } 100 | if (lastName.isEmpty()){ 101 | return firstName; 102 | } 103 | if (firstName.isEmpty() && lastName.isEmpty()){ 104 | return " "; 105 | } 106 | else { 107 | return firstName + " " + lastName; 108 | } 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /PlayingCat.java: -------------------------------------------------------------------------------- 1 | /************************************************************CODING EXERCISE 11: PLAYING CAT************************************************************ 2 | Description Exercise: 3 | - 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 4 | the upper limit is 45 (inclusive) instead of 35. 5 | - Write a method isCatPlaying that has 2 parameters 6 | - Method needs to return if the cat is playing, otherwise, return false. 7 | - 1st parameter should be of type boolean and be named summer - it represents if it is summer 8 | - 2nd parameter represents the temperature and is of type int with the name temperature. 9 | 10 | NOTES: 11 | - The isCatPlaying method needs to be defined as public static 12 | - This code solution has no main method. 13 | ******************************************************************************CODE**********************************************************************/ 14 | 15 | public class PlayingCat { 16 | 17 | public static boolean isCatPlaying (boolean summer, it temperature) { 18 | 19 | return ((temperature >= 25 && temperature <=35) || (temperature >= 25 && temperature <=45 && summer)); 20 | 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /Polymorphism/Challenge/Forgetable.java: -------------------------------------------------------------------------------- 1 | class Forgetable extends Movie { 2 | public Forgetable() { 3 | super("Forgetable"); 4 | } 5 | // no plot method 6 | } 7 | -------------------------------------------------------------------------------- /Polymorphism/Challenge/IndependenceDay.java: -------------------------------------------------------------------------------- 1 | class IndependenceDay extends Movie { 2 | public IndependenceDay() { 3 | super("IndependenceDay"); 4 | } 5 | 6 | @Override 7 | public String plot() { 8 | return "Aliens attempt to take over planet earth"; 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /Polymorphism/Challenge/Jaws.java: -------------------------------------------------------------------------------- 1 | class Jaws extends Movie { 2 | public Jaws(){ 3 | super("Jaws"); 4 | } 5 | public String plot(){ 6 | return "A shark eats lots of people"; 7 | } 8 | 9 | } 10 | -------------------------------------------------------------------------------- /Polymorphism/Challenge/Main.java: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Polymorphism/Challenge/MazeRunner.java: -------------------------------------------------------------------------------- 1 | class MazeRunner extends Movie { 2 | public MazeRunner(){ 3 | super("Maze Runner"); 4 | } 5 | @Override 6 | public String plot(){ 7 | return "Kids try and escape a maze" 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Polymorphism/Challenge/Movie.java: -------------------------------------------------------------------------------- 1 | public class Movie { 2 | private String name; 3 | 4 | public Movie(String name) 5 | this.name = name; 6 | { 7 | 8 | public String getName(){ 9 | return name; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Polymorphism/Challenge/StarWars.java: -------------------------------------------------------------------------------- 1 | class StarWars extends Movie { 2 | public StarWars(){ 3 | super("Star Wars); 4 | } 5 | @Override 6 | public String plot() { 7 | return"Imperial Forces try to take over the universe"; 8 | } 9 | 10 | } 11 | -------------------------------------------------------------------------------- /Polymorphism/Challenge2/Car.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************************************************************************* 2 | Polymorphism Challenge Description: 3 | Car Analogy: 4 | - Create a base class called Car 5 | - It should have a few fields that would be appropriate for a generic car class 6 | - engine, cylinders, wheels, etc. 7 | - Constructors should initialize cylinders (number of) and name, and set wheels to 4 and engine to true 8 | - Cylinders and names would be passed parameters. 9 | - Create appropriate getters 10 | - Create some methods like startEngine, accelerate, and brake 11 | - show a message for each in the base class 12 | - Now, create 3 sub classes for your favorite vehicles 13 | - Override the appropriate methods to demonstrate polymorphism n use 14 | - put all classes in the one Java file (this one). 15 | *********************************************************************************************************************************************/ 16 | class Car { 17 | private boolean engine; 18 | private int cylinders; 19 | private String name; 20 | private int wheels; 21 | 22 | //constructor 23 | public Car(int cylinders, String name){ 24 | this.cylinders = cylinders; 25 | this.name = name; 26 | this.wheels = 4; 27 | this.engine = true; 28 | } 29 | // getters 30 | public int getCylinders(0{ 31 | return cylinders; 32 | } 33 | public String getName(){ 34 | return name; 35 | } 36 | //methods 37 | public String startEngine(){ 38 | return "Car -> startEngine()"; 39 | } 40 | public String accelerate(){ 41 | return "Car -> accelerate()"; 42 | } 43 | public String brake(){ 44 | return "Car -> brake()"; 45 | } 46 | 47 | }// end of Car class 48 | /*************************************************************************************************************************************************/ 49 | // sub classes 50 | class Mitsubishi { 51 | public Mitsubishi(int cylinders, String name){ 52 | super(cylinders, name); 53 | } 54 | @Override 55 | public String startEngine(){ 56 | return ("Mitsubishi -> startEngiin()"; 57 | } 58 | @Override 59 | public String accelerate(){ 60 | return "Mitsubishi -> accelerate()"; 61 | } 62 | @Override 63 | public String brake(){ 64 | return "Mitsubishi -> brake()"; 65 | } 66 | } 67 | /******************************************************************************************************************************************************/ 68 | class Holden extends Car { 69 | public Holden(int Cylinders, String name){ 70 | super(cylinders, name); 71 | } 72 | @Override 73 | public String startEngine(){ 74 | return getClass().getSimpleName() + " -> startEngine()"; 75 | } 76 | @Override 77 | public String accelerate(){ 78 | return getClass().getSimpleName() + " -> accelerate()"; 79 | } 80 | @Override 81 | publi String brak(){ 82 | return getClass().getSimpleName(0 + " -> brake()"; 83 | } 84 | } 85 | /********************************************************************************************************************************************************/ 86 | class Ford extends Movie{ 87 | public Ford(int cylinders, String name){ 88 | super(cylinders, name); 89 | } 90 | @Override 91 | public String startEngine(){ 92 | return "Ford -> startEngin()"; 93 | } 94 | @Override 95 | public String accelerate(){ 96 | return "Ford -> accelerate()"; 97 | } 98 | @Override 99 | public String brake(){ 100 | return "Ford -> brake()"; 101 | } 102 | } 103 | /*******************************************************************************************************************************************************/ 104 | 105 | 106 | -------------------------------------------------------------------------------- /Polymorphism/Challenge2/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String [] args){ 4 | 5 | Car car = new Car(8, "Base car")' 6 | System.out.println(car.startEngine()); 7 | System.out.println(car.accelerate()); 8 | System.out.println(car.brake()); 9 | 10 | Mitsubishi mitsubishi = new Mitsubishi(6, "Outlander VRX 4WD"); 11 | System.out.println(mitsubishi.startEngine()); 12 | System.out.println(mitsubishi.accelerate()); 13 | System.out.println(mitsubishi.brake()); 14 | 15 | Ford ford = new Ford(6, "Ford Falcon"); 16 | System.out.println(ford.startEngine()); 17 | System.out.println(ford.accelerate()); 18 | System.out.println(ford.brake()); 19 | 20 | Holden holden = new Holden(6, "Holden Commodore"); 21 | System.out.println(holden.startEngine()); 22 | System.out.println(holden.accelerate()); 23 | System.out.println(holden.brake()); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Mastering-Java-Exercises- 2 | Mastering Java Programming Course - Tim Buchalka 3 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Supported Versions 4 | 5 | Use this section to tell people about which versions of your project are 6 | currently being supported with security updates. 7 | 8 | | Version | Supported | 9 | | ------- | ------------------ | 10 | | 5.1.x | :white_check_mark: | 11 | | 5.0.x | :x: | 12 | | 4.0.x | :white_check_mark: | 13 | | < 4.0 | :x: | 14 | 15 | ## Reporting a Vulnerability 16 | 17 | Use this section to tell people how to report a vulnerability. 18 | 19 | Tell them where to go, how often they can expect to get an update on a 20 | reported vulnerability, what to expect if the vulnerability is accepted or 21 | declined, etc. 22 | -------------------------------------------------------------------------------- /SharedDigit.java: -------------------------------------------------------------------------------- 1 | /********************************************************************CODING EXERCISE 18: SHARED DIGIT*************************************************************** 2 | DESCRIPTION EXERCISE: 3 | - Write a method named hasSharedDigit with two parameters of type int. 4 | - 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. 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 | NOTE: 7 | - The method hasSharedDigit should be defined as public static 8 | **********************************************************************************CODE*****************************************************************************/ 9 | 10 | public class SharedDigit { 11 | 12 | public static void main(String [] args) { 13 | 14 | System.out.println(hasSharedDigit (12.23)); 15 | 16 | } 17 | 18 | public static boolean hasSharedDigit(int fNumber, int sNumber) { 19 | 20 | if(fNumber >= 10 && fNumber <= 99 && sNumber >= 10 && sNumber >=10 && sNumber <=99 || fNumber / 10 == sNumber / 10 || fNumber % 10 = sNumber / 10){ 21 | 22 | return true; 23 | 24 | } 25 | 26 | } 27 | return false; 28 | 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /SimpleCalculator.java: -------------------------------------------------------------------------------- 1 | /************************************************************CODING EXERCISE 29: SIMPLE CALCULATOR********************************************* 2 | DESCRIPTION EXERCISE: 3 | 4 | Write a class with the name SimpleCalculator. The class needs two fields (instance variables) with names firstNumber and secondNumber both of type double. 5 | 6 | Write the following methods (instance methods): 7 | 8 | *Method named getFirstNumber without any parameters, it needs to return the value of firstNumber field. 9 | *Method named getSecondNumber without any parameters, it needs to return the value of secondNumber field. 10 | *Method named setFirstNumber with one parameter of type double, it needs to set the value of the firstNumber field. 11 | *Method named setSecondNumber with one parameter of type double, it needs to set the value of the secondNumberfield. 12 | *Method named getAdditionResult without any parameters, it needs to return the result of adding the field values of firstNumber and secondNumber. 13 | *Method named getSubtractionResult without any parameters, it needs to return the result of subtracting the field values of secondNumber from the firstNumber. 14 | *Method named getMultiplicationResult without any parameters, it needs to return the result of multiplying the field values of firstNumber and secondNumber. 15 | *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. 16 | 17 | TEST EXAMPLE 18 | 19 | TEST CODE: 20 | 21 | SimpleCalculator calculator = new SimpleCalculator(); 22 | calculator.setFirstNumber(5.0); 23 | calculator.setSecondNumber(4); 24 | System.out.println("add= " + calculator.getAdditionResult()); 25 | System.out.println("subtract= " + calculator.getSubtractionResult()); 26 | calculator.setFirstNumber(5.25); 27 | calculator.setSecondNumber(0); 28 | System.out.println("multiply= " + calculator.getMultiplicationResult()); 29 | System.out.println("divide= " + calculator.getDivisionResult()); 30 | 31 | OUTPUT 32 | 33 | add= 9.0 34 | subtract= 1.0 35 | multiply= 0.0 36 | divide= 0.0 37 | 38 | TIPS: 39 | 40 | *add= 9.0 is printed because 5.0 + 4 is 9.0 41 | *subtract= 1.0 is printed because 5.0 - 4 is 1.0 42 | *multiply= 0.0 is printed because 5.25 * 0 is 0.0 43 | *divide= 0.0 is printed because secondNumber is set to 0 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. 51 | *************************************************************************CODE****************************************************************/ 52 | public class SimpleCalculator { 53 | // write your code here 54 | private double firstNumber; 55 | private double secondNumber; 56 | 57 | public double getFirstNumber(){ 58 | return firstNumber; 59 | } 60 | 61 | public double getSecondNumber(){ 62 | return secondNumber; 63 | } 64 | 65 | public void setFirstNumber(double firstNumber){ 66 | this.firstNumber = firstNumber; 67 | } 68 | 69 | public void setSecondNumber(double secondNumber){ 70 | this.secondNumber = secondNumber; 71 | } 72 | 73 | public double getAdditionResult(){ 74 | return firstNumber + secondNumber; 75 | } 76 | 77 | public double getSubtractionResult(){ 78 | return firstNumber - secondNumber; 79 | } 80 | 81 | public double getMultiplicationResult(){ 82 | return firstNumber * secondNumber; 83 | } 84 | 85 | public double getDivisionResult () { 86 | 87 | if (secondNumber == 0) { 88 | 89 | return this.secondNumber = 0; 90 | 91 | } else { 92 | 93 | return firstNumber / secondNumber; 94 | 95 | } 96 | 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /SpeedConverter.java: -------------------------------------------------------------------------------- 1 | /****************************************************CODE EXERCISE 1: SPEED CONVERTER ***************************************************************** 2 | Description Exercise: 3 | First method: Write a method called toMilesPerHur that has 1 parameter of type double with the name kiloMetersPerHour. 4 | This method needs to return value of the calculation type long. 5 | If the parameter of the killometerPerHour is less than 0, the method toMilesPerHours needs to return -1 to indicatean invalid value. 6 | Otherwise, ifbit is positive, calculate the value of miles per hour, round it and return it. 7 | Second method: Write another method called printConversion with 1 parameter of type double with the name kilometersPerHour. 8 | This method should not return anything(void) and it needs to calculate milesPerHour from the killometersPerHour parameter. Then it 9 | needs to print a message in the format "XX km/h = YY mi/h". 10 | XX represents the original value kilometersPerHour 11 | YY represents the rounded milesPerHour from the kilometersPerHour parameter. 12 | If the parameter kilometersPerHour is < 0 then the text "Invalid Value". 13 | Use method Math.round to round the number of calculated miles per hour (double). The method should return long. 14 | NO ADDED MAIN METHOD IN THIS CODE. 15 | All methods should be defined as public static 16 | 1 mile per hous is 1.609 kilometers per hour 17 | 18 | /*****************************************************CODE********************************************************************************************* 19 | 20 | public class SpeedConverter { 21 | 22 | public static long toMilesPerHour (double kilometersPerHour) { 23 | 24 | if (kilometersPerHour < 0) { 25 | return -1; 26 | } 27 | return Math.round(kilometersPerHou / 1.609); 28 | } 29 | 30 | public static void printConversion (double kilometersPerHour) { 31 | 32 | if (kilometersPerHour < 0) { 33 | System.out.println("Invalid Value"); 34 | } 35 | else { 36 | long milesPerHour = toMilesPerHour(kilometersPerHour); 37 | System.out.println(kilometersPerHour + " km/h = " + milesPerHour + " mi/h"); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /SumOddRange.java: -------------------------------------------------------------------------------- 1 | /*********************************************************CODING EXERCISE 14: SUM ODD****************************************************************************** 2 | DESCRIPTION EXERCISE: 3 | Method1: 4 | - Write a method called isOdd with an int parameter and call it number. The method needs to return a boolean. 5 | 6 | - Check that number is > 0, if it is not return false. 7 | 8 | - If number is odd return true, otherwise return false. 9 | 10 | Method2: 11 | 12 | - Write a second method called sumOdd that has 2 int parameters start and end, which represent a range of numbers. 13 | 14 | - The method should use a for loop to sum all odd numbers in that range including the end and return the sum. 15 | 16 | - It should call the method isOdd to check if each number is odd. 17 | 18 | - The parameter end needs to be greater than or equal to start and both start and end parameters have to be greater than 0. 19 | 20 | - If those conditions are not satisfied return -1 from the method to indicate invalid input. 21 | 22 | TIP: use the remainder operator to check if the number is odd 23 | 24 | NOTE: Both methods needs to be defined as public static like we have been doing so far in the course. 25 | NOTE: Do not add a main method to solution code. 26 | 27 | 28 | ************************************************************************CODE***************************************************************************************/ 29 | 30 | public class SumOddRange { 31 | // Write the code here 32 | 33 | public static boolean isOdd(int number) { 34 | if (number > 0 && number % 2 != 0) { 35 | return true; 36 | } 37 | return false; 38 | } 39 | 40 | public static int sumOdd(int start, int end) { 41 | if (start < 0 || start > end || end < 0 || end < start) { 42 | return -1; 43 | 44 | } 45 | int sum = 0; 46 | for (int n = start; n <= end; n++) { 47 | if (isOdd(n)) { 48 | sum += n; 49 | } 50 | } 51 | return sum; 52 | 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /TeenNumberChecker.java: -------------------------------------------------------------------------------- 1 | /*********************************************************CODE EXERCISE 7: TEEN NUMBER CHECKER********************************************************* 2 | Description Exercise: 3 | - We'll say that a number is "teen" if it is in the range 13 - 19 (inclusive). 4 | Method1: - Write a method named hasTeen with 3 parameters of type int. 5 | - The method should return boolean and it needs to return true if one of the parameters is in range 13(inclusive) - 19(inclusive). 6 | - Otherwise, return false. 7 | Method2: - Write another method isTeen with 1 parameterof type int. 8 | - The method should return boolean and it needs to return true if the parameter is in the range 13(inclusive) - 19(inclusive) 9 | - Otherwise, return false. 10 | NOTES: 11 | - All methods need to be defined as a public static. 12 | - This code solution does not contain main method. 13 | **************************************************************************CODE************************************************************************/ 14 | 15 | public class TeenNumberChecker { 16 | 17 | public static boolean hasTeen(int firstNumber, int secondNumber, int thirdNumber) { 18 | 19 | if((firstNumber >= 13 && firstNumber <= 19) || (secondNumber >= 13 && secondNumber <= 19) || (thirdNumber >= 13 && thirdNumber <= 19)) { 20 | 21 | return true; 22 | 23 | } 24 | else { 25 | 26 | return false; 27 | 28 | } 29 | } 30 | 31 | public static boolean hasTeen(int number) { 32 | 33 | if (number >= 13 && number <= 19) { 34 | 35 | return true; 36 | 37 | } 38 | else { 39 | 40 | return false; 41 | 42 | } 43 | 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /Wall/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String [] args) { 4 | 5 | System.out.println("area = " wall.getArea()); 6 | 7 | Wall wall = new Wall(5,4); 8 | 9 | wall.setHeight(-1.5); 10 | System.out.println("width = " + wall.getWidth()); 11 | System.out.println("height = " + wall.getHeight()); 12 | System.out.println("area = " + wall.getArea()); 13 | 14 | } // main method 15 | 16 | }// main class 17 | -------------------------------------------------------------------------------- /Wall/Wall.java: -------------------------------------------------------------------------------- 1 | /*********************************************************************CODING EXERCISE 31: WALL AREA********************************************************************* 2 | DESCRIPTION EXERCISE: 3 | - Write a class with name Wall.The class needs to have two fields(instance variable) with name width and height of type double 4 | - The class needs to have two constructors. 5 | * The first constructor does not have any parameters(no-arg constructor). 6 | * The second constructor has parameters width and height of type double and it needs to initialize the fields. 7 | * In case the width is less than 0, it needs to set the width field value to 0. 8 | * In case the height parameter is less than 0, it needs to set the height field value to 0. 9 | - Write the following methods(instance methods) 10 | * Method named getWidth without any parameters, it needs to return the value of width field. 11 | * Method named getHeight without any parameters, it needs to return the value of height field. 12 | * 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 13 | width field value to 0. 14 | * 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 the the 15 | height field value to 0. 16 | * Method named getArea without any parameters, it needs to return the area of the wall. 17 | NOTE: 18 | - All methods should be defined as public NOT public static 19 | - In total, you've to write 5 methods and 2 constructors. 20 | ********************************************************************************CODE***********************************************************************************/ 21 | public class Wall { 22 | // write your code here 23 | private double width; 24 | private double height; 25 | //constructors 26 | public Wall() {} 27 | 28 | public Wall(double width, double height) { 29 | setWidth(width); 30 | setHeight(height); 31 | } 32 | 33 | // instance methods 34 | 35 | public double getWidth() { 36 | return width; 37 | } 38 | 39 | public void setWidth(double width) { 40 | if(width < 0){ 41 | this.width = 0; 42 | }else { 43 | this.width = width; 44 | } 45 | } 46 | 47 | public double getHeight() { 48 | return height; 49 | } 50 | 51 | public void setHeight(double height) { 52 | if (height < 0) { 53 | this.height = 0; 54 | }else { 55 | this.height = height; 56 | } 57 | } 58 | 59 | public double getArea(){ 60 | return this.getWidth() * this.getHeight(); 61 | } 62 | }// end of Wall class 63 | --------------------------------------------------------------------------------