├── Java-Advanced-Lectures.iml ├── README.md ├── exam-preparation ├── unit-testing │ ├── .idea │ │ ├── .gitignore │ │ ├── compiler.xml │ │ ├── jarRepositories.xml │ │ └── misc.xml │ ├── pom.xml │ ├── src │ │ ├── main │ │ │ └── java │ │ │ │ └── petStore │ │ │ │ ├── Animal.java │ │ │ │ ├── Main.java │ │ │ │ └── PetStore.java │ │ └── test │ │ │ └── java │ │ │ └── petStore │ │ │ └── PetStoreTests.java │ └── target │ │ ├── classes │ │ └── petStore │ │ │ ├── Animal.class │ │ │ ├── Main.class │ │ │ └── PetStore.class │ │ └── test-classes │ │ └── petStore │ │ └── PetStoreTests.class └── zoo │ ├── .idea │ ├── .gitignore │ ├── compiler.xml │ ├── jarRepositories.xml │ └── misc.xml │ ├── pom.xml │ ├── src │ └── main │ │ └── java │ │ └── zoo │ │ ├── Main.java │ │ ├── common │ │ ├── Command.java │ │ ├── ConstantMessages.java │ │ └── ExceptionMessages.java │ │ ├── core │ │ ├── Controller.java │ │ ├── ControllerImpl.java │ │ ├── Engine.java │ │ └── EngineImpl.java │ │ ├── entities │ │ ├── animals │ │ │ ├── Animal.java │ │ │ ├── AquaticAnimal.java │ │ │ ├── BaseAnimal.java │ │ │ └── TerrestrialAnimal.java │ │ ├── areas │ │ │ ├── Area.java │ │ │ ├── BaseArea.java │ │ │ ├── LandArea.java │ │ │ └── WaterArea.java │ │ └── foods │ │ │ ├── BaseFood.java │ │ │ ├── Food.java │ │ │ ├── Meat.java │ │ │ └── Vegetable.java │ │ └── repositories │ │ ├── FoodRepository.java │ │ └── FoodRepositoryImpl.java │ └── target │ └── classes │ └── zoo │ ├── Main.class │ ├── common │ ├── Command.class │ ├── ConstantMessages.class │ └── ExceptionMessages.class │ ├── core │ ├── Controller.class │ ├── ControllerImpl.class │ ├── Engine.class │ ├── EngineImpl$1.class │ └── EngineImpl.class │ ├── entities │ ├── animals │ │ ├── Animal.class │ │ ├── AquaticAnimal.class │ │ ├── BaseAnimal.class │ │ └── TerrestrialAnimal.class │ ├── areas │ │ ├── Area.class │ │ ├── BaseArea.class │ │ ├── LandArea.class │ │ └── WaterArea.class │ └── foods │ │ ├── BaseFood.class │ │ ├── Food.class │ │ ├── Meat.class │ │ └── Vegetable.class │ └── repositories │ ├── FoodRepository.class │ └── FoodRepositoryImpl.class ├── src ├── .idea │ ├── .gitignore │ ├── misc.xml │ ├── modules.xml │ └── vcs.xml ├── Main.java ├── advanced │ ├── algorithms │ │ ├── ArraySum.java │ │ ├── Fibonacci.java │ │ ├── MergeSort.java │ │ ├── PowerOfNumber.java │ │ └── SumOfCoins.java │ ├── dataStructuresWorkshop │ │ ├── Main.java │ │ ├── MyStack.java │ │ └── SmartArray.java │ ├── definingClasses │ │ ├── BankAccount.java │ │ ├── Car.java │ │ └── Main.java │ ├── exampreparation │ │ ├── Cooking.java │ │ ├── MouseAndCheese.java │ │ └── university │ │ │ ├── Main.java │ │ │ ├── Student.java │ │ │ └── University.java │ ├── functionalProgramming │ │ ├── _4_AddVat.java │ │ ├── _5_FilterByAge.java │ │ └── _6_FindEvensOrOdds.java │ ├── generics │ │ ├── ArrayCreator.java │ │ ├── Jar.java │ │ ├── ListUtils.java │ │ ├── Main.java │ │ └── Scale.java │ └── iteratorsAndComparators │ │ ├── Book.java │ │ ├── BookComparator.java │ │ ├── BookComparatorByYear.java │ │ ├── Library.java │ │ └── Main.java └── oop │ ├── InterfacesAndAbstraction.java │ ├── designPatterns │ ├── Address.java │ ├── Car.java │ ├── Cloneable.java │ ├── Database.java │ ├── Main.java │ ├── command │ │ ├── Command.java │ │ ├── DecreaseProductPriceCommand.java │ │ ├── IncreaseProductPriceCommand.java │ │ ├── Main.java │ │ ├── ModifyPrice.java │ │ ├── Product.java │ │ └── UpdateProductName.java │ └── template │ │ ├── Fibonacci.java │ │ └── RecursiveFibonacci.java │ ├── exceptions │ ├── Main.java │ ├── MyCustomException.java │ ├── NumberInRange.java │ ├── NumberRange.java │ └── SQRT.java │ ├── inheratance │ ├── Animal.java │ ├── Cat.java │ ├── Dog.java │ ├── Goat.java │ ├── Main.java │ ├── MyStack.java │ ├── Organism.java │ ├── Puppy.java │ ├── RandomArrayList.java │ ├── Reader.java │ ├── Spider.java │ └── StackOfStrings.java │ ├── interfacesAndAbstraction │ ├── Animal.java │ ├── Audi.java │ ├── Car.java │ ├── CarImpl.java │ ├── Cat.java │ ├── Dog.java │ ├── Kitten.java │ ├── Main.java │ ├── Rentable.java │ ├── Seat.java │ ├── Sellable.java │ ├── borderControl │ │ ├── Citizen.java │ │ ├── Identifiable.java │ │ ├── IdentifiableImpl.java │ │ ├── Main.java │ │ └── Robot.java │ ├── ferrari │ │ ├── Car.java │ │ ├── Ferrari.java │ │ └── Main.java │ └── sayHello │ │ ├── BasePerson.java │ │ ├── Bulgarian.java │ │ ├── Chinese.java │ │ ├── European.java │ │ ├── Main.java │ │ └── Person.java │ ├── reflection │ ├── AnnotationExample.java │ ├── GettersAndSetters.java │ ├── HighQualityCode.java │ ├── MyAnnotation.java │ ├── Reflection.java │ └── ReflectionUtils.java │ ├── solid │ ├── Base64Algorithm.java │ ├── Decrypt.java │ ├── Encryp.java │ ├── Main.java │ ├── PasswordDecoder.java │ ├── PasswordHasher.java │ └── Sha256Algorithm.java │ └── workingWithAbstraction │ ├── DayOfWeek.java │ ├── Discount.java │ ├── Main.java │ ├── PriceCalculator.java │ ├── RhombusOfStars.java │ ├── Season.java │ ├── pointInRectangle │ ├── Main.java │ ├── Point.java │ └── Rectangle.java │ └── studentSystem │ ├── Main.java │ ├── Student.java │ └── StudentSystem.java └── testing-demo ├── .idea ├── .gitignore ├── compiler.xml ├── jarRepositories.xml ├── misc.xml └── uiDesigner.xml ├── pom.xml ├── src ├── main │ └── java │ │ ├── Main.java │ │ └── rpg_lab │ │ ├── Axe.java │ │ ├── Dummy.java │ │ ├── Hero.java │ │ ├── Target.java │ │ └── Weapon.java └── test │ └── java │ └── rpg_lab │ ├── AxeTest.java │ ├── DummyTest.java │ └── HeroTest.java └── target ├── classes ├── Main.class └── rpg_lab │ ├── Axe.class │ ├── Dummy.class │ ├── Hero.class │ ├── Target.class │ └── Weapon.class └── test-classes └── rpg_lab ├── AxeTest.class ├── DummyTest.class ├── HeroTest$1.class ├── HeroTest$FakeWeapon.class └── HeroTest.class /Java-Advanced-Lectures.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Java-Advanced-Lectures 2 | This repo contains Java Advanced tasks from SoftUni's course 3 | -------------------------------------------------------------------------------- /exam-preparation/unit-testing/.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | -------------------------------------------------------------------------------- /exam-preparation/unit-testing/.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /exam-preparation/unit-testing/.idea/jarRepositories.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 9 | 10 | 14 | 15 | 19 | 20 | -------------------------------------------------------------------------------- /exam-preparation/unit-testing/.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /exam-preparation/unit-testing/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | org.example 8 | PetStore 9 | 1.0-SNAPSHOT 10 | 11 | 12 | 13 | junit 14 | junit 15 | 4.13.1 16 | test 17 | 18 | 19 | 20 | 21 | 15 22 | 15 23 | 24 | 25 | -------------------------------------------------------------------------------- /exam-preparation/unit-testing/src/main/java/petStore/Animal.java: -------------------------------------------------------------------------------- 1 | package petStore; 2 | 3 | public class Animal { 4 | private String specie; 5 | private int age; 6 | private int maxKilograms; 7 | private double price; 8 | 9 | public Animal(String specie, int maxKilograms, double price) { 10 | this.setSpecie(specie); 11 | this.setMaxKilograms(maxKilograms); 12 | this.setPrice(price); 13 | } 14 | 15 | public String getSpecie() { 16 | return specie; 17 | } 18 | 19 | private void setSpecie(String specie) { 20 | this.specie = specie; 21 | } 22 | 23 | public int getAge() { 24 | return age; 25 | } 26 | 27 | public void setAge(int age) { 28 | this.age = age; 29 | } 30 | 31 | public double getPrice() { 32 | return price; 33 | } 34 | 35 | private void setPrice(double price) { 36 | this.price = price; 37 | } 38 | 39 | public int getMaxKilograms() { 40 | return maxKilograms; 41 | } 42 | 43 | private void setMaxKilograms(int maxKilograms) { 44 | this.maxKilograms = maxKilograms; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /exam-preparation/unit-testing/src/main/java/petStore/Main.java: -------------------------------------------------------------------------------- 1 | package petStore; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | 6 | } 7 | } -------------------------------------------------------------------------------- /exam-preparation/unit-testing/src/main/java/petStore/PetStore.java: -------------------------------------------------------------------------------- 1 | package petStore; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.List; 6 | import java.util.stream.Collectors; 7 | 8 | public class PetStore { 9 | 10 | private List animals; 11 | 12 | public PetStore() { 13 | this.animals = new ArrayList<>(); 14 | } 15 | 16 | public List getAnimals() { 17 | return Collections.unmodifiableList(this.animals); 18 | } 19 | 20 | public int getCount() { 21 | return this.animals.size(); 22 | } 23 | 24 | public List findAllAnimalsWithMaxKilograms(int kg) { 25 | List animals = this.animals.stream().filter(c -> c.getMaxKilograms() > kg).collect(Collectors.toList()); 26 | 27 | return animals; 28 | } 29 | 30 | public void addAnimal(Animal animal) { 31 | if (animal == null) { 32 | throw new IllegalArgumentException("Animal can't be null"); 33 | } 34 | 35 | this.animals.add(animal); 36 | } 37 | 38 | public Animal getTheMostExpensiveAnimal() { 39 | Animal animal = this 40 | .animals 41 | .stream() 42 | .sorted((c1, c2) -> Double.compare(c2.getPrice(), c1.getPrice())) 43 | .limit(1) 44 | .findFirst() 45 | .orElse(null); 46 | 47 | return animal; 48 | } 49 | 50 | public List findAllAnimalBySpecie(String specie) { 51 | List animals = this.animals.stream().filter(c -> c.getSpecie().equals(specie)).collect(Collectors.toList()); 52 | 53 | return animals; 54 | } 55 | } -------------------------------------------------------------------------------- /exam-preparation/unit-testing/src/test/java/petStore/PetStoreTests.java: -------------------------------------------------------------------------------- 1 | package petStore; 2 | 3 | import org.junit.Before; 4 | import org.junit.Test; 5 | 6 | import java.util.List; 7 | 8 | import static org.junit.Assert.*; 9 | 10 | public class PetStoreTests { 11 | 12 | private static final String SPECIE = "Dog"; 13 | private static final int MAX_WEIGHT = 30; 14 | 15 | private static final double PRICE = 100.00; 16 | 17 | private PetStore petStore; 18 | private Animal animal; 19 | 20 | @Before 21 | public void setUp() { 22 | this.petStore = new PetStore(); 23 | this.animal = new Animal(SPECIE, MAX_WEIGHT, PRICE); 24 | } 25 | 26 | 27 | @Test(expected = UnsupportedOperationException.class) 28 | public void test_GetAnimals_ShouldReturn_UnmodifiableList() { 29 | List animals = petStore.getAnimals(); 30 | animals.remove(1); 31 | } 32 | 33 | @Test 34 | public void test_GetCount_ShouldReturnZero_WhenEmpty_And_One_When_SingleAnimalAdded() { 35 | assertEquals(0, petStore.getCount()); 36 | petStore.addAnimal(animal); 37 | assertEquals(1, petStore.getCount()); 38 | } 39 | 40 | @Test 41 | public void test_FindAllAnimalsWithMaxKilograms_Should_Return_EmptyList_WhenNoSuchAnimals() { 42 | petStore.addAnimal(animal); 43 | List animals = petStore.findAllAnimalsWithMaxKilograms(MAX_WEIGHT + 10); 44 | assertTrue(animals.isEmpty()); 45 | } 46 | 47 | @Test 48 | public void test_FindAllAnimalsWithMaxKilograms_Should_Return_OnlyThoseHeavier() { 49 | petStore.addAnimal(animal); 50 | petStore.addAnimal(new Animal("test", MAX_WEIGHT - 2, PRICE)); 51 | List animals = petStore.findAllAnimalsWithMaxKilograms(MAX_WEIGHT - 1); 52 | assertEquals(1, animals.size()); 53 | assertEquals(animal.getSpecie(), animals.get(0).getSpecie()); 54 | } 55 | 56 | @Test(expected = IllegalArgumentException.class) 57 | public void test_AddAnimal_ShouldThrow_WhenAnimal_Is_Null() { 58 | petStore.addAnimal(null); 59 | } 60 | 61 | @Test 62 | public void test_AddAnimal_ShouldIncreaseCount() { 63 | petStore.addAnimal(animal); 64 | assertEquals(1, petStore.getCount()); 65 | } 66 | 67 | @Test 68 | public void test_GetTheMostExpensiveAnimal_Should_Return_Null_WhenEmpty() { 69 | Animal animal = petStore.getTheMostExpensiveAnimal(); 70 | assertNull(animal); 71 | } 72 | 73 | @Test 74 | public void test_GetTheMostExpensiveAnimal_Should_Return_TheMostExpensiveOne() { 75 | petStore.addAnimal(animal); 76 | petStore.addAnimal(new Animal(SPECIE, MAX_WEIGHT, PRICE - 10)); 77 | Animal actualAnimal = petStore.getTheMostExpensiveAnimal(); 78 | assertEquals(animal.getPrice(), actualAnimal.getPrice(), 0.00); 79 | } 80 | 81 | @Test 82 | public void test_FindAllAnimalBySpecie_ShouldReturn_EmptyList_When_NoAnimals() { 83 | List animals = petStore.findAllAnimalBySpecie(SPECIE); 84 | assertTrue(animals.isEmpty()); 85 | } 86 | 87 | @Test 88 | public void test_FindAllAnimalBySpecie_ShouldReturn_OnlyTheRequired_SPECIE() { 89 | petStore.addAnimal(animal); 90 | petStore.addAnimal(new Animal("Goat", MAX_WEIGHT, PRICE)); 91 | List animals = petStore.findAllAnimalBySpecie(SPECIE); 92 | assertEquals(1, animals.size()); 93 | assertEquals(SPECIE, animals.get(0).getSpecie()); 94 | } 95 | 96 | } 97 | 98 | -------------------------------------------------------------------------------- /exam-preparation/unit-testing/target/classes/petStore/Animal.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mpaunov/Java-Advanced-Lectures/b389a672ed7d38a5266610f7a834ee52a4e70187/exam-preparation/unit-testing/target/classes/petStore/Animal.class -------------------------------------------------------------------------------- /exam-preparation/unit-testing/target/classes/petStore/Main.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mpaunov/Java-Advanced-Lectures/b389a672ed7d38a5266610f7a834ee52a4e70187/exam-preparation/unit-testing/target/classes/petStore/Main.class -------------------------------------------------------------------------------- /exam-preparation/unit-testing/target/classes/petStore/PetStore.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mpaunov/Java-Advanced-Lectures/b389a672ed7d38a5266610f7a834ee52a4e70187/exam-preparation/unit-testing/target/classes/petStore/PetStore.class -------------------------------------------------------------------------------- /exam-preparation/unit-testing/target/test-classes/petStore/PetStoreTests.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mpaunov/Java-Advanced-Lectures/b389a672ed7d38a5266610f7a834ee52a4e70187/exam-preparation/unit-testing/target/test-classes/petStore/PetStoreTests.class -------------------------------------------------------------------------------- /exam-preparation/zoo/.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | -------------------------------------------------------------------------------- /exam-preparation/zoo/.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /exam-preparation/zoo/.idea/jarRepositories.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 9 | 10 | 14 | 15 | 19 | 20 | -------------------------------------------------------------------------------- /exam-preparation/zoo/.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /exam-preparation/zoo/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | org.example 8 | ZooApp 9 | 1.0-SNAPSHOT 10 | 11 | 12 | 15 13 | 15 14 | 15 | 16 | -------------------------------------------------------------------------------- /exam-preparation/zoo/src/main/java/zoo/Main.java: -------------------------------------------------------------------------------- 1 | package zoo; 2 | 3 | import zoo.core.Engine; 4 | import zoo.core.EngineImpl; 5 | 6 | public class Main { 7 | 8 | public static void main(String[] args) { 9 | Engine engine = new EngineImpl(); 10 | engine.run(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /exam-preparation/zoo/src/main/java/zoo/common/Command.java: -------------------------------------------------------------------------------- 1 | package zoo.common; 2 | public enum Command { 3 | AddArea, 4 | BuyFood, 5 | FoodForArea, 6 | AddAnimal, 7 | FeedAnimal, 8 | CalculateKg, 9 | GetStatistics, 10 | Exit 11 | } 12 | 13 | -------------------------------------------------------------------------------- /exam-preparation/zoo/src/main/java/zoo/common/ConstantMessages.java: -------------------------------------------------------------------------------- 1 | package zoo.common; 2 | 3 | public class ConstantMessages { 4 | public static final String AREA_NOT_SUITABLE = "The external living environment is not suitable."; 5 | public static final String SUCCESSFULLY_ADDED_ANIMAL_IN_AREA = "Successfully added %s to %s."; 6 | public static final String SUCCESSFULLY_ADDED_FOOD_IN_AREA = "Successfully added %s to %s."; 7 | public static final String ANIMALS_FED = "Animals fed: %d"; 8 | public static final String SUCCESSFULLY_ADDED_AREA_TYPE = "Successfully added %s."; 9 | public static final String SUCCESSFULLY_ADDED_FOOD_TYPE = "Successfully added %s."; 10 | public static final String KILOGRAMS_AREA = "The kilograms of Area %s is %.2f."; 11 | } -------------------------------------------------------------------------------- /exam-preparation/zoo/src/main/java/zoo/common/ExceptionMessages.java: -------------------------------------------------------------------------------- 1 | package zoo.common; 2 | 3 | public class ExceptionMessages { 4 | public static final String NOT_ENOUGH_CAPACITY = "Not enough capacity."; 5 | public static final String ANIMAL_NAME_NULL_OR_EMPTY = "Animal name cannot be null or empty."; 6 | public static final String ANIMAL_KIND_NULL_OR_EMPTY = "Animal kind cannot be null or empty."; 7 | public static final String ANIMAL_PRICE_BELOW_OR_EQUAL_ZERO = "Animal price cannot be below or equal to 0."; 8 | public static final String AREA_NAME_NULL_OR_EMPTY = "Area name cannot be null or empty."; 9 | public static final String INVALID_AREA_TYPE = "Invalid area type."; 10 | public static final String INVALID_FOOD_TYPE = "Invalid food type."; 11 | public static final String INVALID_ANIMAL_TYPE = "Invalid animal type."; 12 | public static final String NO_FOOD_FOUND = "There isn't a food of type %s."; 13 | } 14 | 15 | -------------------------------------------------------------------------------- /exam-preparation/zoo/src/main/java/zoo/core/Controller.java: -------------------------------------------------------------------------------- 1 | package zoo.core; 2 | 3 | public interface Controller { 4 | String addArea(String areaType, String areaName); 5 | String buyFood(String foodType); 6 | String foodForArea(String areaName, String foodType); 7 | String addAnimal(String areaName, String animalType, String animalName, String kind, double price); 8 | String feedAnimal(String areaName); 9 | String calculateKg(String areaName); 10 | String getStatistics(); 11 | } 12 | -------------------------------------------------------------------------------- /exam-preparation/zoo/src/main/java/zoo/core/ControllerImpl.java: -------------------------------------------------------------------------------- 1 | package zoo.core; 2 | 3 | import zoo.entities.animals.Animal; 4 | import zoo.entities.animals.AquaticAnimal; 5 | import zoo.entities.animals.TerrestrialAnimal; 6 | import zoo.entities.areas.Area; 7 | import zoo.entities.areas.LandArea; 8 | import zoo.entities.areas.WaterArea; 9 | import zoo.entities.foods.Food; 10 | import zoo.entities.foods.Meat; 11 | import zoo.entities.foods.Vegetable; 12 | import zoo.repositories.FoodRepository; 13 | import zoo.repositories.FoodRepositoryImpl; 14 | 15 | import java.util.*; 16 | import java.util.stream.Collectors; 17 | 18 | import static zoo.common.ConstantMessages.*; 19 | import static zoo.common.ExceptionMessages.*; 20 | 21 | public class ControllerImpl implements Controller { 22 | 23 | private FoodRepository foodRepository; 24 | private Map areas; 25 | 26 | public ControllerImpl() { 27 | this.foodRepository = new FoodRepositoryImpl(); 28 | this.areas = new LinkedHashMap<>(); 29 | } 30 | 31 | @Override 32 | public String addArea(String areaType, String areaName) { 33 | Area area; 34 | 35 | if (areaType.equals("WaterArea")) { 36 | area = new WaterArea(areaName); 37 | } else if (areaType.equals("LandArea")) { 38 | area = new LandArea(areaName); 39 | } else { 40 | throw new NullPointerException(INVALID_AREA_TYPE); 41 | } 42 | 43 | areas.put(areaName, area); 44 | 45 | return String.format(SUCCESSFULLY_ADDED_AREA_TYPE, areaType); 46 | } 47 | 48 | @Override 49 | public String buyFood(String foodType) { 50 | Food food; 51 | 52 | if (foodType.equals("Vegetable")) { 53 | food = new Vegetable(); 54 | } else if (foodType.equals("Meat")) { 55 | food = new Meat(); 56 | } else { 57 | throw new IllegalArgumentException(INVALID_FOOD_TYPE); 58 | } 59 | 60 | foodRepository.add(food); 61 | 62 | return String.format(SUCCESSFULLY_ADDED_FOOD_TYPE, foodType); 63 | } 64 | 65 | @Override 66 | public String foodForArea(String areaName, String foodType) { 67 | Food food = foodRepository.findByType(foodType); 68 | 69 | if (food == null) { 70 | throw new IllegalArgumentException(String.format(NO_FOOD_FOUND, foodType)); 71 | } 72 | 73 | Area area = areas.get(areaName); 74 | area.addFood(food); 75 | 76 | foodRepository.remove(food); 77 | 78 | return String.format(SUCCESSFULLY_ADDED_FOOD_IN_AREA, foodType, areaName); 79 | } 80 | 81 | @Override 82 | public String addAnimal(String areaName, String animalType, String animalName, String kind, double price) { 83 | Animal animal; 84 | 85 | if (animalType.equals("TerrestrialAnimal")) { 86 | animal = new TerrestrialAnimal(animalName, kind, price); 87 | } else if (animalType.equals("AquaticAnimal")) { 88 | animal = new AquaticAnimal(animalName, kind, price); 89 | } else { 90 | throw new IllegalArgumentException(INVALID_ANIMAL_TYPE); 91 | } 92 | 93 | Area area = areas.get(areaName); 94 | 95 | String areaType = area.getClass().getSimpleName(); 96 | 97 | boolean areaAndAnimalAreLandBased = areaType.equals("LandArea") && animalType.equals("TerrestrialAnimal"); 98 | boolean areaAndAnimalAreWaterBased = areaType.equals("WaterArea") && animalType.equals("AquaticAnimal"); 99 | 100 | if (areaAndAnimalAreLandBased || areaAndAnimalAreWaterBased) { 101 | area.addAnimal(animal); 102 | } else { 103 | return AREA_NOT_SUITABLE; 104 | } 105 | 106 | return String.format(SUCCESSFULLY_ADDED_ANIMAL_IN_AREA, animalType, areaName); 107 | } 108 | 109 | @Override 110 | public String feedAnimal(String areaName) { 111 | 112 | Area area = areas.get(areaName); 113 | 114 | area.feed(); 115 | 116 | return String.format(ANIMALS_FED, area.getAnimals().size()); 117 | } 118 | 119 | @Override 120 | public String calculateKg(String areaName) { 121 | 122 | Collection animals = areas.get(areaName).getAnimals(); 123 | 124 | double kgs = animals.stream() 125 | .mapToDouble(Animal::getKg) 126 | .sum(); 127 | 128 | return String.format(KILOGRAMS_AREA, areaName, kgs); 129 | } 130 | 131 | @Override 132 | public String getStatistics() { 133 | return areas.values().stream() 134 | .map(Area::getInfo) 135 | .collect(Collectors.joining(System.lineSeparator())); 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /exam-preparation/zoo/src/main/java/zoo/core/Engine.java: -------------------------------------------------------------------------------- 1 | package zoo.core; 2 | 3 | public interface Engine extends Runnable { 4 | } 5 | -------------------------------------------------------------------------------- /exam-preparation/zoo/src/main/java/zoo/core/EngineImpl.java: -------------------------------------------------------------------------------- 1 | package zoo.core; 2 | 3 | import zoo.common.Command; 4 | 5 | import java.io.BufferedReader; 6 | import java.io.IOException; 7 | import java.io.InputStreamReader; 8 | import java.util.Arrays; 9 | 10 | public class EngineImpl implements Engine { 11 | private Controller controller; 12 | private BufferedReader reader; 13 | 14 | public EngineImpl() { 15 | this.controller = new ControllerImpl(); 16 | this.reader = new BufferedReader(new InputStreamReader(System.in)); 17 | } 18 | 19 | @Override 20 | public void run() { 21 | while (true) { 22 | String result = null; 23 | try { 24 | result = processInput(); 25 | 26 | if (result.equals("Exit")) { 27 | break; 28 | } 29 | } catch (NullPointerException | IllegalArgumentException | IllegalStateException | IOException e) { 30 | result = e.getMessage(); 31 | } 32 | 33 | System.out.println(result); 34 | } 35 | } 36 | private String processInput() throws IOException { 37 | String input = this.reader.readLine(); 38 | String[] tokens = input.split("\\s+"); 39 | 40 | Command command = Command.valueOf(tokens[0]); 41 | String result = null; 42 | String[] data = Arrays.stream(tokens).skip(1).toArray(String[]::new); 43 | 44 | switch (command) { 45 | case AddArea: 46 | result = addArea(data); 47 | break; 48 | case BuyFood: 49 | result = buyFood(data); 50 | break; 51 | case FoodForArea: 52 | result = foodForArea(data); 53 | break; 54 | case AddAnimal: 55 | result = addAnimal(data); 56 | break; 57 | case FeedAnimal: 58 | result = feedAnimal(data); 59 | break; 60 | case CalculateKg: 61 | result = calculateKg(data); 62 | break; 63 | case GetStatistics: 64 | result = getStatistics(); 65 | break; 66 | case Exit: 67 | result = Command.Exit.name(); 68 | break; 69 | } 70 | return result; 71 | } 72 | private String addArea(String[] data) { 73 | String areaType = data[0]; 74 | String areaName = data[1]; 75 | return controller.addArea(areaType, areaName); 76 | } 77 | 78 | private String buyFood(String[] data) { 79 | String foodType = data[0]; 80 | return controller.buyFood(foodType); 81 | } 82 | 83 | private String foodForArea(String[] data) { 84 | String areaName = data[0]; 85 | String foodType = data[1]; 86 | return controller.foodForArea(areaName, foodType); 87 | } 88 | 89 | private String addAnimal(String[] data) { 90 | String areaName = data[0]; 91 | String animalType = data[1]; 92 | String animalName = data[2]; 93 | String kind = data[3]; 94 | double price = Double.parseDouble(data[4]); 95 | return controller.addAnimal(areaName, animalType, animalName, kind, price); 96 | } 97 | 98 | private String feedAnimal(String[] data) { 99 | String areaName = data[0]; 100 | return controller.feedAnimal(areaName); 101 | } 102 | 103 | private String calculateKg(String[] data) { 104 | String areaName = data[0]; 105 | return controller.calculateKg(areaName); 106 | } 107 | 108 | private String getStatistics() { 109 | return controller.getStatistics(); 110 | } 111 | 112 | } -------------------------------------------------------------------------------- /exam-preparation/zoo/src/main/java/zoo/entities/animals/Animal.java: -------------------------------------------------------------------------------- 1 | package zoo.entities.animals; 2 | 3 | public interface Animal { 4 | String getName(); 5 | 6 | double getKg(); 7 | 8 | double getPrice(); 9 | 10 | void eat(); 11 | } 12 | -------------------------------------------------------------------------------- /exam-preparation/zoo/src/main/java/zoo/entities/animals/AquaticAnimal.java: -------------------------------------------------------------------------------- 1 | package zoo.entities.animals; 2 | 3 | public class AquaticAnimal extends BaseAnimal { 4 | 5 | private static final double WEIGHT = 2.50; 6 | 7 | public AquaticAnimal(String name, String kind, double price) { 8 | super(name, kind, WEIGHT, price); 9 | } 10 | 11 | @Override 12 | public void eat() { 13 | setKg(getKg() + 7.50); 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /exam-preparation/zoo/src/main/java/zoo/entities/animals/BaseAnimal.java: -------------------------------------------------------------------------------- 1 | package zoo.entities.animals; 2 | 3 | import static zoo.common.ExceptionMessages.*; 4 | 5 | public abstract class BaseAnimal implements Animal { 6 | 7 | private String name; 8 | private String kind; 9 | private double kg; 10 | private double price; 11 | 12 | protected BaseAnimal(String name, String kind, double kg, double price) { 13 | setName(name); 14 | setKind(kind); 15 | this.kg = kg; 16 | setPrice(price); 17 | } 18 | 19 | private void setName(String name) { 20 | stringNullOrEmpty(name, ANIMAL_NAME_NULL_OR_EMPTY); 21 | this.name = name; 22 | } 23 | 24 | private void setKind(String kind) { 25 | stringNullOrEmpty(kind, ANIMAL_KIND_NULL_OR_EMPTY); 26 | this.kind = kind; 27 | } 28 | 29 | private void stringNullOrEmpty(String str, String exceptionMessage) { 30 | if (str == null || str.trim().isEmpty()) { 31 | throw new NullPointerException(exceptionMessage); 32 | } 33 | } 34 | 35 | private void setPrice(double price) { 36 | if (price <= 0) { 37 | throw new IllegalArgumentException(ANIMAL_PRICE_BELOW_OR_EQUAL_ZERO); 38 | } 39 | 40 | this.price = price; 41 | } 42 | 43 | protected void setKg(double kg) { 44 | this.kg = kg; 45 | } 46 | 47 | @Override 48 | public String getName() { 49 | return name; 50 | } 51 | 52 | @Override 53 | public double getKg() { 54 | return kg; 55 | } 56 | 57 | @Override 58 | public double getPrice() { 59 | return price; 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /exam-preparation/zoo/src/main/java/zoo/entities/animals/TerrestrialAnimal.java: -------------------------------------------------------------------------------- 1 | package zoo.entities.animals; 2 | 3 | public class TerrestrialAnimal extends BaseAnimal { 4 | 5 | private static final double WEIGHT = 5.50; 6 | 7 | public TerrestrialAnimal(String name, String kind, double price) { 8 | super(name, kind, WEIGHT, price); 9 | } 10 | 11 | @Override 12 | public void eat() { 13 | setKg(getKg() + 5.70); 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /exam-preparation/zoo/src/main/java/zoo/entities/areas/Area.java: -------------------------------------------------------------------------------- 1 | package zoo.entities.areas; 2 | 3 | import zoo.entities.animals.Animal; 4 | import zoo.entities.foods.Food; 5 | 6 | import java.util.Collection; 7 | 8 | public interface Area { 9 | String getName(); 10 | 11 | Collection getAnimals(); 12 | 13 | Collection getFoods(); 14 | 15 | int sumCalories(); 16 | 17 | void addAnimal(Animal animal); 18 | 19 | void removeAnimal(Animal animal); 20 | 21 | void addFood(Food food); 22 | 23 | void feed(); 24 | 25 | String getInfo(); 26 | } 27 | -------------------------------------------------------------------------------- /exam-preparation/zoo/src/main/java/zoo/entities/areas/BaseArea.java: -------------------------------------------------------------------------------- 1 | package zoo.entities.areas; 2 | 3 | import zoo.entities.animals.Animal; 4 | import zoo.entities.foods.Food; 5 | 6 | import java.util.ArrayList; 7 | import java.util.Collection; 8 | import java.util.stream.Collectors; 9 | 10 | import static zoo.common.ExceptionMessages.AREA_NAME_NULL_OR_EMPTY; 11 | import static zoo.common.ExceptionMessages.NOT_ENOUGH_CAPACITY; 12 | 13 | public abstract class BaseArea implements Area { 14 | 15 | private String name; 16 | private int capacity; 17 | private Collection foods; 18 | private Collection animals; 19 | 20 | protected BaseArea(String name, int capacity) { 21 | setName(name); 22 | this.capacity = capacity; 23 | this.foods = new ArrayList<>(); 24 | this.animals = new ArrayList<>(); 25 | } 26 | 27 | private void setName(String name) { 28 | if (name == null || name.trim().isEmpty()) { 29 | throw new NullPointerException(AREA_NAME_NULL_OR_EMPTY); 30 | } 31 | 32 | this.name = name; 33 | } 34 | 35 | @Override 36 | public String getName() { 37 | return name; 38 | } 39 | 40 | @Override 41 | public Collection getAnimals() { 42 | return animals; 43 | } 44 | 45 | @Override 46 | public Collection getFoods() { 47 | return foods; 48 | } 49 | 50 | @Override 51 | public int sumCalories() { 52 | return foods.stream().mapToInt(Food::getCalories).sum(); 53 | } 54 | 55 | @Override 56 | public void addAnimal(Animal animal) { 57 | if (animals.size() == capacity) { 58 | throw new IllegalStateException(NOT_ENOUGH_CAPACITY); 59 | } 60 | 61 | animals.add(animal); 62 | } 63 | 64 | @Override 65 | public void removeAnimal(Animal animal) { 66 | animals.remove(animal); 67 | } 68 | 69 | @Override 70 | public void addFood(Food food) { 71 | foods.add(food); 72 | } 73 | 74 | @Override 75 | public void feed() { 76 | animals.forEach(Animal::eat); 77 | } 78 | 79 | @Override 80 | public String getInfo() { 81 | 82 | String animalOutput = animals.isEmpty() 83 | ? "none" 84 | : animals.stream().map(Animal::getName).collect(Collectors.joining(" ")); 85 | 86 | return String.format("%s (%s):%n" + 87 | "Animals: %s%n" + 88 | "Foods: %d%n" + 89 | "Calories: %d", name, this.getClass().getSimpleName(), animalOutput, foods.size(), sumCalories()); 90 | } 91 | 92 | } 93 | -------------------------------------------------------------------------------- /exam-preparation/zoo/src/main/java/zoo/entities/areas/LandArea.java: -------------------------------------------------------------------------------- 1 | package zoo.entities.areas; 2 | 3 | public class LandArea extends BaseArea { 4 | 5 | private static final int CAPACITY = 25; 6 | 7 | public LandArea(String name) { 8 | super(name, CAPACITY); 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /exam-preparation/zoo/src/main/java/zoo/entities/areas/WaterArea.java: -------------------------------------------------------------------------------- 1 | package zoo.entities.areas; 2 | 3 | public class WaterArea extends BaseArea { 4 | 5 | private static final int CAPACITY = 10; 6 | 7 | public WaterArea(String name) { 8 | super(name, CAPACITY); 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /exam-preparation/zoo/src/main/java/zoo/entities/foods/BaseFood.java: -------------------------------------------------------------------------------- 1 | package zoo.entities.foods; 2 | 3 | public abstract class BaseFood implements Food { 4 | 5 | private int calories; 6 | private double price; 7 | 8 | protected BaseFood(int calories, double price) { 9 | this.calories = calories; 10 | this.price = price; 11 | } 12 | 13 | @Override 14 | public int getCalories() { 15 | return calories; 16 | } 17 | 18 | @Override 19 | public double getPrice() { 20 | return price; 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /exam-preparation/zoo/src/main/java/zoo/entities/foods/Food.java: -------------------------------------------------------------------------------- 1 | package zoo.entities.foods; 2 | 3 | public interface Food { 4 | int getCalories(); 5 | 6 | double getPrice(); 7 | } 8 | -------------------------------------------------------------------------------- /exam-preparation/zoo/src/main/java/zoo/entities/foods/Meat.java: -------------------------------------------------------------------------------- 1 | package zoo.entities.foods; 2 | 3 | public class Meat extends BaseFood { 4 | 5 | private static final int CALORIES = 70; 6 | private static final double PRICE = 10.00; 7 | 8 | public Meat() { 9 | super(CALORIES, PRICE); 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /exam-preparation/zoo/src/main/java/zoo/entities/foods/Vegetable.java: -------------------------------------------------------------------------------- 1 | package zoo.entities.foods; 2 | 3 | public class Vegetable extends BaseFood { 4 | 5 | private static final int CALORIES = 50; 6 | private static final double PRICE = 5.00; 7 | 8 | 9 | public Vegetable() { 10 | super(CALORIES, PRICE); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /exam-preparation/zoo/src/main/java/zoo/repositories/FoodRepository.java: -------------------------------------------------------------------------------- 1 | package zoo.repositories; 2 | 3 | import zoo.entities.foods.Food; 4 | 5 | public interface FoodRepository { 6 | void add(Food food); 7 | 8 | boolean remove(Food food); 9 | 10 | Food findByType(String type); 11 | } 12 | -------------------------------------------------------------------------------- /exam-preparation/zoo/src/main/java/zoo/repositories/FoodRepositoryImpl.java: -------------------------------------------------------------------------------- 1 | package zoo.repositories; 2 | 3 | import zoo.entities.foods.Food; 4 | 5 | import java.util.ArrayList; 6 | import java.util.Collection; 7 | 8 | public class FoodRepositoryImpl implements FoodRepository { 9 | 10 | private Collection foods; 11 | 12 | public FoodRepositoryImpl() { 13 | this.foods = new ArrayList<>(); 14 | } 15 | 16 | @Override 17 | public void add(Food food) { 18 | foods.add(food); 19 | } 20 | 21 | @Override 22 | public boolean remove(Food food) { 23 | return foods.remove(food); 24 | } 25 | 26 | @Override 27 | public Food findByType(String type) { 28 | return foods.stream() 29 | .filter(f -> f.getClass().getSimpleName().equals(type)) 30 | .findFirst() 31 | .orElse(null); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /exam-preparation/zoo/target/classes/zoo/Main.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mpaunov/Java-Advanced-Lectures/b389a672ed7d38a5266610f7a834ee52a4e70187/exam-preparation/zoo/target/classes/zoo/Main.class -------------------------------------------------------------------------------- /exam-preparation/zoo/target/classes/zoo/common/Command.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mpaunov/Java-Advanced-Lectures/b389a672ed7d38a5266610f7a834ee52a4e70187/exam-preparation/zoo/target/classes/zoo/common/Command.class -------------------------------------------------------------------------------- /exam-preparation/zoo/target/classes/zoo/common/ConstantMessages.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mpaunov/Java-Advanced-Lectures/b389a672ed7d38a5266610f7a834ee52a4e70187/exam-preparation/zoo/target/classes/zoo/common/ConstantMessages.class -------------------------------------------------------------------------------- /exam-preparation/zoo/target/classes/zoo/common/ExceptionMessages.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mpaunov/Java-Advanced-Lectures/b389a672ed7d38a5266610f7a834ee52a4e70187/exam-preparation/zoo/target/classes/zoo/common/ExceptionMessages.class -------------------------------------------------------------------------------- /exam-preparation/zoo/target/classes/zoo/core/Controller.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mpaunov/Java-Advanced-Lectures/b389a672ed7d38a5266610f7a834ee52a4e70187/exam-preparation/zoo/target/classes/zoo/core/Controller.class -------------------------------------------------------------------------------- /exam-preparation/zoo/target/classes/zoo/core/ControllerImpl.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mpaunov/Java-Advanced-Lectures/b389a672ed7d38a5266610f7a834ee52a4e70187/exam-preparation/zoo/target/classes/zoo/core/ControllerImpl.class -------------------------------------------------------------------------------- /exam-preparation/zoo/target/classes/zoo/core/Engine.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mpaunov/Java-Advanced-Lectures/b389a672ed7d38a5266610f7a834ee52a4e70187/exam-preparation/zoo/target/classes/zoo/core/Engine.class -------------------------------------------------------------------------------- /exam-preparation/zoo/target/classes/zoo/core/EngineImpl$1.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mpaunov/Java-Advanced-Lectures/b389a672ed7d38a5266610f7a834ee52a4e70187/exam-preparation/zoo/target/classes/zoo/core/EngineImpl$1.class -------------------------------------------------------------------------------- /exam-preparation/zoo/target/classes/zoo/core/EngineImpl.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mpaunov/Java-Advanced-Lectures/b389a672ed7d38a5266610f7a834ee52a4e70187/exam-preparation/zoo/target/classes/zoo/core/EngineImpl.class -------------------------------------------------------------------------------- /exam-preparation/zoo/target/classes/zoo/entities/animals/Animal.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mpaunov/Java-Advanced-Lectures/b389a672ed7d38a5266610f7a834ee52a4e70187/exam-preparation/zoo/target/classes/zoo/entities/animals/Animal.class -------------------------------------------------------------------------------- /exam-preparation/zoo/target/classes/zoo/entities/animals/AquaticAnimal.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mpaunov/Java-Advanced-Lectures/b389a672ed7d38a5266610f7a834ee52a4e70187/exam-preparation/zoo/target/classes/zoo/entities/animals/AquaticAnimal.class -------------------------------------------------------------------------------- /exam-preparation/zoo/target/classes/zoo/entities/animals/BaseAnimal.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mpaunov/Java-Advanced-Lectures/b389a672ed7d38a5266610f7a834ee52a4e70187/exam-preparation/zoo/target/classes/zoo/entities/animals/BaseAnimal.class -------------------------------------------------------------------------------- /exam-preparation/zoo/target/classes/zoo/entities/animals/TerrestrialAnimal.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mpaunov/Java-Advanced-Lectures/b389a672ed7d38a5266610f7a834ee52a4e70187/exam-preparation/zoo/target/classes/zoo/entities/animals/TerrestrialAnimal.class -------------------------------------------------------------------------------- /exam-preparation/zoo/target/classes/zoo/entities/areas/Area.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mpaunov/Java-Advanced-Lectures/b389a672ed7d38a5266610f7a834ee52a4e70187/exam-preparation/zoo/target/classes/zoo/entities/areas/Area.class -------------------------------------------------------------------------------- /exam-preparation/zoo/target/classes/zoo/entities/areas/BaseArea.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mpaunov/Java-Advanced-Lectures/b389a672ed7d38a5266610f7a834ee52a4e70187/exam-preparation/zoo/target/classes/zoo/entities/areas/BaseArea.class -------------------------------------------------------------------------------- /exam-preparation/zoo/target/classes/zoo/entities/areas/LandArea.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mpaunov/Java-Advanced-Lectures/b389a672ed7d38a5266610f7a834ee52a4e70187/exam-preparation/zoo/target/classes/zoo/entities/areas/LandArea.class -------------------------------------------------------------------------------- /exam-preparation/zoo/target/classes/zoo/entities/areas/WaterArea.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mpaunov/Java-Advanced-Lectures/b389a672ed7d38a5266610f7a834ee52a4e70187/exam-preparation/zoo/target/classes/zoo/entities/areas/WaterArea.class -------------------------------------------------------------------------------- /exam-preparation/zoo/target/classes/zoo/entities/foods/BaseFood.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mpaunov/Java-Advanced-Lectures/b389a672ed7d38a5266610f7a834ee52a4e70187/exam-preparation/zoo/target/classes/zoo/entities/foods/BaseFood.class -------------------------------------------------------------------------------- /exam-preparation/zoo/target/classes/zoo/entities/foods/Food.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mpaunov/Java-Advanced-Lectures/b389a672ed7d38a5266610f7a834ee52a4e70187/exam-preparation/zoo/target/classes/zoo/entities/foods/Food.class -------------------------------------------------------------------------------- /exam-preparation/zoo/target/classes/zoo/entities/foods/Meat.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mpaunov/Java-Advanced-Lectures/b389a672ed7d38a5266610f7a834ee52a4e70187/exam-preparation/zoo/target/classes/zoo/entities/foods/Meat.class -------------------------------------------------------------------------------- /exam-preparation/zoo/target/classes/zoo/entities/foods/Vegetable.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mpaunov/Java-Advanced-Lectures/b389a672ed7d38a5266610f7a834ee52a4e70187/exam-preparation/zoo/target/classes/zoo/entities/foods/Vegetable.class -------------------------------------------------------------------------------- /exam-preparation/zoo/target/classes/zoo/repositories/FoodRepository.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mpaunov/Java-Advanced-Lectures/b389a672ed7d38a5266610f7a834ee52a4e70187/exam-preparation/zoo/target/classes/zoo/repositories/FoodRepository.class -------------------------------------------------------------------------------- /exam-preparation/zoo/target/classes/zoo/repositories/FoodRepositoryImpl.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mpaunov/Java-Advanced-Lectures/b389a672ed7d38a5266610f7a834ee52a4e70187/exam-preparation/zoo/target/classes/zoo/repositories/FoodRepositoryImpl.class -------------------------------------------------------------------------------- /src/.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | -------------------------------------------------------------------------------- /src/.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /src/.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /src/.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /src/Main.java: -------------------------------------------------------------------------------- 1 | import oop.interfacesAndAbstraction.Audi; 2 | import oop.interfacesAndAbstraction.Car; 3 | import oop.interfacesAndAbstraction.Seat; 4 | 5 | import java.io.BufferedReader; 6 | import java.io.InputStreamReader; 7 | 8 | public class Main { 9 | public static void main(String[] args) { 10 | 11 | Car car = new Seat("Leon", "blue", 110, "Spain", 1_000_000.00); 12 | 13 | doSmthWithCar(car); 14 | 15 | doSmthWithCar(new Audi("A3", "Blue", 110, "Germany",1 , 10D)); 16 | 17 | 18 | BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); 19 | 20 | } 21 | 22 | public static void doSmthWithCar(Car car) { 23 | System.out.println(car.toString()); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/advanced/algorithms/ArraySum.java: -------------------------------------------------------------------------------- 1 | package advanced.algorithms; 2 | 3 | import java.util.Arrays; 4 | import java.util.Scanner; 5 | 6 | public class ArraySum { 7 | public static void main(String[] args) { 8 | Scanner scanner = new Scanner(System.in); 9 | 10 | int[] arr = Arrays.stream(scanner.nextLine().split("\\s+")) 11 | .mapToInt(Integer::parseInt) 12 | .toArray(); 13 | 14 | int sum = 0; 15 | 16 | for (int i = 0; i < arr.length; i++) { 17 | sum += arr[i]; 18 | } 19 | 20 | System.out.println(sum); 21 | 22 | System.out.println(sumArr(arr, 0)); 23 | } 24 | 25 | public static int sumArr(int[] arr, int index) { 26 | if (index == arr.length - 1) { 27 | return arr[index]; 28 | } 29 | 30 | int sum = arr[index] + sumArr(arr, index + 1); 31 | return sum; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/advanced/algorithms/Fibonacci.java: -------------------------------------------------------------------------------- 1 | package advanced.algorithms; 2 | 3 | import java.util.Scanner; 4 | 5 | public class Fibonacci { 6 | public static long counter = 0; 7 | 8 | public static long[] dp; 9 | 10 | public static void main(String[] args) { 11 | Scanner scanner = new Scanner(System.in); 12 | 13 | int n = Integer.parseInt(scanner.nextLine()); 14 | 15 | dp = new long[n + 1]; 16 | 17 | long fibonacci = fibonacci(n); 18 | 19 | System.out.println(fibonacci); 20 | 21 | System.out.println(counter); 22 | } 23 | public static long fibonacci(int n) { 24 | counter++; 25 | if (n <= 2) { 26 | return 1; 27 | } 28 | 29 | if (dp[n] != 0) { 30 | return dp[n]; 31 | } 32 | 33 | return dp[n] = fibonacci(n - 1) + fibonacci(n - 2); 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/advanced/algorithms/MergeSort.java: -------------------------------------------------------------------------------- 1 | package advanced.algorithms; 2 | 3 | public class MergeSort { 4 | 5 | // Merge two subarrays L and M into arr 6 | void merge(int arr[], int p, int q, int r) { 7 | 8 | // Create L ← A[p..q] and M ← A[q+1..r] 9 | int n1 = q - p + 1; 10 | int n2 = r - q; 11 | 12 | int L[] = new int[n1]; 13 | int M[] = new int[n2]; 14 | 15 | for (int i = 0; i < n1; i++) 16 | L[i] = arr[p + i]; 17 | for (int j = 0; j < n2; j++) 18 | M[j] = arr[q + 1 + j]; 19 | 20 | // Maintain current index of sub-arrays and main array 21 | int i, j, k; 22 | i = 0; 23 | j = 0; 24 | k = p; 25 | 26 | // Until we reach either end of either L or M, pick larger among 27 | // elements L and M and place them in the correct position at A[p..r] 28 | while (i < n1 && j < n2) { 29 | if (L[i] <= M[j]) { 30 | arr[k] = L[i]; 31 | i++; 32 | } else { 33 | arr[k] = M[j]; 34 | j++; 35 | } 36 | k++; 37 | } 38 | 39 | // When we run out of elements in either L or M, 40 | // pick up the remaining elements and put in A[p..r] 41 | while (i < n1) { 42 | arr[k] = L[i]; 43 | i++; 44 | k++; 45 | } 46 | 47 | while (j < n2) { 48 | arr[k] = M[j]; 49 | j++; 50 | k++; 51 | } 52 | } 53 | 54 | // Divide the array into two subarrays, sort them and merge them 55 | void mergeSort(int arr[], int l, int r) { 56 | if (l < r) { 57 | 58 | // m is the point where the array is divided into two subarrays 59 | int m = (l + r) / 2; 60 | 61 | mergeSort(arr, l, m); 62 | mergeSort(arr, m + 1, r); 63 | 64 | // Merge the sorted subarrays 65 | merge(arr, l, m, r); 66 | } 67 | } 68 | 69 | // Print the array 70 | static void printArray(int arr[]) { 71 | int n = arr.length; 72 | for (int i = 0; i < n; ++i) 73 | System.out.print(arr[i] + " "); 74 | System.out.println(); 75 | } 76 | 77 | // Driver program 78 | public static void main(String args[]) { 79 | int arr[] = { 6, 5, 12, 10, 9, 1 }; 80 | 81 | MergeSort ob = new MergeSort(); 82 | ob.mergeSort(arr, 0, arr.length - 1); 83 | 84 | System.out.println("Sorted array:"); 85 | printArray(arr); 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/advanced/algorithms/PowerOfNumber.java: -------------------------------------------------------------------------------- 1 | package advanced.algorithms; 2 | 3 | public class PowerOfNumber { 4 | public static void main(String[] args) { 5 | 6 | int x = 2; 7 | 8 | int n = 16; 9 | 10 | System.out.println(Math.pow(x, n)); 11 | 12 | int result = x; 13 | 14 | for (int i = n; i > 1; i--) { 15 | result = result * x; 16 | } 17 | 18 | System.out.println(result); 19 | 20 | System.out.println(power(x, n)); 21 | } 22 | 23 | public static int power(int number, int power) { 24 | if (power == 1) { 25 | return number; 26 | } 27 | 28 | int prevPower = power(number, power - 1); 29 | int pow = number * prevPower; 30 | return pow; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/advanced/algorithms/SumOfCoins.java: -------------------------------------------------------------------------------- 1 | package advanced.algorithms; 2 | 3 | import java.util.LinkedHashMap; 4 | import java.util.Map; 5 | import java.util.Scanner; 6 | 7 | public class SumOfCoins { 8 | public static void main(String[] args) { 9 | Scanner in = new Scanner(System.in); 10 | 11 | String[] elements = in.nextLine().substring(7).split(", "); 12 | int[] coins = new int[elements.length]; 13 | 14 | for (int i = 0; i < coins.length; i++) { 15 | coins[i] = Integer.parseInt(elements[i]); 16 | } 17 | 18 | int targetSum = Integer.parseInt(in.nextLine().substring(5)); 19 | 20 | Map usedCoins = chooseCoins(coins, targetSum); 21 | 22 | int sumCollected = usedCoins.entrySet().stream() 23 | .mapToInt(e -> e.getKey() * e.getValue()) 24 | .sum(); 25 | 26 | if (sumCollected != targetSum) { 27 | System.out.println("Error"); 28 | } else { 29 | for (Map.Entry usedCoin : usedCoins.entrySet()) { 30 | System.out.println(usedCoin.getKey() + " -> " + usedCoin.getValue()); 31 | } 32 | } 33 | } 34 | public static Map chooseCoins(int[] coins, int targetSum) { 35 | 36 | Map coinsCount = new LinkedHashMap<>(); 37 | 38 | int index = coins.length - 1; 39 | 40 | while (targetSum > 0 && index >= 0) { 41 | int coin = coins[index]; 42 | 43 | int coinsToTake = targetSum / coin; 44 | 45 | if (coinsToTake != 0) { 46 | coinsCount.put(coin, coinsToTake); 47 | } 48 | 49 | targetSum = targetSum % coin; 50 | index--; 51 | } 52 | 53 | return coinsCount; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/advanced/dataStructuresWorkshop/Main.java: -------------------------------------------------------------------------------- 1 | package advanced.dataStructuresWorkshop; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class Main { 6 | public static void main(String[] args) { 7 | 8 | ArrayList list = new ArrayList<>(); 9 | 10 | SmartArray numbers = new SmartArray<>(); 11 | 12 | SmartArray strings = new SmartArray<>(); 13 | 14 | System.out.println(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/advanced/dataStructuresWorkshop/MyStack.java: -------------------------------------------------------------------------------- 1 | package advanced.dataStructuresWorkshop; 2 | 3 | import java.util.Iterator; 4 | 5 | public class MyStack implements Iterable { 6 | 7 | @Override 8 | public Iterator iterator() { 9 | return new Iterator() { 10 | private Node current = top; 11 | 12 | @Override 13 | public boolean hasNext() { 14 | return current != null; 15 | } 16 | 17 | @Override 18 | public E next() { 19 | E element = current.element; 20 | current = current.prev; 21 | return element; 22 | } 23 | }; 24 | } 25 | 26 | private static class Node { 27 | private T element; 28 | private Node prev; 29 | 30 | public Node(T element, Node prev) { 31 | this.element = element; 32 | this.prev = prev; 33 | } 34 | } 35 | 36 | private Node top; 37 | private int size; 38 | 39 | public MyStack() { 40 | } 41 | 42 | public void push(E element) { 43 | Node newNode = new Node<>(element, this.top); 44 | this.top = newNode; 45 | this.size++; 46 | } 47 | 48 | public E pop() { 49 | ensureNotEmpty(); 50 | E element = this.top.element; 51 | this.top = this.top.prev; 52 | this.size--; 53 | return element; 54 | } 55 | 56 | public E peek() { 57 | ensureNotEmpty(); 58 | return this.top.element; 59 | } 60 | 61 | public int size() { 62 | return this.size; 63 | } 64 | 65 | private void ensureNotEmpty() { 66 | if (this.top == null) { 67 | throw new IllegalStateException("Cannot execute on empty stack."); 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/advanced/dataStructuresWorkshop/SmartArray.java: -------------------------------------------------------------------------------- 1 | package advanced.dataStructuresWorkshop; 2 | 3 | import java.util.Iterator; 4 | 5 | public class SmartArray implements Iterable { 6 | private Object[] data; 7 | private int size; 8 | 9 | public SmartArray() { 10 | this.data = new Object[4]; 11 | this.size = 0; 12 | } 13 | 14 | private class SmartArrayIterator implements Iterator { 15 | private int i = 0; 16 | 17 | @Override 18 | public boolean hasNext() { 19 | return i < size; 20 | } 21 | 22 | @Override 23 | public E next() { 24 | E element = get(i); 25 | i++; 26 | return element; 27 | } 28 | } 29 | 30 | @Override 31 | public Iterator iterator() { 32 | return new SmartArrayIterator(); 33 | } 34 | 35 | public void add(E element) { 36 | if (this.size == this.data.length) { 37 | this.data = grow(); 38 | } 39 | 40 | this.data[size] = element; 41 | this.size++; 42 | } 43 | 44 | @SuppressWarnings("unchecked") 45 | public E get(int index) { 46 | validateIndex(index); 47 | 48 | return (E)this.data[index]; 49 | } 50 | 51 | public int size() { 52 | return this.size; 53 | } 54 | 55 | public E remove(int index) { 56 | validateIndex(index); 57 | this.size--; 58 | E element = get(index); 59 | 60 | if (this.size - index >= 0) { 61 | System.arraycopy(this.data, index + 1, this.data, index, this.size - index); 62 | } 63 | 64 | this.data[this.size] = 0; 65 | 66 | if (this.data.length / 4 >= this.size || this.data.length / 4 == 4) { 67 | this.data = shrink(); 68 | } 69 | 70 | return element; 71 | } 72 | 73 | public boolean contains(int element) { 74 | 75 | for (int i = 0; i < this.size; i++) { 76 | if (this.data[i].equals(element)) { 77 | return true; 78 | } 79 | } 80 | 81 | return false; 82 | } 83 | 84 | public void add(int index, E element) { 85 | validateIndex(index); 86 | 87 | int lastIndex = this.size - 1; 88 | E lastElement = get(lastIndex); 89 | 90 | if (lastIndex - index >= 0) { 91 | System.arraycopy(this.data, index, this.data, index + 1, lastIndex - index); 92 | } 93 | 94 | this.data[index] = element; 95 | 96 | add(lastElement); 97 | } 98 | 99 | private void validateIndex(int index) { 100 | if (index < 0 || index >= this.size) { 101 | throw new IndexOutOfBoundsException("Invalid index " + index); 102 | } 103 | } 104 | 105 | private Object[] grow() { 106 | Object[] newData = new Object[this.data.length * 2]; 107 | 108 | System.arraycopy(this.data, 0, newData, 0, this.data.length); 109 | 110 | return newData; 111 | } 112 | 113 | private Object[] shrink() { 114 | Object[] newData = new Object[this.data.length / 2]; 115 | 116 | System.arraycopy(this.data, 0, newData, 0, this.size); 117 | 118 | return newData; 119 | } 120 | 121 | } 122 | -------------------------------------------------------------------------------- /src/advanced/definingClasses/BankAccount.java: -------------------------------------------------------------------------------- 1 | package advanced.definingClasses; 2 | 3 | public class BankAccount { 4 | private static double interestRate = 0.02; 5 | private static int nextId = 1; 6 | 7 | private int id; 8 | private double balance; 9 | 10 | public BankAccount() { 11 | this.id = nextId; 12 | nextId++; 13 | } 14 | 15 | public static void setInterestRate(double interest) { 16 | interestRate = interest; 17 | } 18 | 19 | public double getInterest(int years) { 20 | return interestRate * years * this.balance; 21 | } 22 | 23 | public void deposit(double amount) { 24 | this.balance += amount; 25 | } 26 | 27 | public int getId() { 28 | return id; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/advanced/definingClasses/Car.java: -------------------------------------------------------------------------------- 1 | package advanced.definingClasses; 2 | 3 | import java.util.Objects; 4 | 5 | public class Car { 6 | private String brand; 7 | private String model; 8 | private int horsePower; 9 | 10 | public Car(String brand, String model, int horsePower) { 11 | this.brand = brand; 12 | this.model = model; 13 | this.horsePower = horsePower; 14 | } 15 | 16 | public Car(String brand) { 17 | this(brand, "unknown", -1); 18 | } 19 | 20 | public String getBrand() { 21 | return brand; 22 | } 23 | 24 | public void setBrand(String brand) { 25 | this.brand = brand; 26 | } 27 | 28 | public String getModel() { 29 | return model; 30 | } 31 | 32 | public void setModel(String model) { 33 | this.model = model; 34 | } 35 | 36 | public int getHorsePower() { 37 | return horsePower; 38 | } 39 | 40 | public void setHorsePower(int horsePower) { 41 | this.horsePower = horsePower; 42 | } 43 | 44 | public String carInfo() { 45 | return String.format("The car is: %s %s - %d HP.", 46 | getBrand(), 47 | getModel(), 48 | getHorsePower()); 49 | } 50 | 51 | @Override 52 | public String toString() { 53 | return carInfo(); 54 | } 55 | 56 | @Override 57 | public boolean equals(Object o) { 58 | if (this == o) return true; 59 | if (o == null || getClass() != o.getClass()) return false; 60 | Car car = (Car) o; 61 | return horsePower == car.horsePower && Objects.equals(brand, car.brand) && Objects.equals(model, car.model); 62 | } 63 | 64 | @Override 65 | public int hashCode() { 66 | return Objects.hash(brand, model, horsePower); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/advanced/definingClasses/Main.java: -------------------------------------------------------------------------------- 1 | package advanced.definingClasses; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | import java.util.Scanner; 6 | 7 | public class Main { 8 | public static void main(String[] args) { 9 | Scanner scanner = new Scanner(System.in); 10 | 11 | Map map = new HashMap<>(); 12 | 13 | String line = scanner.nextLine(); 14 | 15 | while (!line.equals("End")) { 16 | 17 | String[] tokens = line.split("\\s+"); 18 | 19 | String command = tokens[0]; 20 | 21 | String output = null; 22 | if (command.equals("Create")) { 23 | BankAccount bankAccount = new BankAccount(); 24 | int key = bankAccount.getId(); 25 | map.put(key, bankAccount); 26 | output = "Account ID" + key + " created"; 27 | } else if (command.equals("Deposit")) { 28 | int id = Integer.parseInt(tokens[1]); 29 | int amount = Integer.parseInt(tokens[2]); 30 | BankAccount bankAccount = map.get(id); 31 | if (bankAccount != null) { 32 | bankAccount.deposit(amount); 33 | output = "Deposited " + amount + " to ID" + id; 34 | } else { 35 | output = "Account does not exist"; 36 | } 37 | } else if (command.equals("SetInterest")) { 38 | double interest = Double.parseDouble(tokens[1]); 39 | BankAccount.setInterestRate(interest); 40 | } else { 41 | int id = Integer.parseInt(tokens[1]); 42 | int years = Integer.parseInt(tokens[2]); 43 | BankAccount bankAccount = map.get(id); 44 | if (bankAccount != null) { 45 | output = String.format("%.2f", bankAccount.getInterest(years)); 46 | } else { 47 | output = "Account does not exist"; 48 | } 49 | } 50 | 51 | if (output != null) { 52 | System.out.println(output); 53 | } 54 | 55 | line = scanner.nextLine(); 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/advanced/exampreparation/Cooking.java: -------------------------------------------------------------------------------- 1 | package advanced.exampreparation; 2 | 3 | import java.util.*; 4 | import java.util.stream.Collectors; 5 | 6 | public class Cooking { 7 | public static void main(String[] args) { 8 | Scanner scanner = new Scanner(System.in); 9 | 10 | ArrayDeque liquids = Arrays.stream(scanner.nextLine().split("\\s+")) 11 | .map(Integer::parseInt) 12 | .collect(Collectors.toCollection(ArrayDeque::new)); 13 | 14 | ArrayDeque ingredients = new ArrayDeque<>(); 15 | 16 | Arrays.stream(scanner.nextLine().split("\\s+")) 17 | .map(Integer::parseInt) 18 | .forEach(ingredients::push); 19 | 20 | Map cookedFoods = new TreeMap<>(); 21 | 22 | cookedFoods.put("Bread", 0); 23 | cookedFoods.put("Cake", 0); 24 | cookedFoods.put("Pastry", 0); 25 | cookedFoods.put("Fruit Pie", 0); 26 | 27 | while (!liquids.isEmpty() && !ingredients.isEmpty()) { 28 | int lastIngredient = ingredients.pop(); 29 | int sum = liquids.poll() + lastIngredient; 30 | 31 | String cookedFood; 32 | switch (sum) { 33 | case 25: 34 | cookedFood = "Bread"; 35 | break; 36 | case 50: 37 | cookedFood = "Cake"; 38 | break; 39 | case 75: 40 | cookedFood = "Pastry"; 41 | break; 42 | case 100: 43 | cookedFood = "Fruit Pie"; 44 | break; 45 | default: 46 | cookedFood = null; 47 | break; 48 | } 49 | 50 | if (cookedFood != null) { 51 | int newVal = cookedFoods.get(cookedFood) + 1; 52 | cookedFoods.put(cookedFood, newVal); 53 | } else { 54 | ingredients.push(lastIngredient + 3); 55 | } 56 | } 57 | 58 | boolean allFoodsAreCooked = cookedFoods.entrySet().stream().allMatch(e -> e.getValue() > 0); 59 | 60 | if (allFoodsAreCooked) { 61 | System.out.println("Wohoo! You succeeded in cooking all the food!"); 62 | } else { 63 | System.out.println("Ugh, what a pity! You didn't have enough materials to cook everything."); 64 | } 65 | 66 | String remainingLiquids = liquids.isEmpty() ? "none" : liquids.stream() 67 | .map(String::valueOf) 68 | .collect(Collectors.joining(", ")); 69 | 70 | System.out.println("Liquids left: " + remainingLiquids); 71 | 72 | String remainingIngredients = ingredients.isEmpty() ? "none" : ingredients.stream() 73 | .map(String::valueOf) 74 | .collect(Collectors.joining(", ")); 75 | 76 | System.out.println("Ingredients left: " + remainingIngredients); 77 | 78 | cookedFoods.entrySet() 79 | .forEach(e -> System.out.println(e.getKey() + ": " + e.getValue())); 80 | 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/advanced/exampreparation/MouseAndCheese.java: -------------------------------------------------------------------------------- 1 | package advanced.exampreparation; 2 | 3 | import java.util.Scanner; 4 | 5 | public class MouseAndCheese { 6 | 7 | private static int row = 0; 8 | private static int col = 0; 9 | private static int eatenCheese = 0; 10 | private static boolean mouseIsInField = true; 11 | 12 | public static void main(String[] args) { 13 | Scanner scanner = new Scanner(System.in); 14 | 15 | int size = Integer.parseInt(scanner.nextLine()); 16 | 17 | char[][] field = new char[size][size]; 18 | 19 | for (int i = 0; i < size; i++) { 20 | String line = scanner.nextLine(); 21 | field[i] = line.toCharArray(); 22 | 23 | if (line.contains("M")) { 24 | row = i; 25 | col = line.indexOf("M"); 26 | } 27 | } 28 | 29 | String command = scanner.nextLine(); 30 | 31 | while (!command.equals("end")) { 32 | 33 | 34 | // Move mouse will be called with the correct mutators in each case the mutators are defining the 35 | // movement direction 36 | // UP { -1, 0} 37 | // DOWN { 1, 0} 38 | // LEFT { 0, -1} 39 | // RIGHT { 0, 1} 40 | if (command.equals("up")) { 41 | moveMouse(field, -1, 0); 42 | } else if (command.equals("down")) { 43 | moveMouse(field, 1, 0); 44 | } else if (command.equals("left")) { 45 | moveMouse(field, 0, -1); 46 | } else if (command.equals("right")) { 47 | moveMouse(field, 0, 1); 48 | } 49 | 50 | if (!mouseIsInField) { 51 | break; 52 | } 53 | 54 | command = scanner.nextLine(); 55 | } 56 | 57 | if (!mouseIsInField) { 58 | System.out.println("Where is the mouse?"); 59 | } 60 | 61 | if (eatenCheese >= 5) { 62 | System.out.println("Great job, the mouse is fed " + eatenCheese + " cheeses!"); 63 | } else { 64 | System.out.println("The mouse couldn't eat the cheeses, she needed " + 65 | (5 - eatenCheese) + " cheeses more."); 66 | } 67 | 68 | print2dArray(field); 69 | } 70 | 71 | /** 72 | * 73 | * @param field char[][] the mouse field 74 | * @param rowMutator int mutator that will be added to the current row of the mouse 75 | * @param colMutator int mutator that will be added to the current col of the mouse 76 | */ 77 | private static void moveMouse(char[][] field, int rowMutator, int colMutator) { 78 | int nextRow = row + rowMutator; 79 | int nextCol = col + colMutator; 80 | 81 | boolean isBonusHit = false; 82 | 83 | if (!isInBounds(field, nextRow, nextCol)) { 84 | field[row][col] = '-'; 85 | mouseIsInField = false; 86 | return; 87 | } 88 | 89 | if (field[nextRow][nextCol] == 'c') { 90 | eatenCheese++; 91 | } else if (field[nextRow][nextCol] == 'B') { 92 | isBonusHit = true; 93 | } 94 | 95 | field[row][col] = '-'; 96 | field[nextRow][nextCol] = 'M'; 97 | row = nextRow; 98 | col = nextCol; 99 | 100 | if (isBonusHit) { 101 | // Call this same method with the same mutators again if bonus is hit 102 | moveMouse(field, rowMutator, colMutator); 103 | } 104 | } 105 | 106 | private static boolean isInBounds(char[][] field, int r, int c) { 107 | return r >= 0 && r < field.length && c >= 0 && c < field[r].length; 108 | } 109 | 110 | private static void print2dArray(char[][] field) { 111 | for (char[] arr : field) { 112 | for (char c : arr) { 113 | System.out.print(c); 114 | } 115 | System.out.println(); 116 | } 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /src/advanced/exampreparation/university/Main.java: -------------------------------------------------------------------------------- 1 | package advanced.exampreparation.university; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | // Initialize the repository 6 | University university = new University(10); 7 | // Initialize entities 8 | Student student = new Student("John", "Smith", "Astronomy"); 9 | Student studentTwo = new Student("Anna", "Cameron", "Geometry"); 10 | Student studentThree = new Student("Samy", "Johnson", "Algebra"); 11 | Student studentFour = new Student("Rihanna", "Fenty", "Music"); 12 | Student studentFive = new Student("Ellie", "Goulding", "Music"); 13 | // Print Student 14 | System.out.println(student); 15 | // Student: John Smith, Astronomy 16 | // Register Student 17 | String register = university.registerStudent(student); 18 | System.out.println(university.getCapacity()); // 10 19 | System.out.println(register); // Added student John Smith 20 | String registerTwo = university.registerStudent(studentTwo); 21 | String registerThree = university.registerStudent(studentThree); 22 | String registerFour = university.registerStudent(studentFour); 23 | // Dismiss Student 24 | String dismissed = university.dismissStudent(student); 25 | System.out.println(dismissed); // Removed student John Smith 26 | String dismissedTwo = university.dismissStudent(studentFive); 27 | System.out.println(dismissedTwo); // Student not found 28 | // Get Student 29 | System.out.println(university.getStudent("Rihanna", "Fenty")); 30 | // Student: Rihanna Fenty, Music 31 | System.out.println(university.getStudentCount()); // 3 32 | System.out.println(university.getStatistics()); 33 | //==Student: First Name = Anna, Last Name = Cameron, Best Subject = Geometry 34 | //==Student: First Name = Samy, Last Name = Johnson, Best Subject = Algebra 35 | //==Student: First Name = Rihanna, Last Name = Fenty, Best Subject = Music 36 | 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/advanced/exampreparation/university/Student.java: -------------------------------------------------------------------------------- 1 | package advanced.exampreparation.university; 2 | 3 | public class Student { 4 | public String firstName; 5 | public String lastName; 6 | public String bestSubject; 7 | 8 | public Student(String firstName, String lastName, String bestSubject) { 9 | this.firstName = firstName; 10 | this.lastName = lastName; 11 | this.bestSubject = bestSubject; 12 | } 13 | 14 | public String getFirstName() { 15 | return firstName; 16 | } 17 | 18 | public String getLastName() { 19 | return lastName; 20 | } 21 | 22 | public String getBestSubject() { 23 | return bestSubject; 24 | } 25 | 26 | @Override 27 | public String toString() { 28 | return "Student: " + firstName + " " + lastName + ", " + bestSubject; 29 | } 30 | 31 | } 32 | 33 | -------------------------------------------------------------------------------- /src/advanced/exampreparation/university/University.java: -------------------------------------------------------------------------------- 1 | package advanced.exampreparation.university; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.stream.Collectors; 6 | 7 | public class University { 8 | public int capacity; 9 | public List students; 10 | 11 | public University(int capacity) { 12 | this.capacity = capacity; 13 | this.students = new ArrayList<>(); 14 | } 15 | 16 | public int getCapacity() { 17 | return capacity; 18 | } 19 | 20 | public List getStudents() { 21 | return students; 22 | } 23 | 24 | public int getStudentCount() { 25 | return students.size(); 26 | } 27 | 28 | public String registerStudent(Student student) { 29 | String result = null; 30 | 31 | if (getStudentCount() >= capacity) { 32 | result = "No seats in the advanced.exampreparation.university"; 33 | } 34 | 35 | if (getStudent(student.firstName, student.lastName) != null) { 36 | result = "Student is already in the advanced.exampreparation.university"; 37 | } 38 | 39 | if (result == null) { 40 | students.add(student); 41 | result = "Added student " + student.getFirstName() + " " + student.getLastName(); 42 | } 43 | 44 | return result; 45 | } 46 | 47 | public String dismissStudent(Student student) { 48 | Student foundStudent = getStudent(student.getFirstName(), student.getLastName()); 49 | 50 | if (foundStudent == null) { 51 | return "Student not found"; 52 | } 53 | 54 | students.remove(student); 55 | 56 | return "Removed student " + foundStudent.getFirstName() + " " + foundStudent.getLastName(); 57 | } 58 | 59 | public Student getStudent(String firstName, String lastName) { 60 | for (Student student : students) { 61 | if (firstName.equals(student.getFirstName()) && lastName.equals(student.getLastName())) { 62 | return student; 63 | } 64 | } 65 | return null; 66 | } 67 | 68 | public String getStatistics() { 69 | return students.stream() 70 | .map(s -> String.format( 71 | "==Student: First Name = %s, Last Name = %s, Best Subject = %s", 72 | s.getFirstName(), s.getLastName(), s.getBestSubject())) 73 | .collect(Collectors.joining(System.lineSeparator())); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/advanced/functionalProgramming/_4_AddVat.java: -------------------------------------------------------------------------------- 1 | package advanced.functionalProgramming; 2 | 3 | import java.util.Arrays; 4 | import java.util.Scanner; 5 | import java.util.function.Consumer; 6 | import java.util.function.UnaryOperator; 7 | 8 | public class _4_AddVat { 9 | public static void main(String[] args) { 10 | Scanner scanner = new Scanner(System.in); 11 | 12 | Consumer printer = d -> System.out.printf("%.2f%n", d); 13 | 14 | UnaryOperator addVat = p -> p * 1.20; 15 | 16 | System.out.println("Prices with VAT:"); 17 | 18 | Arrays.stream(scanner.nextLine().split(", ")) 19 | .map(Double::parseDouble) 20 | .map(addVat) 21 | .forEach(printer); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/advanced/functionalProgramming/_5_FilterByAge.java: -------------------------------------------------------------------------------- 1 | package advanced.functionalProgramming; 2 | 3 | import java.util.List; 4 | import java.util.Scanner; 5 | import java.util.function.Consumer; 6 | import java.util.function.Predicate; 7 | import java.util.stream.Collectors; 8 | import java.util.stream.IntStream; 9 | 10 | public class _5_FilterByAge { 11 | public static class Person { 12 | String name; 13 | int age; 14 | 15 | Person(String name, int age) { 16 | this.name = name; 17 | this.age = age; 18 | } 19 | } 20 | 21 | public static void main(String[] args) { 22 | Scanner scanner = new Scanner(System.in); 23 | 24 | int n = Integer.parseInt(scanner.nextLine()); 25 | 26 | List people = IntStream.range(0, n) 27 | .mapToObj(i -> readPerson(scanner)) 28 | .collect(Collectors.toList()); 29 | 30 | String ageCondition = scanner.nextLine(); 31 | int ageFilter = Integer.parseInt(scanner.nextLine()); 32 | String outputFormat = scanner.nextLine(); 33 | 34 | people = filterByAgeCondition(people, getPredicate(ageCondition, ageFilter)); 35 | 36 | Consumer printer = getPrinter(outputFormat); 37 | 38 | people.forEach(printer); 39 | } 40 | 41 | public static Person readPerson(Scanner scanner) { 42 | String[] data = scanner.nextLine().split(", "); 43 | 44 | String name = data[0]; 45 | int age = Integer.parseInt(data[1]); 46 | 47 | return new Person(name, age); 48 | } 49 | 50 | private static Consumer getPrinter(String outputFormat) { 51 | switch (outputFormat) { 52 | case "name": 53 | return p -> System.out.println(p.name); 54 | case "age": 55 | return p -> System.out.println(p.age); 56 | case "name age": 57 | return p -> System.out.println(p.name + " - " + p.age); 58 | default: 59 | throw new IllegalArgumentException("Unknown format " + outputFormat); 60 | } 61 | } 62 | 63 | private static Predicate getPredicate(String ageCondition, int ageFilter) { 64 | switch (ageCondition) { 65 | case "younger": 66 | return p -> p.age <= ageFilter; 67 | case "older": 68 | return p -> p.age >= ageFilter; 69 | default: 70 | throw new IllegalArgumentException("Invalid parameters for age predicate " + ageCondition + " " + ageFilter); 71 | } 72 | } 73 | 74 | public static List filterByAgeCondition(List people, Predicate predicate) { 75 | return people.stream() 76 | .filter(predicate) 77 | .collect(Collectors.toList()); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/advanced/functionalProgramming/_6_FindEvensOrOdds.java: -------------------------------------------------------------------------------- 1 | package advanced.functionalProgramming; 2 | 3 | import java.util.Arrays; 4 | import java.util.Scanner; 5 | import java.util.function.Predicate; 6 | import java.util.stream.Collectors; 7 | import java.util.stream.IntStream; 8 | 9 | public class _6_FindEvensOrOdds { 10 | public static void main(String[] args) { 11 | Scanner scanner = new Scanner(System.in); 12 | 13 | int[] range = Arrays.stream(scanner.nextLine().split("\\s+")) 14 | .mapToInt(Integer::parseInt) 15 | .toArray(); 16 | 17 | String condition = scanner.nextLine(); 18 | 19 | int low = range[0]; 20 | int up = range[1]; 21 | 22 | System.out.println(IntStream.rangeClosed(low, up) 23 | .boxed() 24 | .filter(getPredicate(condition)) 25 | .map(String::valueOf) 26 | .collect(Collectors.joining(" "))); 27 | } 28 | 29 | public static Predicate getPredicate(String condition) { 30 | if (condition.equals("odd")) { 31 | return n -> n % 2 != 0; 32 | } 33 | return n -> n % 2 == 0; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/advanced/generics/ArrayCreator.java: -------------------------------------------------------------------------------- 1 | package advanced.generics; 2 | 3 | import java.lang.reflect.Array; 4 | import java.util.Arrays; 5 | 6 | public class ArrayCreator { 7 | 8 | @SuppressWarnings("unchecked") 9 | public static T[] create(int length, T defValue) { 10 | T[] arr = (T[])Array.newInstance(defValue.getClass(), length); 11 | 12 | Arrays.fill(arr, defValue); 13 | 14 | return arr; 15 | } 16 | 17 | @SuppressWarnings("unchecked") 18 | public static T[] create(Class clazz, int length, T defValue) { 19 | T[] arr = (T[])Array.newInstance(clazz, length); 20 | 21 | Arrays.fill(arr, defValue); 22 | 23 | return arr; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/advanced/generics/Jar.java: -------------------------------------------------------------------------------- 1 | package advanced.generics; 2 | 3 | import java.util.ArrayDeque; 4 | 5 | public class Jar { 6 | private ArrayDeque elements; 7 | 8 | public Jar() { 9 | this.elements = new ArrayDeque<>(); 10 | } 11 | 12 | public void add(E element) { 13 | elements.push(element); 14 | } 15 | 16 | public E remove() { 17 | return elements.pop(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/advanced/generics/ListUtils.java: -------------------------------------------------------------------------------- 1 | package advanced.generics; 2 | 3 | import java.util.List; 4 | 5 | public class ListUtils { 6 | 7 | public static > T getMin(List elements) { 8 | return elements.stream() 9 | .min(T::compareTo) 10 | .orElseThrow(() -> new IllegalArgumentException("Empty collection")); 11 | } 12 | 13 | public static > T getMax(List elements) { 14 | return elements.stream() 15 | .max(T::compareTo) 16 | .orElseThrow(() -> new IllegalArgumentException("Empty collection")); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/advanced/generics/Main.java: -------------------------------------------------------------------------------- 1 | package advanced.generics; 2 | 3 | import java.util.List; 4 | 5 | public class Main { 6 | public static void main(String[] args) { 7 | 8 | List numbers = List.of(13, 42, 69, 73); 9 | 10 | System.out.println(ListUtils.getMin(numbers)); 11 | System.out.println(ListUtils.getMax(numbers)); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/advanced/generics/Scale.java: -------------------------------------------------------------------------------- 1 | package advanced.generics; 2 | 3 | public class Scale> { 4 | private T left; 5 | private T right; 6 | 7 | public Scale(T left, T right) { 8 | this.left = left; 9 | this.right = right; 10 | } 11 | 12 | public T getHeavier() { 13 | if (left.compareTo(right) > 0) { 14 | return left; 15 | } else if (right.compareTo(left) > 0) { 16 | return right; 17 | } 18 | 19 | return null; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/advanced/iteratorsAndComparators/Book.java: -------------------------------------------------------------------------------- 1 | package advanced.iteratorsAndComparators; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | public class Book implements Comparable { 7 | private String title; 8 | private int year; 9 | private List authors; 10 | 11 | public Book(String title, int year, String... authors) { 12 | setTitle(title); 13 | setYear(year); 14 | setAuthors(authors); 15 | } 16 | 17 | public void setTitle(String title) { 18 | this.title = title; 19 | } 20 | 21 | public void setYear(int year) { 22 | this.year = year; 23 | } 24 | 25 | public void setAuthors(String... authors) { 26 | this.authors = Arrays.asList(authors); 27 | } 28 | 29 | public String getTitle() { 30 | return title; 31 | } 32 | 33 | public int getYear() { 34 | return year; 35 | } 36 | 37 | public List getAuthors() { 38 | return authors; 39 | } 40 | 41 | @Override 42 | public int compareTo(Book other) { 43 | int result = this.title.compareTo(other.title); 44 | 45 | if (result == 0) { 46 | result = Integer.compare(this.year, other.year); 47 | } 48 | 49 | return result; 50 | } 51 | 52 | @Override 53 | public String toString() { 54 | return "Book{" + 55 | "title='" + title + '\'' + 56 | ", year=" + year + 57 | ", authors=" + authors + 58 | '}'; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/advanced/iteratorsAndComparators/BookComparator.java: -------------------------------------------------------------------------------- 1 | package advanced.iteratorsAndComparators; 2 | 3 | import java.util.Comparator; 4 | 5 | public class BookComparator implements Comparator { 6 | 7 | @Override 8 | public int compare(Book f, Book s) { 9 | return f.compareTo(s); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/advanced/iteratorsAndComparators/BookComparatorByYear.java: -------------------------------------------------------------------------------- 1 | package advanced.iteratorsAndComparators; 2 | 3 | import java.util.Comparator; 4 | 5 | public class BookComparatorByYear implements Comparator { 6 | 7 | @Override 8 | public int compare(Book f, Book s) { 9 | return Integer.compare(f.getYear(), s.getYear()); 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /src/advanced/iteratorsAndComparators/Library.java: -------------------------------------------------------------------------------- 1 | package advanced.iteratorsAndComparators; 2 | 3 | import java.util.Arrays; 4 | import java.util.Iterator; 5 | 6 | public class Library implements Iterable { 7 | private Book[] books; 8 | 9 | public Library(Book... books) { 10 | this.books = books; 11 | } 12 | 13 | @Override 14 | public Iterator iterator() { 15 | return Arrays.stream(books).iterator(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/advanced/iteratorsAndComparators/Main.java: -------------------------------------------------------------------------------- 1 | package advanced.iteratorsAndComparators; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Comparator; 5 | import java.util.List; 6 | import java.util.TreeSet; 7 | 8 | public class Main { 9 | public static void main(String[] args) { 10 | Book bookOne = new Book("Animal Farm", 2003, "George Orwell"); 11 | Book bookThree = new Book("The Documents in the Case", 2002); 12 | Book bookTwo = new Book("The Documents in the Case", 1930, "Dorothy Sayers", "Robert Eustace"); 13 | Book bookFour = new Book("Lord of The Rings", 1950, "J. R. R. Tolkein"); 14 | 15 | List books = new ArrayList<>(); 16 | 17 | books.add(bookOne); 18 | books.add(bookTwo); 19 | books.add(bookThree); 20 | books.add(bookFour); 21 | 22 | System.out.println("Unordered books"); 23 | 24 | for (Book b : books) { 25 | System.out.println(b); 26 | } 27 | 28 | System.out.println("Ordered by year with stream"); 29 | 30 | books.stream() 31 | .sorted(Comparator.comparingInt(Book::getYear)) 32 | .forEach(System.out::println); 33 | 34 | System.out.println("Ordered by natural order(Comparable)"); 35 | 36 | books.stream() 37 | .sorted() 38 | .forEach(System.out::println); 39 | 40 | TreeSet setOfBooks = new TreeSet<>(new BookComparatorByYear()); 41 | setOfBooks.add(bookOne); 42 | setOfBooks.add(bookTwo); 43 | setOfBooks.add(bookThree); 44 | setOfBooks.add(bookFour); 45 | 46 | System.out.println("Ordered in TreeSet by year."); 47 | 48 | for (Book b : setOfBooks) { 49 | System.out.println(b); 50 | } 51 | 52 | System.out.println("Ordered by authors count"); 53 | 54 | books.stream() 55 | .sorted(Comparator.comparingInt(b -> b.getAuthors().size())) 56 | .forEach(System.out::println); 57 | 58 | 59 | System.out.println("Ordered by authors count reversed"); 60 | 61 | books.stream() 62 | .sorted((f, s) -> Integer.compare(s.getAuthors().size(), f.getAuthors().size())) 63 | .forEach(System.out::println); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/oop/InterfacesAndAbstraction.java: -------------------------------------------------------------------------------- 1 | package oop; 2 | 3 | public class InterfacesAndAbstraction { 4 | public static void main(String[] args) { 5 | 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/oop/designPatterns/Address.java: -------------------------------------------------------------------------------- 1 | public class Address { 2 | 3 | private String country; 4 | private String city; 5 | private String postCode; 6 | private String street; 7 | private String email; 8 | private String phoneNumber; 9 | private String recipientName; 10 | 11 | public static class Builder { 12 | 13 | private Address address; 14 | 15 | public Builder() { 16 | this.address = new Address(); 17 | } 18 | 19 | public Builder withCountry(String country) { 20 | address.country = country; 21 | return this; 22 | } 23 | 24 | public Builder withCity(String city) { 25 | address.city = city; 26 | return this; 27 | } 28 | 29 | public Builder withPostCode(String postCode) { 30 | address.postCode = postCode; 31 | return this; 32 | } 33 | 34 | public Builder withStreet(String street) { 35 | address.street = street; 36 | return this; 37 | } 38 | 39 | public Builder withEmail(String email) { 40 | address.email = email; 41 | return this; 42 | } 43 | 44 | public Builder withPhoneNumber(String phoneNumber) { 45 | address.phoneNumber = phoneNumber; 46 | return this; 47 | } 48 | 49 | public Builder withRecipientName(String recipientName) { 50 | address.recipientName = recipientName; 51 | return this; 52 | } 53 | 54 | public Address build() { 55 | return address; 56 | } 57 | 58 | } 59 | 60 | public static Builder builder() { 61 | return new Builder(); 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /src/oop/designPatterns/Car.java: -------------------------------------------------------------------------------- 1 | public class Car implements Cloneable { 2 | 3 | private String make; 4 | private String model; 5 | private int year; 6 | private String color; 7 | private int horsePower; 8 | 9 | public Car(String make, String model, int year, String color, int horsePower) { 10 | this.make = make; 11 | this.model = model; 12 | this.year = year; 13 | this.color = color; 14 | this.horsePower = horsePower; 15 | } 16 | 17 | private Car(Car other) { 18 | this.make = other.make; 19 | this.model = other.model; 20 | this.year = other.year; 21 | this.color = other.color; 22 | this.horsePower = other.horsePower; 23 | } 24 | 25 | @Override 26 | public Car clone() { 27 | return new Car(this); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/oop/designPatterns/Cloneable.java: -------------------------------------------------------------------------------- 1 | public interface Cloneable { 2 | 3 | T clone(); 4 | 5 | } 6 | -------------------------------------------------------------------------------- /src/oop/designPatterns/Database.java: -------------------------------------------------------------------------------- 1 | public class Database { 2 | 3 | private static Database instance; 4 | 5 | private Database() { 6 | } 7 | 8 | public static Database getInstance() { 9 | if (instance == null) { 10 | System.out.println("Creating Database..."); 11 | 12 | try { 13 | // Simulate some heavy work 14 | Thread.sleep(100); 15 | } catch (InterruptedException e) { 16 | throw new RuntimeException(e); 17 | } 18 | 19 | instance = new Database(); 20 | } 21 | 22 | return instance; 23 | } 24 | 25 | public void create(T object) { 26 | System.out.println("Saving in database " + object.toString()); 27 | } 28 | 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/oop/designPatterns/Main.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.InputStreamReader; 3 | 4 | public class Main { 5 | public static void main(String[] args) { 6 | 7 | Database database = Database.getInstance(); 8 | 9 | database.create(13); 10 | 11 | Car car = getCar(); 12 | 13 | Car car2 = car.clone(); 14 | 15 | Address address = Address.builder() 16 | .withCity("Sofia") 17 | .withCountry("Bulgaria") 18 | .withPhoneNumber("1234") 19 | .withRecipientName("Martin") 20 | .withPostCode("1234") 21 | .withEmail("me@gmail.com") 22 | .build(); 23 | 24 | } 25 | 26 | private static Car getCar() { 27 | return new Car("Ford", "Mustang", 2023, "Black", 245); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/oop/designPatterns/command/Command.java: -------------------------------------------------------------------------------- 1 | package command; 2 | 3 | public interface Command { 4 | String executeAction(); 5 | } 6 | -------------------------------------------------------------------------------- /src/oop/designPatterns/command/DecreaseProductPriceCommand.java: -------------------------------------------------------------------------------- 1 | package command; 2 | 3 | public class DecreaseProductPriceCommand implements Command { 4 | private final Product product; 5 | private final int amount; 6 | 7 | public DecreaseProductPriceCommand(Product product, int amount) { 8 | this.product = product; 9 | this.amount = amount; 10 | } 11 | 12 | @Override 13 | public String executeAction() { 14 | this.product.decreasePrice(this.amount); 15 | return String.format("The price for the %s has been decreased by %d$.%n", 16 | this.product.getName(), this.amount); 17 | } 18 | } 19 | 20 | -------------------------------------------------------------------------------- /src/oop/designPatterns/command/IncreaseProductPriceCommand.java: -------------------------------------------------------------------------------- 1 | package command; 2 | 3 | public class IncreaseProductPriceCommand implements Command { 4 | private final Product product; 5 | private final int amount; 6 | 7 | public IncreaseProductPriceCommand(Product product, int amount) { 8 | this.product = product; 9 | this.amount = amount; 10 | } 11 | 12 | @Override 13 | public String executeAction() { 14 | this.product.increasePrice(this.amount); 15 | return String.format("The price for the %s has been increased by %d$.%n", 16 | this.product.getName(), this.amount); 17 | } 18 | } 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/oop/designPatterns/command/Main.java: -------------------------------------------------------------------------------- 1 | package command; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | ModifyPrice modifyPrice = new ModifyPrice(); 6 | Product product = new Product("Phone",500); 7 | 8 | execute(new IncreaseProductPriceCommand(product, 100)); 9 | execute(new IncreaseProductPriceCommand(product, 50)); 10 | execute(new DecreaseProductPriceCommand(product, 25)); 11 | execute(new UpdateProductName(product, "Mobile Phone")); 12 | 13 | System.out.println(product); 14 | } 15 | private static void execute(Command productCommand){ 16 | System.out.println(productCommand.executeAction()); 17 | } 18 | } 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/oop/designPatterns/command/ModifyPrice.java: -------------------------------------------------------------------------------- 1 | package command; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class ModifyPrice { 7 | private final List commands; 8 | private Command command; 9 | 10 | public ModifyPrice() { 11 | this.commands = new ArrayList<>(); 12 | } 13 | 14 | public void setCommand(Command command) { 15 | this.command = command; 16 | } 17 | 18 | public void invoke() { 19 | this.commands.add(this.command); 20 | this.command.executeAction(); 21 | } 22 | } 23 | 24 | 25 | -------------------------------------------------------------------------------- /src/oop/designPatterns/command/Product.java: -------------------------------------------------------------------------------- 1 | package command; 2 | 3 | public class Product { 4 | private String name; 5 | private int price; 6 | 7 | public String getName() { 8 | return name; 9 | } 10 | 11 | public void setName(String name) { 12 | this.name = name; 13 | } 14 | 15 | public int getPrice() { 16 | return price; 17 | } 18 | 19 | public void setPrice(int price) { 20 | this.price = price; 21 | } 22 | 23 | public Product(String name, int price) { 24 | this.name = name; 25 | this.price = price; 26 | } 27 | 28 | public void increasePrice(int amount) { 29 | this.setPrice(this.getPrice() + amount); 30 | } 31 | 32 | public void decreasePrice(int amount) { 33 | this.setPrice(this.getPrice() - amount); 34 | } 35 | 36 | @Override 37 | public String toString() { 38 | return String.format("Current price for the %s product is %d$.%n", this.name, this.price); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/oop/designPatterns/command/UpdateProductName.java: -------------------------------------------------------------------------------- 1 | package command; 2 | 3 | public class UpdateProductName implements Command { 4 | 5 | private Product product; 6 | private String newName; 7 | 8 | public UpdateProductName(Product product, String newName) { 9 | this.product = product; 10 | this.newName = newName; 11 | } 12 | 13 | @Override 14 | public String executeAction() { 15 | String oldName = product.getName(); 16 | product.setName(newName); 17 | return "Product name updated from " + oldName + " to " + newName; 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/oop/designPatterns/template/Fibonacci.java: -------------------------------------------------------------------------------- 1 | package template; 2 | 3 | public interface Fibonacci { 4 | 5 | long fibonacci(int n); 6 | 7 | } 8 | -------------------------------------------------------------------------------- /src/oop/designPatterns/template/RecursiveFibonacci.java: -------------------------------------------------------------------------------- 1 | package template; 2 | 3 | public class RecursiveFibonacci implements Fibonacci { 4 | 5 | private long[] memory; 6 | 7 | @Override 8 | public long fibonacci(int n) { 9 | if (n <= 2) { 10 | return 1; 11 | } 12 | 13 | if (memory == null) { 14 | memory = new long[n]; 15 | } 16 | 17 | if (memory[n] != 0) { 18 | return memory[n]; 19 | } 20 | 21 | return memory[n] = fibonacci(n - 1) + fibonacci(n - 2); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/oop/exceptions/Main.java: -------------------------------------------------------------------------------- 1 | package oop.exceptions; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStreamReader; 6 | import java.util.Scanner; 7 | 8 | public class Main { 9 | public static void main(String[] args) { 10 | 11 | 12 | 13 | 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/oop/exceptions/MyCustomException.java: -------------------------------------------------------------------------------- 1 | package oop.exceptions; 2 | 3 | public class MyCustomException extends RuntimeException { 4 | 5 | public MyCustomException(String message, Throwable cause) { 6 | super(message, cause); 7 | } 8 | 9 | } 10 | -------------------------------------------------------------------------------- /src/oop/exceptions/NumberInRange.java: -------------------------------------------------------------------------------- 1 | package oop.exceptions; 2 | 3 | import java.util.Arrays; 4 | import java.util.Optional; 5 | import java.util.Scanner; 6 | 7 | public class NumberInRange { 8 | 9 | public static void main(String[] args) { 10 | Scanner scanner = new Scanner(System.in); 11 | 12 | int[] range = Arrays.stream(scanner.nextLine().split("\\s+")) 13 | .mapToInt(Integer::parseInt) 14 | .toArray(); 15 | 16 | int begin = range[0]; 17 | int end = range[1]; 18 | 19 | System.out.println("Range: [" + begin + "..." + end + "]"); 20 | 21 | String input = scanner.nextLine(); 22 | 23 | boolean isInRange = false; 24 | 25 | while (!isInRange) { 26 | 27 | Optional number; 28 | 29 | try { 30 | number = Optional.of(Integer.parseInt(input)); 31 | } catch (NumberFormatException e) { 32 | throw new RuntimeException(e); 33 | } finally { 34 | System.out.println("I am always executed!"); 35 | } 36 | 37 | if (number.get() < begin || number.get() > end) { 38 | System.out.println("Invalid number: " + input); 39 | input = scanner.nextLine(); 40 | } else { 41 | isInRange = true; 42 | } 43 | } 44 | 45 | System.out.println("Valid number: " + input); 46 | 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /src/oop/exceptions/NumberRange.java: -------------------------------------------------------------------------------- 1 | package oop.exceptions; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.Scanner; 6 | import java.util.stream.Collectors; 7 | 8 | public class NumberRange { 9 | 10 | public static void main(String[] args) { 11 | 12 | Scanner scanner = new Scanner(System.in); 13 | 14 | int start = 1; 15 | 16 | List numbers = new ArrayList<>(); 17 | 18 | while (numbers.size() < 10) { 19 | 20 | int number; 21 | 22 | try { 23 | number = readNumber(start, 100, scanner); 24 | } catch (IllegalStateException e) { 25 | System.out.println(e.getMessage()); 26 | 27 | continue; 28 | } 29 | 30 | start = number; 31 | numbers.add(number); 32 | } 33 | 34 | System.out.println( 35 | numbers.stream() 36 | .map(String::valueOf) 37 | .collect(Collectors.joining(", ")) 38 | ); 39 | } 40 | 41 | public static int readNumber(int start, int end, Scanner scanner) { 42 | 43 | String input = scanner.nextLine(); 44 | 45 | int number; 46 | 47 | try { 48 | number = Integer.parseInt(input); 49 | } catch (NumberFormatException e) { 50 | throw new IllegalStateException("Invalid Number!"); 51 | } 52 | 53 | if (number <= start || number >= end) { 54 | throw new IllegalStateException("Your number is not in range " + start + " - 100!"); 55 | } 56 | 57 | return number; 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /src/oop/exceptions/SQRT.java: -------------------------------------------------------------------------------- 1 | package oop.exceptions; 2 | 3 | import java.util.Scanner; 4 | 5 | public class SQRT { 6 | 7 | public static void main(String[] args) { 8 | String numberAsString = new Scanner(System.in).nextLine(); 9 | 10 | double sqrt = -1; 11 | 12 | try { 13 | sqrt = sqrt(Integer.parseInt(numberAsString)); 14 | } catch (IllegalArgumentException e) { 15 | System.out.println("Invalid"); 16 | } 17 | 18 | if (sqrt != -1) { 19 | System.out.printf("%.2f%n", sqrt); 20 | } 21 | 22 | System.out.println("Goodbye"); 23 | 24 | } 25 | 26 | public static double sqrt(int n) { 27 | if (n < 0) { 28 | throw new IllegalArgumentException("Invalid"); 29 | } 30 | 31 | return Math.sqrt(n); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/oop/inheratance/Animal.java: -------------------------------------------------------------------------------- 1 | package oop.inheratance; 2 | 3 | public class Animal { 4 | public void eat() { 5 | System.out.println("eating..."); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/oop/inheratance/Cat.java: -------------------------------------------------------------------------------- 1 | package oop.inheratance; 2 | 3 | public class Cat extends Animal { 4 | 5 | public void meow() { 6 | System.out.println("meowing..."); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/oop/inheratance/Dog.java: -------------------------------------------------------------------------------- 1 | package oop.inheratance; 2 | 3 | public class Dog extends Animal { 4 | 5 | @Override 6 | public void eat() { 7 | System.out.print("Sharo is "); 8 | super.eat(); 9 | } 10 | 11 | public void bark() { 12 | System.out.println("barking..."); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/oop/inheratance/Goat.java: -------------------------------------------------------------------------------- 1 | package oop.inheratance; 2 | 3 | public class Goat extends Organism { 4 | int milkGiven; 5 | 6 | public Goat() { 7 | super(13, 72); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/oop/inheratance/Main.java: -------------------------------------------------------------------------------- 1 | package oop.inheratance; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Main { 6 | 7 | public static void main(String[] args) { 8 | 9 | Dog dog = new Dog(); 10 | 11 | dog.eat(); 12 | dog.bark(); 13 | 14 | Cat cat = new Cat(); 15 | 16 | cat.eat(); 17 | cat.meow(); 18 | 19 | RandomArrayList list = new RandomArrayList(); 20 | 21 | list.add(13); 22 | list.add(42); 23 | list.add(73); 24 | list.add(69); 25 | list.add(51); 26 | 27 | System.out.println(list.getRandomElement()); 28 | 29 | Reader reader = new Reader(System.in); 30 | 31 | System.out.println(Arrays.toString(reader.readIntArray("\\s+"))); 32 | 33 | MyStack strings = new MyStack(); 34 | 35 | strings.push("my-solution"); 36 | System.out.println(strings.pop()); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/oop/inheratance/MyStack.java: -------------------------------------------------------------------------------- 1 | package oop.inheratance; 2 | 3 | import java.util.ArrayDeque; 4 | 5 | public class MyStack extends ArrayDeque { 6 | } 7 | -------------------------------------------------------------------------------- /src/oop/inheratance/Organism.java: -------------------------------------------------------------------------------- 1 | package oop.inheratance; 2 | 3 | public class Organism { 4 | protected int weight; 5 | protected int height; 6 | public Organism(int weight, int height) { 7 | this.weight = weight; 8 | this.height = height; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/oop/inheratance/Puppy.java: -------------------------------------------------------------------------------- 1 | package oop.inheratance; 2 | 3 | public class Puppy extends Dog { 4 | public void weep() { 5 | System.out.println("weeping..."); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/oop/inheratance/RandomArrayList.java: -------------------------------------------------------------------------------- 1 | package oop.inheratance; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Random; 5 | 6 | public class RandomArrayList extends ArrayList { 7 | 8 | public Object getRandomElement() { 9 | Random random = new Random(); 10 | int index = random.nextInt(super.size()); 11 | return remove(index); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/oop/inheratance/Reader.java: -------------------------------------------------------------------------------- 1 | package oop.inheratance; 2 | 3 | import java.io.InputStream; 4 | import java.util.Arrays; 5 | import java.util.Scanner; 6 | 7 | public class Reader { 8 | Scanner scanner; 9 | 10 | public Reader(InputStream inputStream) { 11 | this.scanner = new Scanner(inputStream); 12 | } 13 | 14 | public int[] readIntArray(String pattern) { 15 | return Arrays.stream(scanner.nextLine().split(pattern)) 16 | .mapToInt(Integer::parseInt) 17 | .toArray(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/oop/inheratance/Spider.java: -------------------------------------------------------------------------------- 1 | package oop.inheratance; 2 | 3 | public class Spider extends Organism { 4 | int fliesEaten; 5 | 6 | public Spider() { 7 | super(42, 67); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/oop/inheratance/StackOfStrings.java: -------------------------------------------------------------------------------- 1 | package oop.inheratance; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class StackOfStrings { 6 | private ArrayList data; 7 | 8 | public StackOfStrings() { 9 | this.data = new ArrayList<>(); 10 | } 11 | 12 | public void push(String e) { 13 | data.add(e); 14 | } 15 | 16 | public String pop() { 17 | return data.remove(data.size() - 1); 18 | } 19 | 20 | public String peek() { 21 | return data.get(data.size() - 1); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/oop/interfacesAndAbstraction/Animal.java: -------------------------------------------------------------------------------- 1 | package oop.interfacesAndAbstraction; 2 | 3 | public interface Animal { 4 | 5 | void eat(); 6 | 7 | } 8 | -------------------------------------------------------------------------------- /src/oop/interfacesAndAbstraction/Audi.java: -------------------------------------------------------------------------------- 1 | package oop.interfacesAndAbstraction; 2 | 3 | public class Audi extends CarImpl implements Rentable { 4 | private Integer minRentDay; 5 | private Double pricePerDay; 6 | 7 | public Audi(String model, String color, Integer horsePower, 8 | String countryProduced, Integer minRentDay, Double pricePerDay) { 9 | super(model, color, horsePower, countryProduced); 10 | this.minRentDay = minRentDay; 11 | this.pricePerDay = pricePerDay; 12 | } 13 | 14 | @Override 15 | public Integer getMinRentDay() { 16 | return minRentDay; 17 | } 18 | 19 | @Override 20 | public Double getPricePerDay() { 21 | return pricePerDay; 22 | } 23 | 24 | @Override 25 | public String toString() { 26 | return String.format("%s%nMinimum rental period of %d days. Price per day %f", 27 | super.toString(), minRentDay, pricePerDay); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/oop/interfacesAndAbstraction/Car.java: -------------------------------------------------------------------------------- 1 | package oop.interfacesAndAbstraction; 2 | 3 | public interface Car { 4 | 5 | String getModel(); 6 | 7 | String getColor(); 8 | 9 | Integer getHorsePower(); 10 | 11 | String countryProduced(); 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/oop/interfacesAndAbstraction/CarImpl.java: -------------------------------------------------------------------------------- 1 | package oop.interfacesAndAbstraction; 2 | 3 | public class CarImpl implements Car { 4 | 5 | private static final int TIRE = 4; 6 | 7 | private String model; 8 | private String color; 9 | private Integer horsePower; 10 | private String countryProduced; 11 | 12 | public CarImpl(String model, String color, Integer horsePower, String countryProduced) { 13 | this.model = model; 14 | this.color = color; 15 | this.horsePower = horsePower; 16 | this.countryProduced = countryProduced; 17 | } 18 | 19 | public String getModel() { 20 | return model; 21 | } 22 | 23 | public String getColor() { 24 | return color; 25 | } 26 | 27 | public Integer getHorsePower() { 28 | return horsePower; 29 | } 30 | 31 | @Override 32 | public String countryProduced() { 33 | return countryProduced; 34 | } 35 | 36 | @Override 37 | public String toString() { 38 | return String.format("This is %s produced in %s and have %d tires", 39 | model, countryProduced, TIRE); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/oop/interfacesAndAbstraction/Cat.java: -------------------------------------------------------------------------------- 1 | package oop.interfacesAndAbstraction; 2 | 3 | public class Cat implements Animal { 4 | 5 | @Override 6 | public void eat() { 7 | System.out.println("The cat doesn't like the food and meows..."); 8 | } 9 | 10 | } 11 | -------------------------------------------------------------------------------- /src/oop/interfacesAndAbstraction/Dog.java: -------------------------------------------------------------------------------- 1 | package oop.interfacesAndAbstraction; 2 | 3 | public class Dog implements Animal { 4 | 5 | @Override 6 | public void eat() { 7 | System.out.println("Dog is eating..."); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/oop/interfacesAndAbstraction/Kitten.java: -------------------------------------------------------------------------------- 1 | package oop.interfacesAndAbstraction; 2 | 3 | public class Kitten extends Cat { 4 | } 5 | -------------------------------------------------------------------------------- /src/oop/interfacesAndAbstraction/Main.java: -------------------------------------------------------------------------------- 1 | package oop.interfacesAndAbstraction; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class Main { 6 | public static void main(String[] args) { 7 | Car seat = new Seat("Leon", "Gray", 110, 8 | "Spain", 11111.1); 9 | Car audi = new Audi("A4", "Gray", 110, 10 | "Germany", 3, 99.9); 11 | 12 | printCarInfo(seat); 13 | printCarInfo(audi); 14 | } 15 | 16 | private static void printCarInfo(Car car) { 17 | System.out.println(String.format( 18 | "%s is %s color and have %s horse power", 19 | car.getModel(), 20 | car.getColor(), 21 | car.getHorsePower())); 22 | System.out.println(car.toString()); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/oop/interfacesAndAbstraction/Rentable.java: -------------------------------------------------------------------------------- 1 | package oop.interfacesAndAbstraction; 2 | 3 | public interface Rentable { 4 | 5 | Integer getMinRentDay(); 6 | Double getPricePerDay(); 7 | 8 | } 9 | -------------------------------------------------------------------------------- /src/oop/interfacesAndAbstraction/Seat.java: -------------------------------------------------------------------------------- 1 | package oop.interfacesAndAbstraction; 2 | 3 | public class Seat extends CarImpl implements Sellable { 4 | private Double price; 5 | 6 | public Seat(String model, String color, Integer horsePower, 7 | String countryProduced, Double price) { 8 | super(model, color, horsePower, countryProduced); 9 | this.price = price; 10 | } 11 | 12 | @Override 13 | public Double getPrice() { 14 | return price; 15 | } 16 | 17 | @Override 18 | public String toString() { 19 | return String.format("%s%n%s sells for %f", super.toString(), getModel(), price); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/oop/interfacesAndAbstraction/Sellable.java: -------------------------------------------------------------------------------- 1 | package oop.interfacesAndAbstraction; 2 | 3 | public interface Sellable { 4 | 5 | Double getPrice(); 6 | 7 | } 8 | -------------------------------------------------------------------------------- /src/oop/interfacesAndAbstraction/borderControl/Citizen.java: -------------------------------------------------------------------------------- 1 | package oop.interfacesAndAbstraction.borderControl; 2 | 3 | public class Citizen extends IdentifiableImpl { 4 | 5 | private int age; 6 | private String name; 7 | 8 | public Citizen(String id, int age, String name) { 9 | super(id); 10 | this.age = age; 11 | this.name = name; 12 | } 13 | 14 | public int getAge() { 15 | return age; 16 | } 17 | 18 | public String getName() { 19 | return name; 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/oop/interfacesAndAbstraction/borderControl/Identifiable.java: -------------------------------------------------------------------------------- 1 | package oop.interfacesAndAbstraction.borderControl; 2 | 3 | public interface Identifiable { 4 | 5 | String getId(); 6 | 7 | } 8 | -------------------------------------------------------------------------------- /src/oop/interfacesAndAbstraction/borderControl/IdentifiableImpl.java: -------------------------------------------------------------------------------- 1 | package oop.interfacesAndAbstraction.borderControl; 2 | 3 | public abstract class IdentifiableImpl implements Identifiable { 4 | 5 | private String id; 6 | 7 | protected IdentifiableImpl(String id) { 8 | this.id = id; 9 | } 10 | 11 | @Override 12 | public String getId() { 13 | return id; 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/oop/interfacesAndAbstraction/borderControl/Main.java: -------------------------------------------------------------------------------- 1 | package oop.interfacesAndAbstraction.borderControl; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.Scanner; 6 | 7 | public class Main { 8 | public static void main(String[] args) { 9 | 10 | Scanner scanner = new Scanner(System.in); 11 | 12 | List identifiables = new ArrayList<>(); 13 | 14 | String input = scanner.nextLine(); 15 | 16 | while (!input.equals("End")) { 17 | 18 | String[] tokens = input.split("\\s+"); 19 | 20 | Identifiable identifiable = tokens.length == 2 21 | ? new Robot(tokens[1], tokens[0]) 22 | : new Citizen(tokens[2], Integer.parseInt(tokens[1]), tokens[1]); 23 | 24 | identifiables.add(identifiable); 25 | 26 | input = scanner.nextLine(); 27 | } 28 | 29 | String fakeIdPostfix = scanner.nextLine(); 30 | 31 | identifiables 32 | .stream() 33 | .map(Identifiable::getId) 34 | .filter(i -> i.endsWith(fakeIdPostfix)) 35 | .forEach(System.out::println); 36 | 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/oop/interfacesAndAbstraction/borderControl/Robot.java: -------------------------------------------------------------------------------- 1 | package oop.interfacesAndAbstraction.borderControl; 2 | 3 | public class Robot extends IdentifiableImpl { 4 | 5 | private String model; 6 | 7 | public Robot(String id, String model) { 8 | super(id); 9 | this.model = model; 10 | } 11 | 12 | public String getModel() { 13 | return model; 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/oop/interfacesAndAbstraction/ferrari/Car.java: -------------------------------------------------------------------------------- 1 | package oop.interfacesAndAbstraction.ferrari; 2 | 3 | public interface Car { 4 | 5 | String brakes(); 6 | String gas(); 7 | 8 | } 9 | -------------------------------------------------------------------------------- /src/oop/interfacesAndAbstraction/ferrari/Ferrari.java: -------------------------------------------------------------------------------- 1 | package oop.interfacesAndAbstraction.ferrari; 2 | 3 | public class Ferrari implements Car { 4 | 5 | private String driverName; 6 | private String model; 7 | 8 | public Ferrari(String driverName) { 9 | this.driverName = driverName; 10 | this.model = "488-Spider"; 11 | } 12 | 13 | @Override 14 | public String brakes() { 15 | return "Brakes!"; 16 | } 17 | 18 | @Override 19 | public String gas() { 20 | return "brum-brum-brum-brrrrr"; 21 | } 22 | 23 | @Override 24 | public String toString() { 25 | return String.format("%s/%s/%s/%s", model, brakes(), gas(), driverName); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/oop/interfacesAndAbstraction/ferrari/Main.java: -------------------------------------------------------------------------------- 1 | package oop.interfacesAndAbstraction.ferrari; 2 | 3 | import java.util.Scanner; 4 | 5 | public class Main { 6 | public static void main(String[] args) { 7 | 8 | String driverName = new Scanner(System.in).nextLine(); 9 | 10 | Car ferrari = new Ferrari(driverName); 11 | 12 | System.out.println(ferrari); 13 | 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/oop/interfacesAndAbstraction/sayHello/BasePerson.java: -------------------------------------------------------------------------------- 1 | package oop.interfacesAndAbstraction.sayHello; 2 | 3 | public abstract class BasePerson implements Person { 4 | 5 | private String name; 6 | 7 | protected BasePerson(String name) { 8 | this.name = name; 9 | } 10 | 11 | @Override 12 | public String getName() { 13 | return name; 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/oop/interfacesAndAbstraction/sayHello/Bulgarian.java: -------------------------------------------------------------------------------- 1 | package oop.interfacesAndAbstraction.sayHello; 2 | 3 | public class Bulgarian extends BasePerson { 4 | 5 | public Bulgarian(String name) { 6 | super(name); 7 | } 8 | 9 | @Override 10 | public String sayHello() { 11 | return "Здравей"; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/oop/interfacesAndAbstraction/sayHello/Chinese.java: -------------------------------------------------------------------------------- 1 | package oop.interfacesAndAbstraction.sayHello; 2 | 3 | public class Chinese extends BasePerson { 4 | 5 | public Chinese(String name) { 6 | super(name); 7 | } 8 | 9 | @Override 10 | public String sayHello() { 11 | return "Djydjybydjy"; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/oop/interfacesAndAbstraction/sayHello/European.java: -------------------------------------------------------------------------------- 1 | package oop.interfacesAndAbstraction.sayHello; 2 | 3 | public class European extends BasePerson { 4 | 5 | public European(String name) { 6 | super(name); 7 | } 8 | 9 | @Override 10 | public String sayHello() { 11 | return "Hello"; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/oop/interfacesAndAbstraction/sayHello/Main.java: -------------------------------------------------------------------------------- 1 | package oop.interfacesAndAbstraction.sayHello; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class Main { 7 | public static void main(String[] args) { 8 | 9 | List persons = new ArrayList<>(); 10 | 11 | persons.add(new Bulgarian("Peter")); 12 | persons.add(new European("Peter")); 13 | persons.add(new Chinese("Peter")); 14 | 15 | for (Person person : persons) { 16 | print(person); 17 | } 18 | 19 | } 20 | 21 | private static void print(Person person) { 22 | System.out.println(person.sayHello()); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/oop/interfacesAndAbstraction/sayHello/Person.java: -------------------------------------------------------------------------------- 1 | package oop.interfacesAndAbstraction.sayHello; 2 | 3 | public interface Person { 4 | 5 | String getName(); 6 | String sayHello(); 7 | 8 | } 9 | -------------------------------------------------------------------------------- /src/oop/reflection/AnnotationExample.java: -------------------------------------------------------------------------------- 1 | package oop.reflection; 2 | 3 | import java.lang.annotation.Annotation; 4 | import java.lang.reflect.InvocationTargetException; 5 | import java.lang.reflect.Method; 6 | 7 | public class AnnotationExample { 8 | public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { 9 | 10 | Class clazz = Reflection.class; 11 | 12 | Method method = clazz.getDeclaredMethod("setName", String.class); 13 | 14 | Annotation[][] parameterAnnotations = method.getParameterAnnotations(); 15 | 16 | Reflection reflection = new Reflection(); 17 | 18 | method.setAccessible(true); 19 | 20 | MyAnnotation myAnnotation = (MyAnnotation) parameterAnnotations[0][0]; 21 | 22 | method.invoke(reflection, myAnnotation.name()); 23 | 24 | System.out.println(reflection); 25 | 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/oop/reflection/GettersAndSetters.java: -------------------------------------------------------------------------------- 1 | package oop.reflection; 2 | 3 | import java.lang.reflect.InvocationTargetException; 4 | import java.lang.reflect.Method; 5 | import java.util.TreeSet; 6 | import java.util.function.Function; 7 | 8 | import static oop.reflection.ReflectionUtils.collectByName; 9 | import static oop.reflection.ReflectionUtils.filterMembersByName; 10 | 11 | public class GettersAndSetters { 12 | public static void main(String[] args) throws ClassNotFoundException, 13 | NoSuchMethodException, InvocationTargetException, 14 | InstantiationException, IllegalAccessException { 15 | 16 | Class clazz = Reflection.class; 17 | 18 | Method[] methods = clazz.getDeclaredMethods(); 19 | 20 | TreeSet getters = collectByName(filterMembersByName(methods, "get")); 21 | 22 | TreeSet setters = collectByName(filterMembersByName(methods, "set")); 23 | 24 | Function, String> formatType = c -> c == int.class ? "class int" : c.toString(); 25 | 26 | getters 27 | .forEach(m -> System.out.printf("%s will return %s%n", m.getName(), 28 | formatType.apply(m.getReturnType()))); 29 | 30 | setters 31 | .forEach(m -> System.out.printf("%s and will set field of %s%n", m.getName(), 32 | formatType.apply(m.getParameterTypes()[0]))); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/oop/reflection/HighQualityCode.java: -------------------------------------------------------------------------------- 1 | package oop.reflection; 2 | 3 | import java.lang.reflect.Field; 4 | import java.lang.reflect.Method; 5 | import java.lang.reflect.Modifier; 6 | import java.util.Arrays; 7 | import java.util.TreeSet; 8 | 9 | import static oop.reflection.ReflectionUtils.*; 10 | 11 | public class HighQualityCode { 12 | public static void main(String[] args) { 13 | 14 | Class clazz = Reflection.class; 15 | 16 | Method[] methods = clazz.getDeclaredMethods(); 17 | 18 | Field[] declaredFields = clazz.getDeclaredFields(); 19 | 20 | TreeSet fields = collectByName(Arrays.stream(declaredFields)); 21 | 22 | filterMembers(fields.stream(), f -> !Modifier.isPrivate(f.getModifiers())) 23 | .forEach(f -> System.out.println(f.getName() + " must be private!")); 24 | 25 | TreeSet getters = collectByName(filterMembersByName(methods, "get")); 26 | 27 | filterMembers(getters.stream(), g -> !Modifier.isPublic(g.getModifiers())) 28 | .forEach(g -> System.out.println(g.getName() + " have to be public!")); 29 | 30 | TreeSet setters = collectByName(filterMembersByName(methods, "set")); 31 | 32 | filterMembers(setters.stream(), s -> !Modifier.isPrivate(s.getModifiers())) 33 | .forEach(s -> System.out.println(s.getName() + " have to be private!")); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/oop/reflection/MyAnnotation.java: -------------------------------------------------------------------------------- 1 | package oop.reflection; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | @Target(ElementType.PARAMETER) 9 | @Retention(RetentionPolicy.RUNTIME) 10 | public @interface MyAnnotation { 11 | 12 | String name(); 13 | 14 | } 15 | -------------------------------------------------------------------------------- /src/oop/reflection/Reflection.java: -------------------------------------------------------------------------------- 1 | package oop.reflection; 2 | 3 | import java.io.Serializable; 4 | 5 | public class Reflection implements Serializable { 6 | 7 | private static final String nickName = "Pinguin"; 8 | public String name; 9 | protected String webAddress; 10 | String email; 11 | private int zip; 12 | 13 | public Reflection() { 14 | this.setName("Java"); 15 | this.setWebAddress("oracle.com"); 16 | this.setEmail("mail@oracle.com"); 17 | this.setZip(1407); 18 | } 19 | 20 | private Reflection(String name, String webAddress, String email) { 21 | this.setName(name); 22 | this.setWebAddress(webAddress); 23 | this.setEmail(email); 24 | this.setZip(2300); 25 | } 26 | 27 | protected Reflection(String name, String webAddress, String email, int zip) { 28 | this.setName(name); 29 | this.setWebAddress(webAddress); 30 | this.setEmail(email); 31 | this.setZip(2300); 32 | } 33 | 34 | public final String getName() { 35 | return name; 36 | } 37 | 38 | private void setName(@MyAnnotation(name = "MyExample") String name) { 39 | this.name = name; 40 | } 41 | 42 | protected String getWebAddress() { 43 | return webAddress; 44 | } 45 | 46 | private void setWebAddress(String webAddress) { 47 | this.webAddress = webAddress; 48 | } 49 | 50 | public String getEmail() { 51 | return email; 52 | } 53 | 54 | public void setEmail(String email) { 55 | this.email = email; 56 | } 57 | 58 | protected final int getZip() { 59 | return zip; 60 | } 61 | 62 | private void setZip(int zip) { 63 | this.zip = zip; 64 | } 65 | 66 | public String toString() { 67 | String result = "Name: " + getName() + "\n"; 68 | result += "WebAddress: " + getWebAddress() + "\n"; 69 | result += "email: " + getEmail() + "\n"; 70 | result += "zip: " + getZip() + "\n"; 71 | return result; 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/oop/reflection/ReflectionUtils.java: -------------------------------------------------------------------------------- 1 | package oop.reflection; 2 | 3 | import java.lang.reflect.Member; 4 | import java.util.*; 5 | import java.util.function.Predicate; 6 | import java.util.stream.Collectors; 7 | import java.util.stream.Stream; 8 | 9 | public class ReflectionUtils { 10 | 11 | private ReflectionUtils() throws IllegalAccessException { 12 | throw new IllegalAccessException("Accessing this constructor is forbidden"); 13 | } 14 | 15 | public static Stream filterMembersByName(T[] members, String filter) { 16 | return filterMembers(members, m -> m.getName().contains(filter)); 17 | } 18 | 19 | public static Stream filterMembers(T[] members, Predicate predicate) { 20 | return filterMembers(Arrays.stream(members), predicate); 21 | } 22 | 23 | public static Stream filterMembers(Stream stream, Predicate predicate) { 24 | return stream.filter(predicate); 25 | } 26 | 27 | public static TreeSet collectByName(Stream stream) { 28 | return stream.collect(Collectors.toCollection( 29 | () -> new TreeSet<>(Comparator.comparing(Member::getName)))); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/oop/solid/Base64Algorithm.java: -------------------------------------------------------------------------------- 1 | package oop.solid; 2 | 3 | import java.util.Base64; 4 | 5 | public class Base64Algorithm implements Encryp, Decrypt { 6 | @Override 7 | public String encode(String password) { 8 | return new String(Base64.getEncoder().encode(password.getBytes())); 9 | } 10 | 11 | @Override 12 | public String decode(String hash) { 13 | return new String(Base64.getDecoder().decode(hash.getBytes())); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/oop/solid/Decrypt.java: -------------------------------------------------------------------------------- 1 | package oop.solid; 2 | 3 | public interface Decrypt { 4 | String decode(String hash); 5 | 6 | } 7 | -------------------------------------------------------------------------------- /src/oop/solid/Encryp.java: -------------------------------------------------------------------------------- 1 | package oop.solid; 2 | 3 | public interface Encryp { 4 | String encode(String password); 5 | 6 | } 7 | -------------------------------------------------------------------------------- /src/oop/solid/Main.java: -------------------------------------------------------------------------------- 1 | package oop.solid; 2 | 3 | import java.security.NoSuchAlgorithmException; 4 | import java.util.Scanner; 5 | 6 | public class Main { 7 | public static void main(String[] args) throws NoSuchAlgorithmException { 8 | 9 | String password = "my-password"; 10 | 11 | PasswordHasher passwordHasher = new PasswordHasher(new Sha256Algorithm()); 12 | 13 | String hash = passwordHasher.hash(password); 14 | 15 | System.out.println(hash); 16 | 17 | Scanner scanner = new Scanner(System.in); 18 | 19 | System.out.print("Enter password: "); 20 | String loginInfo = scanner.nextLine(); 21 | 22 | while (!passwordHasher.hash(loginInfo).equals(hash)) { 23 | System.out.print(System.lineSeparator() + "Enter password: "); 24 | loginInfo = scanner.nextLine(); 25 | } 26 | 27 | System.out.println("Welcome!"); 28 | 29 | } 30 | 31 | public static String decodeBase64Hash(String hash, PasswordDecoder passwordDecoder) { 32 | return passwordDecoder.decode(hash); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/oop/solid/PasswordDecoder.java: -------------------------------------------------------------------------------- 1 | package oop.solid; 2 | 3 | import java.util.Base64; 4 | 5 | public class PasswordDecoder { 6 | 7 | public String decode(String hash) { 8 | return new String(Base64.getEncoder().encode(hash.getBytes())); 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/oop/solid/PasswordHasher.java: -------------------------------------------------------------------------------- 1 | package oop.solid; 2 | 3 | import java.security.NoSuchAlgorithmException; 4 | 5 | public class PasswordHasher { 6 | 7 | private Encryp encryp; 8 | 9 | public PasswordHasher(Encryp encryp) { 10 | this.encryp = encryp; 11 | } 12 | 13 | public String hash(String password) { 14 | return encryp.encode(password); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/oop/solid/Sha256Algorithm.java: -------------------------------------------------------------------------------- 1 | package oop.solid; 2 | 3 | import java.security.MessageDigest; 4 | import java.security.NoSuchAlgorithmException; 5 | 6 | public class Sha256Algorithm implements Encryp { 7 | @Override 8 | public String encode(String password) { 9 | try { 10 | MessageDigest messageDigest = MessageDigest.getInstance("sha256"); 11 | return new String(messageDigest.digest(password.getBytes())); 12 | } catch (NoSuchAlgorithmException e) { 13 | throw new RuntimeException(e); 14 | } 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/oop/workingWithAbstraction/DayOfWeek.java: -------------------------------------------------------------------------------- 1 | package oop.workingWithAbstraction; 2 | 3 | public enum DayOfWeek { 4 | MONDAY(1), 5 | TUESDAY(2), 6 | WEDNESDAY(3), 7 | THURSDAY(4), 8 | FRIDAY(5), 9 | SATURDAY(6), 10 | SUNDAY(7); 11 | 12 | private int dayNumber; 13 | 14 | private DayOfWeek(int dayNumber) { 15 | this.dayNumber = dayNumber; 16 | } 17 | 18 | public int getDayNumber() { 19 | return dayNumber; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/oop/workingWithAbstraction/Discount.java: -------------------------------------------------------------------------------- 1 | package oop.workingWithAbstraction; 2 | 3 | public enum Discount { 4 | VIP(0.80), 5 | SECOND_VISIT(0.90), 6 | NONE(1); 7 | 8 | private double priceReductionFactor; 9 | 10 | Discount(double priceReductionFactor) { 11 | this.priceReductionFactor = priceReductionFactor; 12 | } 13 | 14 | public double getPriceReductionFactor() { 15 | return priceReductionFactor; 16 | } 17 | 18 | public static Discount parse(String str) { 19 | switch (str) { 20 | case "VIP": 21 | return VIP; 22 | case "SecondVisit": 23 | return SECOND_VISIT; 24 | case "None": 25 | return NONE; 26 | default: 27 | throw new IllegalArgumentException("Unknown enum value" + str); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/oop/workingWithAbstraction/Main.java: -------------------------------------------------------------------------------- 1 | package oop.workingWithAbstraction; 2 | 3 | import java.util.Scanner; 4 | 5 | public class Main { 6 | public static void main(String[] args) { 7 | 8 | Scanner scanner = new Scanner(System.in); 9 | 10 | String[] tokens = scanner.nextLine().split("\\s+"); 11 | 12 | double pricePerDay = Double.parseDouble(tokens[0]); 13 | int days = Integer.parseInt(tokens[1]); 14 | Season season = Season.parse(tokens[2]); 15 | Discount discount = Discount.parse(tokens[3]); 16 | 17 | PriceCalculator calculator = new PriceCalculator(pricePerDay, days, season, discount); 18 | 19 | System.out.printf("%.2f%n", calculator.calculatePrice()); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/oop/workingWithAbstraction/PriceCalculator.java: -------------------------------------------------------------------------------- 1 | package oop.workingWithAbstraction; 2 | 3 | public class PriceCalculator { 4 | private double pricePerDay; 5 | private int days; 6 | private Season season; 7 | private Discount discount; 8 | 9 | public PriceCalculator(double pricePerDay, int days, Season season, Discount discount) { 10 | this.pricePerDay = pricePerDay; 11 | this.days = days; 12 | this.season = season; 13 | this.discount = discount; 14 | } 15 | 16 | public double calculatePrice() { 17 | return pricePerDay * days * season.getMultiplier() * discount.getPriceReductionFactor(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/oop/workingWithAbstraction/RhombusOfStars.java: -------------------------------------------------------------------------------- 1 | package oop.workingWithAbstraction; 2 | 3 | import java.util.Scanner; 4 | 5 | public class RhombusOfStars { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | 9 | int n = Integer.parseInt(scanner.nextLine()); 10 | 11 | printRhombus(n); 12 | } 13 | 14 | public static void printRhombus(int size) { 15 | for (int i = 1; i <= size; i++) { 16 | printTriangle(size - i, i); 17 | } 18 | 19 | for (int i = 1; i < size; i++) { 20 | printTriangle(i, size - i); 21 | } 22 | } 23 | 24 | private static void printTriangle(int firstCount, int secondCount) { 25 | for (int i = 0; i < firstCount; i++) { 26 | System.out.print(" "); 27 | } 28 | 29 | for (int i = 0; i < secondCount; i++) { 30 | System.out.print("* "); 31 | } 32 | 33 | System.out.println(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/oop/workingWithAbstraction/Season.java: -------------------------------------------------------------------------------- 1 | package oop.workingWithAbstraction; 2 | 3 | import java.util.Locale; 4 | 5 | public enum Season { 6 | AUTUMN(1), 7 | SPRING(2), 8 | WINTER(3), 9 | SUMMER(4); 10 | 11 | private int multiplier; 12 | 13 | Season(int multiplier) { 14 | this.multiplier = multiplier; 15 | } 16 | 17 | public int getMultiplier() { 18 | return multiplier; 19 | } 20 | 21 | public static Season parse(String str) { 22 | return Season.valueOf(str.toUpperCase()); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/oop/workingWithAbstraction/pointInRectangle/Main.java: -------------------------------------------------------------------------------- 1 | package oop.workingWithAbstraction.pointInRectangle; 2 | 3 | import java.util.Arrays; 4 | import java.util.Scanner; 5 | 6 | public class Main { 7 | public static void main(String[] args) { 8 | Scanner scanner = new Scanner(System.in); 9 | 10 | int[] coordinates = getCoordinates(scanner); 11 | 12 | Point A = new Point(coordinates[0], coordinates[1]); 13 | Point C = new Point(coordinates[2], coordinates[3]); 14 | 15 | Rectangle rect = new Rectangle(A, C); 16 | 17 | int n = Integer.parseInt(scanner.nextLine()); 18 | 19 | while (n-- > 0) { 20 | int[] pointCoordinates = getCoordinates(scanner); 21 | 22 | Point x = new Point(pointCoordinates[0], pointCoordinates[1]); 23 | 24 | // Pa(x1, y1), Pb(x2, y2), Px(x3, y3) 25 | // For Px to be inside the following should be true: 26 | // x3 >= x1 && y3 >= y1 && x3 <= x2 && y3 <= y2 27 | 28 | boolean isInside = rect.contains(x); 29 | 30 | System.out.println(isInside); 31 | } 32 | } 33 | 34 | private static int[] getCoordinates(Scanner scanner) { 35 | return Arrays.stream(scanner.nextLine().split("\\s+")) 36 | .mapToInt(Integer::parseInt) 37 | .toArray(); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/oop/workingWithAbstraction/pointInRectangle/Point.java: -------------------------------------------------------------------------------- 1 | package oop.workingWithAbstraction.pointInRectangle; 2 | 3 | public class Point { 4 | private int x; 5 | private int y; 6 | 7 | public Point(int x, int y) { 8 | this.x = x; 9 | this.y = y; 10 | } 11 | 12 | public boolean greaterOrEqual(Point other) { 13 | return x >= other.x && y >= other.y; 14 | } 15 | 16 | public boolean lessOrEqual(Point other) { 17 | return x <= other.x && y <= other.y; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/oop/workingWithAbstraction/pointInRectangle/Rectangle.java: -------------------------------------------------------------------------------- 1 | package oop.workingWithAbstraction.pointInRectangle; 2 | 3 | public class Rectangle { 4 | private Point A; 5 | private Point C; 6 | 7 | public Rectangle(Point A, Point C) { 8 | this.A = A; 9 | this.C = C; 10 | } 11 | 12 | public boolean contains(Point x) { 13 | return x.greaterOrEqual(A) && x.lessOrEqual(C); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/oop/workingWithAbstraction/studentSystem/Main.java: -------------------------------------------------------------------------------- 1 | package oop.workingWithAbstraction.studentSystem; 2 | 3 | import oop.workingWithAbstraction.DayOfWeek; 4 | 5 | import java.util.Scanner; 6 | 7 | public class Main { 8 | public static void main(String[] args) { 9 | Scanner scanner = new Scanner(System.in); 10 | 11 | StudentSystem studentSystem = new StudentSystem(); 12 | 13 | while (true) { 14 | String[] input = scanner.nextLine().split("\\s+"); 15 | 16 | if (input[0].equals("Exit")) { 17 | break; 18 | } 19 | 20 | studentSystem.ParseCommand(input); 21 | } 22 | 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/oop/workingWithAbstraction/studentSystem/Student.java: -------------------------------------------------------------------------------- 1 | package oop.workingWithAbstraction.studentSystem; 2 | 3 | public class Student { 4 | private String name; 5 | private int age; 6 | private double grade; 7 | 8 | public Student(String name, int age, double grade) { 9 | this.name = name; 10 | this.age = age; 11 | this.grade = grade; 12 | } 13 | 14 | public String getInfo() { 15 | 16 | String studentInfo = String.format("%s is %s years old.", name, age); 17 | 18 | if (grade >= 5.00) { 19 | studentInfo += " Excellent student."; 20 | } else if (grade < 5.00 && grade >= 3.50) { 21 | studentInfo += " Average student."; 22 | } else { 23 | studentInfo += " Very nice person."; 24 | } 25 | 26 | return studentInfo; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/oop/workingWithAbstraction/studentSystem/StudentSystem.java: -------------------------------------------------------------------------------- 1 | package oop.workingWithAbstraction.studentSystem; 2 | 3 | import oop.workingWithAbstraction.pointInRectangle.Point; 4 | 5 | import java.util.HashMap; 6 | import java.util.Map; 7 | 8 | public class StudentSystem { 9 | private Map studentsByName; 10 | 11 | public StudentSystem() { 12 | this.studentsByName = new HashMap<>(); 13 | } 14 | 15 | public Map getStudentsByName() { 16 | return this.studentsByName; 17 | } 18 | 19 | public void ParseCommand(String[] args) { 20 | 21 | String command = args[0]; 22 | 23 | String name = args[1]; 24 | 25 | if (command.equals("Create")) { 26 | int age = Integer.parseInt(args[2]); 27 | double grade = Double.parseDouble(args[3]); 28 | 29 | if (!studentsByName.containsKey(name)) { 30 | Student student = new Student(name, age, grade); 31 | studentsByName.put(name, student); 32 | } 33 | 34 | } else if (command.equals("Show")) { 35 | 36 | Student student = studentsByName.get(name); 37 | 38 | if (student != null) { 39 | System.out.println(student.getInfo()); 40 | } 41 | 42 | } else { 43 | throw new IllegalArgumentException("Unknown command " + command); 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /testing-demo/.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | -------------------------------------------------------------------------------- /testing-demo/.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /testing-demo/.idea/jarRepositories.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 9 | 10 | 14 | 15 | 19 | 20 | -------------------------------------------------------------------------------- /testing-demo/.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /testing-demo/.idea/uiDesigner.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | -------------------------------------------------------------------------------- /testing-demo/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | org.example 8 | testing-demo 9 | 1.0-SNAPSHOT 10 | 11 | 12 | 17 13 | 17 14 | 15 | 16 | 17 | 18 | junit 19 | junit 20 | 4.12 21 | test 22 | 23 | 24 | org.mockito 25 | mockito-core 26 | 3.0.0 27 | test 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /testing-demo/src/main/java/Main.java: -------------------------------------------------------------------------------- 1 | import rpg_lab.Axe; 2 | 3 | public class Main { 4 | 5 | public static void main(String[] args) { 6 | Axe axe = new Axe(13, 42); 7 | 8 | System.out.println(axe.getAttackPoints()); 9 | System.out.println(axe.getDurabilityPoints()); 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /testing-demo/src/main/java/rpg_lab/Axe.java: -------------------------------------------------------------------------------- 1 | package rpg_lab; 2 | 3 | public class Axe implements Weapon { 4 | 5 | private int attackPoints; 6 | private int durabilityPoints; 7 | 8 | public Axe(int attack, int durability) { 9 | this.attackPoints = attack; 10 | this.durabilityPoints = durability; 11 | } 12 | 13 | @Override 14 | public int getAttackPoints() { 15 | return this.attackPoints; 16 | } 17 | 18 | @Override 19 | public int getDurabilityPoints() { 20 | return this.durabilityPoints; 21 | } 22 | 23 | @Override 24 | public void attack(Target target) { 25 | if (this.durabilityPoints <= 0) { 26 | throw new IllegalStateException("Axe is broken."); 27 | } 28 | 29 | target.takeAttack(this.attackPoints); 30 | this.durabilityPoints -= 1; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /testing-demo/src/main/java/rpg_lab/Dummy.java: -------------------------------------------------------------------------------- 1 | package rpg_lab; 2 | 3 | public class Dummy implements Target { 4 | 5 | private int health; 6 | private int experience; 7 | 8 | public Dummy(int health, int experience) { 9 | this.health = health; 10 | this.experience = experience; 11 | } 12 | 13 | @Override 14 | public int getHealth() { 15 | return this.health; 16 | } 17 | 18 | @Override 19 | public void takeAttack(int attackPoints) { 20 | if (this.isDead()) { 21 | throw new IllegalStateException("Dummy is dead."); 22 | } 23 | 24 | this.health -= attackPoints; 25 | } 26 | 27 | @Override 28 | public int giveExperience() { 29 | if (!this.isDead()) { 30 | throw new IllegalStateException("Target is not dead."); 31 | } 32 | 33 | return this.experience * 2; 34 | } 35 | 36 | @Override 37 | public Boolean isDead() { 38 | return this.health <= 0; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /testing-demo/src/main/java/rpg_lab/Hero.java: -------------------------------------------------------------------------------- 1 | package rpg_lab; 2 | 3 | public class Hero { 4 | 5 | private String name; 6 | private int experience; 7 | private Weapon weapon; 8 | 9 | public Hero(String name, Weapon weapon) { 10 | this.name = name; 11 | this.experience = 0; 12 | this.weapon = weapon; 13 | } 14 | 15 | public String getName() { 16 | return this.name; 17 | } 18 | 19 | public int getExperience() { 20 | return this.experience; 21 | } 22 | 23 | public Weapon getWeapon() { 24 | return this.weapon; 25 | } 26 | 27 | public void attack(Target target) { 28 | this.weapon.attack(target); 29 | 30 | if (target.isDead()) { 31 | this.experience += target.giveExperience(); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /testing-demo/src/main/java/rpg_lab/Target.java: -------------------------------------------------------------------------------- 1 | package rpg_lab; 2 | 3 | public interface Target { 4 | int getHealth(); 5 | 6 | void takeAttack(int attackPoints); 7 | 8 | int giveExperience(); 9 | 10 | Boolean isDead(); 11 | 12 | } 13 | -------------------------------------------------------------------------------- /testing-demo/src/main/java/rpg_lab/Weapon.java: -------------------------------------------------------------------------------- 1 | package rpg_lab; 2 | 3 | public interface Weapon { 4 | int getAttackPoints(); 5 | 6 | int getDurabilityPoints(); 7 | 8 | void attack(Target target); 9 | } 10 | -------------------------------------------------------------------------------- /testing-demo/src/test/java/rpg_lab/AxeTest.java: -------------------------------------------------------------------------------- 1 | package rpg_lab; 2 | 3 | import org.junit.Before; 4 | import org.junit.Test; 5 | 6 | import static org.junit.Assert.*; 7 | 8 | public class AxeTest { 9 | 10 | private static final int ATTACK = 13; 11 | private static final int DURABILITY = 42; 12 | private static final int HEALTH = 13; 13 | private static final int EXPERIENCE = 42; 14 | private Axe axe; 15 | private Dummy dummy; 16 | 17 | @Before 18 | public void setUp() { 19 | this.axe = new Axe(ATTACK, DURABILITY); 20 | this.dummy = new Dummy(HEALTH, EXPERIENCE); 21 | } 22 | 23 | @Test 24 | public void test_AxeCreation_WillReturn_SameValues_AsCreated() { 25 | assertEquals(ATTACK, axe.getAttackPoints()); 26 | assertEquals(DURABILITY, axe.getDurabilityPoints()); 27 | } 28 | 29 | @Test 30 | public void test_AxeLoosesDurability_AfterAttacking() { 31 | axe.attack(dummy); 32 | assertEquals(DURABILITY - 1, axe.getDurabilityPoints()); 33 | } 34 | 35 | @Test(expected = IllegalStateException.class) 36 | public void test_AxeAttack_WhenBroken_Fails() { 37 | int durability = 0; 38 | 39 | Axe axe = new Axe(ATTACK, durability); 40 | 41 | // Assert the axe is broken 42 | assertEquals(0, axe.getDurabilityPoints()); 43 | 44 | axe.attack(dummy); 45 | } 46 | 47 | } -------------------------------------------------------------------------------- /testing-demo/src/test/java/rpg_lab/DummyTest.java: -------------------------------------------------------------------------------- 1 | package rpg_lab; 2 | 3 | import org.junit.Before; 4 | import org.junit.Test; 5 | 6 | import static org.junit.Assert.*; 7 | 8 | public class DummyTest { 9 | 10 | private static final int DEAD_HEALTH = 0; 11 | private static final int ALIVE_HEALTH = 10; 12 | private static final int EXPERIENCE = 30; 13 | 14 | private static int ATTACK_POINTS = 1; 15 | 16 | private Dummy aliveDummy; 17 | private Dummy deadDummy; 18 | 19 | @Before 20 | public void setUp() { 21 | this.aliveDummy = new Dummy(ALIVE_HEALTH, EXPERIENCE); 22 | this.deadDummy = new Dummy(DEAD_HEALTH, EXPERIENCE); 23 | } 24 | 25 | @Test 26 | public void test_Dummy_LosesHealth_WhenAttacked() { 27 | aliveDummy.takeAttack(ATTACK_POINTS); 28 | assertEquals(ALIVE_HEALTH - ATTACK_POINTS, aliveDummy.getHealth()); 29 | } 30 | 31 | @Test(expected = IllegalStateException.class) 32 | public void test_DeadDummy_CannotBeAttacked() { 33 | deadDummy.takeAttack(ATTACK_POINTS); 34 | } 35 | 36 | @Test 37 | public void test_DeadDummy_Gives_Experience() { 38 | int actual = deadDummy.giveExperience(); 39 | assertEquals(EXPERIENCE * 2, actual); 40 | } 41 | 42 | @Test(expected = IllegalStateException.class) 43 | public void test_AliveDummy_CannotGive_Experience() { 44 | aliveDummy.giveExperience(); 45 | } 46 | 47 | @Test 48 | public void test_AliveDummy_IsAlive() { 49 | assertFalse(aliveDummy.isDead()); 50 | } 51 | 52 | @Test 53 | public void test_DeadDummy_IsDead() { 54 | assertTrue(deadDummy.isDead()); 55 | } 56 | 57 | } -------------------------------------------------------------------------------- /testing-demo/src/test/java/rpg_lab/HeroTest.java: -------------------------------------------------------------------------------- 1 | package rpg_lab; 2 | 3 | import org.junit.Test; 4 | import org.mockito.Mockito; 5 | 6 | import static org.junit.Assert.*; 7 | 8 | public class HeroTest { 9 | 10 | // Example of stubbed implementation of Weapon just for tests 11 | private static class FakeWeapon implements Weapon { 12 | @Override 13 | public int getAttackPoints() { 14 | return 0; 15 | } 16 | 17 | @Override 18 | public int getDurabilityPoints() { 19 | return 0; 20 | } 21 | 22 | @Override 23 | public void attack(Target target) { 24 | } 25 | } 26 | 27 | @Test 28 | public void test_HeroGainsXP_When_KillingTarget() { 29 | Hero hero = new Hero("Javarcho", new FakeWeapon()); 30 | 31 | assertEquals(0, hero.getExperience()); 32 | 33 | // Example of anonymous class instance of Target just to fake giveExperience() and isDead() 34 | Target target = new Target() { 35 | @Override 36 | public int getHealth() { 37 | return 0; 38 | } 39 | 40 | @Override 41 | public void takeAttack(int attackPoints) { 42 | 43 | } 44 | 45 | @Override 46 | public int giveExperience() { 47 | return 200; 48 | } 49 | 50 | @Override 51 | public Boolean isDead() { 52 | return true; 53 | } 54 | }; 55 | 56 | hero.attack(target); 57 | 58 | assertEquals(200, hero.getExperience()); 59 | } 60 | 61 | @Test 62 | public void test_HeroGainsXP_When_KillingTarget_Mocking_Example() { 63 | Weapon weapon = Mockito.mock(Weapon.class); 64 | 65 | Hero hero = new Hero("Javarcho", weapon); 66 | 67 | assertEquals(0, hero.getExperience()); 68 | 69 | Target target = Mockito.mock(Target.class); 70 | 71 | Mockito.when(target.isDead()).thenReturn(true); 72 | Mockito.when(target.giveExperience()).thenReturn(200); 73 | 74 | hero.attack(target); 75 | 76 | assertEquals(200, hero.getExperience()); 77 | } 78 | 79 | @Test 80 | public void test_HeroGainsXP_When_KillingTarget_Real_Objects_Example() { 81 | Weapon weapon = new Axe(13, 42); 82 | 83 | Hero hero = new Hero("Javarcho", weapon); 84 | 85 | assertEquals(0, hero.getExperience()); 86 | 87 | Target target = new Dummy(13, 200); 88 | 89 | hero.attack(target); 90 | 91 | assertEquals(200, hero.getExperience()); 92 | } 93 | 94 | } -------------------------------------------------------------------------------- /testing-demo/target/classes/Main.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mpaunov/Java-Advanced-Lectures/b389a672ed7d38a5266610f7a834ee52a4e70187/testing-demo/target/classes/Main.class -------------------------------------------------------------------------------- /testing-demo/target/classes/rpg_lab/Axe.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mpaunov/Java-Advanced-Lectures/b389a672ed7d38a5266610f7a834ee52a4e70187/testing-demo/target/classes/rpg_lab/Axe.class -------------------------------------------------------------------------------- /testing-demo/target/classes/rpg_lab/Dummy.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mpaunov/Java-Advanced-Lectures/b389a672ed7d38a5266610f7a834ee52a4e70187/testing-demo/target/classes/rpg_lab/Dummy.class -------------------------------------------------------------------------------- /testing-demo/target/classes/rpg_lab/Hero.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mpaunov/Java-Advanced-Lectures/b389a672ed7d38a5266610f7a834ee52a4e70187/testing-demo/target/classes/rpg_lab/Hero.class -------------------------------------------------------------------------------- /testing-demo/target/classes/rpg_lab/Target.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mpaunov/Java-Advanced-Lectures/b389a672ed7d38a5266610f7a834ee52a4e70187/testing-demo/target/classes/rpg_lab/Target.class -------------------------------------------------------------------------------- /testing-demo/target/classes/rpg_lab/Weapon.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mpaunov/Java-Advanced-Lectures/b389a672ed7d38a5266610f7a834ee52a4e70187/testing-demo/target/classes/rpg_lab/Weapon.class -------------------------------------------------------------------------------- /testing-demo/target/test-classes/rpg_lab/AxeTest.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mpaunov/Java-Advanced-Lectures/b389a672ed7d38a5266610f7a834ee52a4e70187/testing-demo/target/test-classes/rpg_lab/AxeTest.class -------------------------------------------------------------------------------- /testing-demo/target/test-classes/rpg_lab/DummyTest.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mpaunov/Java-Advanced-Lectures/b389a672ed7d38a5266610f7a834ee52a4e70187/testing-demo/target/test-classes/rpg_lab/DummyTest.class -------------------------------------------------------------------------------- /testing-demo/target/test-classes/rpg_lab/HeroTest$1.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mpaunov/Java-Advanced-Lectures/b389a672ed7d38a5266610f7a834ee52a4e70187/testing-demo/target/test-classes/rpg_lab/HeroTest$1.class -------------------------------------------------------------------------------- /testing-demo/target/test-classes/rpg_lab/HeroTest$FakeWeapon.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mpaunov/Java-Advanced-Lectures/b389a672ed7d38a5266610f7a834ee52a4e70187/testing-demo/target/test-classes/rpg_lab/HeroTest$FakeWeapon.class -------------------------------------------------------------------------------- /testing-demo/target/test-classes/rpg_lab/HeroTest.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mpaunov/Java-Advanced-Lectures/b389a672ed7d38a5266610f7a834ee52a4e70187/testing-demo/target/test-classes/rpg_lab/HeroTest.class --------------------------------------------------------------------------------