├── OOP-1-classes-constructors-inheritance ├── class-constructors-challenge │ ├── BankAccount.java │ ├── Main.java │ └── VipCustomer.java ├── classes │ ├── Car.java │ └── Main.java ├── inheritance-challenge-ver1 │ ├── Car.java │ ├── Main.java │ ├── Sedan.java │ └── Vehicle.java ├── inheritance-challenge-ver2 │ ├── Car.java │ ├── Main.java │ ├── Outlander.java │ └── Vehicle.java ├── inheritance-training-project │ ├── Computer.java │ ├── Laptop.java │ └── Main.java └── inheritance │ ├── Animal.java │ ├── Dog.java │ ├── Fish.java │ └── Main.java ├── OOP-2-composition-encapsulation-polymorphism ├── composition-challenge │ ├── Bathroom.java │ ├── Bed.java │ ├── House.java │ ├── Kitchen.java │ ├── Lamp.java │ ├── Main.java │ └── Room.java ├── composition │ ├── Car.java │ ├── Case.java │ ├── Dimensions.java │ ├── Main.java │ ├── Monitor.java │ ├── Motherboard.java │ ├── PC.java │ ├── Resolution.java │ └── Vehicle.java ├── encapsulation-challenge │ ├── Main.java │ └── Printer.java ├── encapsulation │ ├── EnhancedPlayer.java │ └── Main.java ├── oop-master-challenge-by-tim │ ├── DeluxeBurger.java │ ├── Hamburger.java │ ├── HealthyBurger.java │ └── Main.java ├── oop-master-challenge │ ├── Addition.java │ ├── DeluxeHamburger.java │ ├── Hamburger.java │ ├── HealthyBurger.java │ ├── Main.java │ └── RollType.java ├── polymorphism-challenge │ └── PolymorphismChallenge.java └── polymorphism │ └── Polymorphism.java ├── README.md ├── arrays-lists-autoboxing-unboxing ├── ArrayChallenge │ └── ArrayChallenge.java ├── ArrayListChallenge-MobilePhoneApp │ ├── Contact.java │ ├── Main.java │ └── MobilePhone.java ├── ArrayListTraining-TODOList │ ├── Main.java │ └── ToDoList.java ├── Arrays │ └── Arrays.java ├── ArraysWithScanner │ └── ArraysWithScanner.java ├── Autoboxing-unboxing │ └── AutoboxingUnboxing.java ├── AutoboxingUnboxingChallenge │ ├── Bank.java │ ├── Branch.java │ ├── Customer.java │ └── Main.java ├── GroceryApp │ ├── GroceryApp.java │ └── GroceryList.java ├── LinkedList-Challenge │ ├── Album.java │ ├── Main.java │ └── Song.java ├── LinkedList │ ├── Customer.java │ ├── Demo.java │ └── Main.java ├── MinElementChallenge │ └── MinElementChallenge.java ├── ReisizingArrayWithNewValues │ └── ResizingArrayWithNewValues.java ├── ReverseArrayChallenge │ └── ReverseArrayChallenge.java └── VisitedPlaces-ArrayList-training │ ├── Main.java │ └── VisitedPlaces.java ├── control-flow-statements ├── DayOfTheWeek.java ├── DiagonalStar.java ├── DigitSumChallenge.java ├── EvenDigitSum.java ├── FactorsPrinter.java ├── FirstLastDigitSum.java ├── FlourPacker.java ├── ForLoop.java ├── GreatestCommonDivisor.java ├── LargestPrime.java ├── LastDigitChecker.java ├── MinMaxInputChallenge.java ├── NumberInWord.java ├── NumberOfDaysInMonths.java ├── NumberPalindrome.java ├── NumberToWords.java ├── ParsingValuesFromString.java ├── PerfectNumber.java ├── ReadingUserInput.java ├── ReadingUserInputChallenge.java ├── SharedDigit.java ├── Sum3And5Challenge.java ├── SumOddRange.java ├── Switch.java ├── UserInputTraining.java └── WhileAndDoWhile.java ├── expressions-statements-methods ├── AreaCalculator.java ├── BarkingDog.java ├── CheckNumber.java ├── DecimalComparator.java ├── EqualSumChecker.java ├── GallonCalc.java ├── IfKeywordAndCodeBlocks.java ├── LeapYear.java ├── MegabytesConverter.java ├── MethodOverloading.java ├── Methods.java ├── MinutesYearsDaysCalc.java ├── PlayingCat.java ├── SecondsMinutesHours.java └── TeenNumberChecker.java ├── inner-abstract-classes-interfaces ├── abstract-classes │ ├── Animal.java │ ├── Bird.java │ ├── CanFly.java │ ├── Cat.java │ ├── Dog.java │ ├── Main.java │ ├── Parrot.java │ └── Penguin.java ├── inner-classes │ ├── Gearbox.java │ └── Main.java ├── interface-challenge │ ├── ISaveable.java │ ├── Main.java │ ├── Monster.java │ └── Player.java └── interfaces │ ├── DeskPhone.java │ ├── ITelephone.java │ ├── Main.java │ └── MobilePhone.java └── variables-datatypes-operators ├── CharAndBoolean.java ├── FloatAndDouble.java ├── Operators.java ├── PrimitiveDataTypes.java └── Strings.java /OOP-1-classes-constructors-inheritance/class-constructors-challenge/BankAccount.java: -------------------------------------------------------------------------------- 1 | public class BankAccount { 2 | 3 | private int accountNumber; 4 | private double balance; 5 | private String customerName; 6 | private String email; 7 | private int phoneNumber; 8 | 9 | public BankAccount(int accountNumber, double accountBalance, String customerName, String email, int phone) { 10 | this.accountNumber = accountNumber; 11 | this.balance = accountBalance; 12 | this.customerName = customerName; 13 | this.email = email; 14 | this.phoneNumber = phone; 15 | } 16 | 17 | public BankAccount() { 18 | } 19 | 20 | public BankAccount(String customerName, String email, int phoneNumber) { 21 | this(452312312, 25, customerName, email, phoneNumber); 22 | } 23 | 24 | public int getAccountNumber() { 25 | return accountNumber; 26 | } 27 | 28 | public void setAccountNumber(int accountNumber) { 29 | this.accountNumber = accountNumber; 30 | } 31 | 32 | public double getBalance() { 33 | return balance; 34 | } 35 | 36 | public void setBalance(double balance) { 37 | this.balance = balance; 38 | } 39 | 40 | public String getCustomerName() { 41 | return customerName; 42 | } 43 | 44 | public void setCustomerName(String customerName) { 45 | this.customerName = customerName; 46 | } 47 | 48 | public String getEmail() { 49 | return email; 50 | } 51 | 52 | public void setEmail(String email) { 53 | this.email = email; 54 | } 55 | 56 | public int getPhoneNumber() { 57 | return phoneNumber; 58 | } 59 | 60 | public void setPhoneNumber(int phoneNumber) { 61 | this.phoneNumber = phoneNumber; 62 | } 63 | 64 | public double deposeFunds(double deposit) { 65 | this.balance = this.balance + deposit; 66 | System.out.println("You have succesfully made a deposit of " + deposit + ". The current balance at your bank account is " + balance + "."); 67 | return balance; 68 | } 69 | 70 | public double withdrawMoney(double withdrawalAmount) { 71 | if (withdrawalAmount > balance) { 72 | System.out.println("Insufficient funds for such an operation, " + customerName + ". You tried to withdraw " + withdrawalAmount + " but your balance is " + balance + "."); 73 | return balance; 74 | } else { 75 | this.balance = this.balance - withdrawalAmount; 76 | System.out.println("You have withdrawn " + withdrawalAmount + ". Your current balance is " + balance + "."); 77 | return balance; 78 | } 79 | } 80 | 81 | } 82 | -------------------------------------------------------------------------------- /OOP-1-classes-constructors-inheritance/class-constructors-challenge/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | 5 | BankAccount michalAccount = new BankAccount(23_112_313, 22, "Michal", "michal@email.com", 1_222); 6 | BankAccount ryszardAccount = new BankAccount("Ryszard", "rysiek@email.com", 22_112_512); 7 | 8 | System.out.println("Sir, here are some details of your client's profile:"); 9 | System.out.println("Customer's name: " + michalAccount.getCustomerName()); 10 | System.out.println("Customer's email: " + michalAccount.getEmail()); 11 | System.out.println("Customer's phone number: " + michalAccount.getPhoneNumber()); 12 | System.out.println("Customer's bank account number: " + michalAccount.getAccountNumber()); 13 | System.out.println("Customer's bank account balance: " + michalAccount.getBalance()); 14 | 15 | System.out.println("\n\n"); 16 | 17 | michalAccount.deposeFunds(15_000); 18 | michalAccount.deposeFunds(3_444); 19 | michalAccount.withdrawMoney(1_231_232); 20 | michalAccount.withdrawMoney(51_444); 21 | michalAccount.withdrawMoney(18_400); 22 | michalAccount.withdrawMoney(66); 23 | 24 | System.out.println("\n\n"); 25 | 26 | System.out.println("Sir, here are some details of your client's profile:"); 27 | System.out.println("Customer's name: " + ryszardAccount.getCustomerName()); 28 | System.out.println("Customer's email: " + ryszardAccount.getEmail()); 29 | System.out.println("Customer's phone number: " + ryszardAccount.getPhoneNumber()); 30 | System.out.println("Customer's bank account number: " + ryszardAccount.getAccountNumber()); 31 | System.out.println("Customer's bank account balance: " + ryszardAccount.getBalance()); 32 | 33 | System.out.println("\n\n"); 34 | 35 | ryszardAccount.withdrawMoney(30); 36 | ryszardAccount.withdrawMoney(20); 37 | 38 | System.out.println("\n\n"); 39 | 40 | VipCustomer vip1 = new VipCustomer(); 41 | VipCustomer vip2 = new VipCustomer("Anna", "anna@email.com"); 42 | VipCustomer vip3 = new VipCustomer("Jagna", 40_000, "jagna@email.com"); 43 | 44 | System.out.println(vip1.getName() + ", " + vip1.getEmailAddress() + ", " + vip1.getCreditLimit()); 45 | System.out.println(vip2.getName() + ", " + vip2.getEmailAddress() + ", " + vip2.getCreditLimit()); 46 | System.out.println(vip3.getName() + ", " + vip3.getEmailAddress() + ", " + vip3.getCreditLimit()); 47 | 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /OOP-1-classes-constructors-inheritance/class-constructors-challenge/VipCustomer.java: -------------------------------------------------------------------------------- 1 | public class VipCustomer { 2 | 3 | private String name; 4 | private int creditLimit; 5 | private String emailAddress; 6 | 7 | public String getName() { 8 | return name; 9 | } 10 | 11 | public int getCreditLimit() { 12 | return creditLimit; 13 | } 14 | 15 | public String getEmailAddress() { 16 | return emailAddress; 17 | } 18 | 19 | public VipCustomer() { 20 | this("Default name", 10_000, "default@email.com"); 21 | } 22 | 23 | public VipCustomer(String name, String emailAddress) { 24 | this(name, 50_000, emailAddress); 25 | } 26 | 27 | public VipCustomer(String name, int creditLimit, String emailAddress) { 28 | this.name = name; 29 | this.creditLimit = creditLimit; 30 | this.emailAddress = emailAddress; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /OOP-1-classes-constructors-inheritance/classes/Car.java: -------------------------------------------------------------------------------- 1 | public class Car { 2 | 3 | private int doors; 4 | private int wheels; 5 | public String model; 6 | private String engine; 7 | private String colour; 8 | 9 | public void setModel(String model) { 10 | String validModel = model.toLowerCase(); 11 | if (validModel.equals("carrera") || validModel.equals("commodore")) { // validation 12 | this.model = model; 13 | } else { 14 | this.model = "Unknown"; 15 | } 16 | } 17 | 18 | public String getModel() { 19 | return this.model; 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /OOP-1-classes-constructors-inheritance/classes/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | Car porsche = new Car(); 5 | Car holden = new Car(); 6 | porsche.setModel("Commodore"); 7 | System.out.println("Model is " + porsche.getModel()); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /OOP-1-classes-constructors-inheritance/inheritance-challenge-ver1/Car.java: -------------------------------------------------------------------------------- 1 | public class Car extends Vehicle { 2 | 3 | private int wheels; 4 | 5 | public Car(int productionYear, String model, String color, int doors, int gear, int wheels) { 6 | super(productionYear, model, color, doors, gear); 7 | this.wheels = wheels; 8 | } 9 | 10 | @Override 11 | public int moving(int speed) { 12 | if(speed > 150) { 13 | System.out.println("Driving at " + speed + " is very dangerous and prohibited in Poland. Please, decelerate your car!"); 14 | } else if(speed > 90){ 15 | System.out.println("At your current speed of " + speed + " you can drive only at highways."); 16 | } else if(speed > 50) { 17 | System.out.println("You are driving at speed of " + speed + ". You should decelerate if you are at build-up area."); 18 | } else { 19 | System.out.println("You are driving like a newbie. "); 20 | } 21 | return speed; 22 | } 23 | 24 | @Override 25 | public int changingGears(int gear) { 26 | if(gear > getGear()) { 27 | System.out.println("Gear changed to higher: " + gear); 28 | return gear; 29 | } else if(gear < getGear()) { 30 | System.out.println("Gear changed to lower: " + gear); 31 | return gear; 32 | } else { 33 | System.out.println("Gear remains at " + gear); 34 | } 35 | return gear; 36 | } 37 | } 38 | 39 | 40 | -------------------------------------------------------------------------------- /OOP-1-classes-constructors-inheritance/inheritance-challenge-ver1/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | 5 | Sedan mySedan = new Sedan(2012, "Croma", "Black", 4, 1, 4, 250); 6 | Car myCar = new Car(2018, "Linea", "White", 4, 1, 4); 7 | 8 | System.out.println(mySedan.getModel()); 9 | mySedan.changingGears(1); 10 | mySedan.moving(30); 11 | mySedan.changingGears(3); 12 | mySedan.moving(60); 13 | mySedan.changingGears(5); 14 | mySedan.moving(95); 15 | mySedan.changingGears(6); 16 | mySedan.moving(160); 17 | mySedan.changingGears(4); 18 | mySedan.moving(70); 19 | 20 | System.out.println(); 21 | 22 | System.out.println(myCar.getModel()); 23 | myCar.changingGears(1); 24 | myCar.moving(30); 25 | myCar.changingGears(2); 26 | myCar.moving(45); 27 | myCar.changingGears(4); 28 | myCar.moving(80); 29 | myCar.changingGears(2); 30 | myCar.moving(25); 31 | myCar.changingGears(5); 32 | myCar.moving(105); 33 | 34 | 35 | 36 | 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /OOP-1-classes-constructors-inheritance/inheritance-challenge-ver1/Sedan.java: -------------------------------------------------------------------------------- 1 | public class Sedan extends Car { 2 | 3 | private int trunk; 4 | 5 | 6 | public Sedan(int productionYear, String model, String color, int doors, int gear, int wheels, int trunk) { 7 | super(productionYear, model, color, doors, gear, wheels); 8 | this.trunk = trunk; 9 | } 10 | 11 | @Override 12 | public int moving(int speed) { 13 | if(speed > 90) { 14 | System.out.println("Driving at " + speed + ". You are not allowed to exceed 90 km/h, because you have a big trunk!"); 15 | } else if(speed > 50) { 16 | System.out.println("You are driving at speed of " + speed + ". You should decelerate if you are at build-up area."); 17 | } else { 18 | System.out.println("You are driving like a newbie. "); 19 | } 20 | return speed; 21 | } 22 | } 23 | 24 | -------------------------------------------------------------------------------- /OOP-1-classes-constructors-inheritance/inheritance-challenge-ver1/Vehicle.java: -------------------------------------------------------------------------------- 1 | public class Vehicle { 2 | 3 | private int productionYear; 4 | private String model; 5 | private String color; 6 | private int doors; 7 | private int gear; 8 | 9 | public Vehicle(int productionYear, String model, String color, int doors, int gear) { 10 | this.productionYear = productionYear; 11 | this.model = model; 12 | this.color = color; 13 | this.doors = doors; 14 | this.gear = gear; 15 | } 16 | 17 | public void handSteering() { 18 | 19 | } 20 | 21 | public int changingGears(int gear) { 22 | return gear; 23 | } 24 | 25 | public int moving(int speed) { 26 | return speed; 27 | } 28 | 29 | 30 | public int getProductionYear() { 31 | return productionYear; 32 | } 33 | 34 | public String getModel() { 35 | return model; 36 | } 37 | 38 | public String getColor() { 39 | return color; 40 | } 41 | 42 | public int getDoors() { 43 | return doors; 44 | } 45 | 46 | public int getGear() { 47 | return gear; 48 | } 49 | 50 | 51 | } 52 | -------------------------------------------------------------------------------- /OOP-1-classes-constructors-inheritance/inheritance-challenge-ver2/Car.java: -------------------------------------------------------------------------------- 1 | 2 | public class Car extends Vehicle { 3 | 4 | private int wheels; 5 | private int doors; 6 | private int gears; 7 | private boolean isManual; 8 | 9 | private int currentGear; 10 | 11 | public Car(String name, int wheels, int doors, int gears, boolean isManual) { 12 | super(name); 13 | this.wheels = wheels; 14 | this.doors = doors; 15 | this.gears = gears; 16 | this.isManual = isManual; 17 | this.currentGear = 1; 18 | } 19 | 20 | public void changeGear(int currentGear) { 21 | this.currentGear = currentGear; 22 | System.out.println("Current gear changed to " + this.currentGear + "."); 23 | } 24 | 25 | public void changeVelocity(int speed, int direction) { 26 | System.out.println("Car speed " + speed + ", direction: " + direction + "."); 27 | move(speed, direction); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /OOP-1-classes-constructors-inheritance/inheritance-challenge-ver2/Main.java: -------------------------------------------------------------------------------- 1 | 2 | public class Main { 3 | 4 | public static void main(String[] args) { 5 | Outlander myOutlander = new Outlander(36); 6 | myOutlander.steer(45); 7 | myOutlander.accelerate(30); 8 | myOutlander.accelerate(20); 9 | myOutlander.steer(90); 10 | myOutlander.accelerate(-33); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /OOP-1-classes-constructors-inheritance/inheritance-challenge-ver2/Outlander.java: -------------------------------------------------------------------------------- 1 | 2 | public class Outlander extends Car { 3 | 4 | private int roadServiceMonths; 5 | 6 | public Outlander(int roadService) { 7 | super("Outlander", 4, 5, 6, false); 8 | this.roadServiceMonths = roadService; 9 | } 10 | 11 | public void accelerate(int rate) { 12 | int newSpeed = getCurrentSpeed() + rate; 13 | if (newSpeed == 0) { 14 | stop(); 15 | changeGear(1); 16 | } else if (newSpeed > 0 && newSpeed <= 10) { 17 | changeGear(1); 18 | } else if (newSpeed > 10 && newSpeed <= 30) { 19 | changeGear(2); 20 | } else if (newSpeed > 30 && newSpeed <= 40) { 21 | changeGear(3); 22 | } else if (newSpeed > 40 && newSpeed <= 50) { 23 | changeGear(3); 24 | } else if (newSpeed > 50 && newSpeed <= 70) { 25 | changeGear(5); 26 | } else if (newSpeed > 70) { 27 | changeGear(6); 28 | } 29 | 30 | if(newSpeed > 0) { 31 | changeVelocity(newSpeed, getCurrentDirection()); 32 | } 33 | 34 | 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /OOP-1-classes-constructors-inheritance/inheritance-challenge-ver2/Vehicle.java: -------------------------------------------------------------------------------- 1 | 2 | public class Vehicle { 3 | private String name; 4 | 5 | private int currentSpeed; 6 | private int currentDirection; 7 | 8 | public Vehicle(String name) { 9 | this.name = name; 10 | // every vehicle starts at speed and direction of 0 11 | this.currentSpeed = 0; 12 | this.currentDirection = 0; 13 | } 14 | 15 | public void steer(int direction) { 16 | this.currentDirection = direction; 17 | System.out.println("Steering at " + currentDirection + " degrees."); 18 | } 19 | 20 | public void move(int speed, int direction) { 21 | currentDirection = direction; 22 | currentSpeed = speed; 23 | System.out.println("Vehicle moves at " + currentSpeed + " in direction " + currentDirection + "."); 24 | } 25 | 26 | public String getName() { 27 | return name; 28 | } 29 | 30 | public int getCurrentSpeed() { 31 | return currentSpeed; 32 | } 33 | 34 | public int getCurrentDirection() { 35 | return currentDirection; 36 | } 37 | 38 | public void stop() { 39 | this.currentDirection = 0; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /OOP-1-classes-constructors-inheritance/inheritance-training-project/Computer.java: -------------------------------------------------------------------------------- 1 | public class Computer { 2 | 3 | String brand; 4 | String model; 5 | String operationSystem; 6 | String mainboard; 7 | String diskDriveType; 8 | String graphicsCardModel; 9 | int cpu; 10 | int ram; 11 | int graphicsCardMemory; 12 | int diskDriveCapacity; 13 | int productionYear; 14 | int price; 15 | 16 | public Computer(String brand, String model, String operationSystem, String mainboard, String diskDriveType, String graphicsCardModel, int cpu, int ram, int graphicsCardMemory, int diskDriveCapacity, int productionYear, int price) { 17 | this.brand = brand; 18 | this.model = model; 19 | this.operationSystem = operationSystem; 20 | this.mainboard = mainboard; 21 | this.diskDriveType = diskDriveType; 22 | this.graphicsCardModel = graphicsCardModel; 23 | this.cpu = cpu; 24 | this.ram = ram; 25 | this.graphicsCardMemory = graphicsCardMemory; 26 | this.diskDriveCapacity = diskDriveCapacity; 27 | this.productionYear = productionYear; 28 | this.price = price; 29 | } 30 | 31 | public String getBrand() { 32 | return brand; 33 | } 34 | 35 | public String getModel() { 36 | return model; 37 | } 38 | 39 | public String getOperationSystem() { 40 | return operationSystem; 41 | } 42 | 43 | public String getMainboard() { 44 | return mainboard; 45 | } 46 | 47 | public String getDiskDriveType() { 48 | return diskDriveType; 49 | } 50 | 51 | public String getGraphicsCardModel() { 52 | return graphicsCardModel; 53 | } 54 | 55 | public int getCpu() { 56 | return cpu; 57 | } 58 | 59 | public int getRam() { 60 | return ram; 61 | } 62 | 63 | public int getGraphicsCardMemory() { 64 | return graphicsCardMemory; 65 | } 66 | 67 | public int getDiskDriveCapacity() { 68 | return diskDriveCapacity; 69 | } 70 | 71 | public int getProductionYear() { 72 | return productionYear; 73 | } 74 | 75 | public int getPrice() { 76 | return price; 77 | } 78 | 79 | public void printComputerInfo() { 80 | System.out.println("Brand: " + getBrand() + "\nModel: " + getModel() + "\nMainboard: " + getMainboard() + "\nOperation system: " + getOperationSystem() + "\nDisk drive: " + getDiskDriveType() + getDiskDriveCapacity() + "\nGraphics card: " + getGraphicsCardModel() + ", " + getGraphicsCardMemory() + "\nCPU: " + getCpu() + "\nRAM: " + getRam() + "\nProduction year: " + getProductionYear() + "\nPrice: " + getPrice()); 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /OOP-1-classes-constructors-inheritance/inheritance-training-project/Laptop.java: -------------------------------------------------------------------------------- 1 | public class Laptop extends Computer { 2 | 3 | private int weight; 4 | private String matrixType; 5 | private boolean multiTouchMatrix; 6 | private int batteryCapacity; 7 | 8 | public Laptop(String brand, String model, String operationSystem, String mainboard, String diskDriveType, String graphicsCardModel, int cpu, int ram, int graphicsCardMemory, int diskDriveCapacity, int productionYear, int price, int weight, String matrixType, boolean multiTouchMatrix, int batteryCapacity) { 9 | super(brand, model, operationSystem, mainboard, diskDriveType, graphicsCardModel, cpu, ram, graphicsCardMemory, diskDriveCapacity, productionYear, price); 10 | this.weight = weight; 11 | this.matrixType = matrixType; 12 | this.multiTouchMatrix = multiTouchMatrix; 13 | this.batteryCapacity = batteryCapacity; 14 | } 15 | 16 | @Override 17 | public void printComputerInfo() { 18 | super.printComputerInfo(); 19 | System.out.println("Weight: " + weight + "\nMatrix type: " + matrixType + "\nMulti-touch matrix: " + multiTouchMatrix + "\nBattery capacity: " + batteryCapacity); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /OOP-1-classes-constructors-inheritance/inheritance-training-project/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | 5 | Computer comp1 = new Computer("Dell", "XPS22", "Windows 10", "Intel", "SSD", "GeForce 1060", 3600, 2000, 4000, 128, 2009, 1150); 6 | Laptop laptop1 = new Laptop("Dell", "Precision", "Ubuntu", "Special20", "SSD", "NVIDA 900", 4500, 2322, 5000, 256, 2013, 2300, 8, "mat", true, 3200); 7 | 8 | comp1.printComputerInfo(); 9 | 10 | System.out.println("==========================="); 11 | 12 | laptop1.printComputerInfo(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /OOP-1-classes-constructors-inheritance/inheritance/Animal.java: -------------------------------------------------------------------------------- 1 | public class Animal { 2 | 3 | private String name; 4 | private int brain; 5 | private int body; 6 | private int size; 7 | private int weight; 8 | 9 | public Animal(String name, int brain, int body, int size, int weight) { 10 | this.name = name; 11 | this.brain = brain; 12 | this.body = body; 13 | this.size = size; 14 | this.weight = weight; 15 | } 16 | 17 | public void eat() { 18 | System.out.println("Animal eats!"); 19 | } 20 | public void move(int speed) { 21 | System.out.println("Animal is moving at speed " + speed); 22 | } 23 | 24 | 25 | public String getName() { 26 | return name; 27 | } 28 | 29 | public int getBrain() { 30 | return brain; 31 | } 32 | 33 | public int getBody() { 34 | return body; 35 | } 36 | 37 | public int getSize() { 38 | return size; 39 | } 40 | 41 | public int getWeight() { 42 | return weight; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /OOP-1-classes-constructors-inheritance/inheritance/Dog.java: -------------------------------------------------------------------------------- 1 | public class Dog extends Animal { 2 | 3 | private int eyes; 4 | private int legs; 5 | private int tail; 6 | private int teeth; 7 | private String coat; 8 | 9 | public Dog(String name, int size, int weight, int eyes, int legs, int tail, int teeth, String coat) { 10 | super(name, 1, 1, size, weight); 11 | this.eyes = eyes; 12 | this.legs = legs; 13 | this.tail = tail; 14 | this.teeth = teeth; 15 | this.coat = coat; 16 | 17 | } 18 | 19 | private void chew() { 20 | System.out.println("Dog chews!"); 21 | } 22 | 23 | @Override 24 | public void eat() { 25 | chew(); 26 | } 27 | 28 | public void walk() { 29 | System.out.println("Dog walks!"); 30 | move(5); 31 | } 32 | 33 | public void run() { 34 | System.out.println("Dog runs!"); 35 | move(10); 36 | } 37 | 38 | public void moveLegs(int speed) { 39 | System.out.println("Dog is moving legs"); 40 | } 41 | 42 | @Override 43 | public void move(int speed) { 44 | moveLegs(5); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /OOP-1-classes-constructors-inheritance/inheritance/Fish.java: -------------------------------------------------------------------------------- 1 | public class Fish extends Animal { 2 | 3 | private int gills; 4 | private int eyes; 5 | private int fins; 6 | 7 | public Fish(String name, int size, int weight, int gills, int eyes, int fins) { 8 | super(name, 1, 1, size, weight); 9 | this.gills = gills; 10 | this.eyes = eyes; 11 | this.fins = fins; 12 | } 13 | 14 | private void rest() { 15 | 16 | } 17 | 18 | private void moveMuscles() { 19 | 20 | } 21 | private void swim(int speed) { 22 | moveMuscles(); 23 | moveBackFin(); 24 | super.move(speed); 25 | } 26 | 27 | private void moveBackFin() { 28 | 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /OOP-1-classes-constructors-inheritance/inheritance/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | Animal animal = new Animal("Animal", 1, 1, 5, 5); 5 | 6 | Dog dog = new Dog("Yorkie", 8, 20, 2, 4, 1, 20, "long silky"); 7 | 8 | dog.run(); 9 | 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /OOP-2-composition-encapsulation-polymorphism/composition-challenge/Bathroom.java: -------------------------------------------------------------------------------- 1 | public class Bathroom { 2 | private String bath; 3 | private String sink; 4 | private String washingMachine; 5 | private String basket; 6 | private String mirror; 7 | 8 | public Bathroom(String bath, String sink, String washingMachine, String basket, String mirror) { 9 | this.bath = bath; 10 | this.sink = sink; 11 | this.washingMachine = washingMachine; 12 | this.basket = basket; 13 | this.mirror = mirror; 14 | } 15 | 16 | public void takebath() { 17 | System.out.println("You've taken a bath."); 18 | } 19 | 20 | public void washHands() { 21 | System.out.println("You've washed your hands in the sink."); 22 | } 23 | 24 | public void doTheLaundry() { 25 | System.out.println("You've done the laundry."); 26 | } 27 | 28 | public String getBath() { 29 | return bath; 30 | } 31 | 32 | public String getSink() { 33 | return sink; 34 | } 35 | 36 | public String getWashingMachine() { 37 | return washingMachine; 38 | } 39 | 40 | public String getBasket() { 41 | return basket; 42 | } 43 | 44 | public String getMirror() { 45 | return mirror; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /OOP-2-composition-encapsulation-polymorphism/composition-challenge/Bed.java: -------------------------------------------------------------------------------- 1 | public class Bed { 2 | 3 | private String location; 4 | 5 | public Bed(String location) { 6 | this.location = location; 7 | } 8 | 9 | public void goToBed() { 10 | System.out.println("You went to bed."); 11 | } 12 | 13 | public String getLocation() { 14 | return location; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /OOP-2-composition-encapsulation-polymorphism/composition-challenge/House.java: -------------------------------------------------------------------------------- 1 | public class House { 2 | private Room room; 3 | private Kitchen kitchen; 4 | private Bathroom bathroom; 5 | private String address; 6 | 7 | public House(Room room, Kitchen kitchen, Bathroom bathroom, String address) { 8 | this.room = room; 9 | this.kitchen = kitchen; 10 | this.bathroom = bathroom; 11 | this.address = address; 12 | } 13 | 14 | public void enterTheHouse() { 15 | System.out.println("You've entered the house."); 16 | } 17 | 18 | public void gotoTheRoom() { 19 | System.out.println("You've entered your lovely room."); 20 | } 21 | 22 | public void goToTheBathroom() { 23 | System.out.println("You've entered your lovely bathroom."); 24 | } 25 | 26 | 27 | public Room getRoom() { 28 | return room; 29 | } 30 | 31 | public Kitchen getKitchen() { 32 | return kitchen; 33 | } 34 | 35 | public Bathroom getBathroom() { 36 | return bathroom; 37 | } 38 | 39 | public String getAddress() { 40 | return address; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /OOP-2-composition-encapsulation-polymorphism/composition-challenge/Kitchen.java: -------------------------------------------------------------------------------- 1 | public class Kitchen { 2 | private String cooker; 3 | private String refrigerator; 4 | private String table; 5 | private String oven; 6 | private String sink; 7 | private String dishwasher; 8 | 9 | public Kitchen(String cooker, String refrigerator, String table, String oven, String sink, String dishwasher) { 10 | this.cooker = cooker; 11 | this.refrigerator = refrigerator; 12 | this.table = table; 13 | this.oven = oven; 14 | this.sink = sink; 15 | this.dishwasher = dishwasher; 16 | } 17 | 18 | public String getCooker() { 19 | return cooker; 20 | } 21 | 22 | public String getRefrigerator() { 23 | return refrigerator; 24 | } 25 | 26 | public String getTable() { 27 | return table; 28 | } 29 | 30 | public String getOven() { 31 | return oven; 32 | } 33 | 34 | public String getSink() { 35 | return sink; 36 | } 37 | 38 | public String getDishwasher() { 39 | return dishwasher; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /OOP-2-composition-encapsulation-polymorphism/composition-challenge/Lamp.java: -------------------------------------------------------------------------------- 1 | public class Lamp { 2 | 3 | private String bulb; 4 | private boolean turned = false; 5 | 6 | public void turnOnOfftheLamp(boolean turned) { 7 | this.turned = turned; 8 | if (turned) { 9 | System.out.println("You've turned the lamp ON."); 10 | } else { 11 | System.out.println("You've turned the lamp OFF."); 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /OOP-2-composition-encapsulation-polymorphism/composition-challenge/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | Bed theBed = new Bed("in the corner"); 5 | Lamp theLamp = new Lamp(); 6 | Room myRoom = new Room(theBed, "LittleReader", theLamp, "IKEA wardrobe"); 7 | Kitchen myKitchen = new Kitchen("Mastercook", "Beko", "IKEA table", "Zelmer", "Oval sink", "Indesit Dishwasher XC200"); 8 | Bathroom myBathroom = new Bathroom("BigBath", "Square-sink", "Łucznik 7KG", "Auchan basket", "Your Shadow RX350"); 9 | House myHouse = new House(myRoom, myKitchen, myBathroom, "The Best Address"); 10 | 11 | myHouse.enterTheHouse(); 12 | myHouse.gotoTheRoom(); 13 | myRoom.readABook(); 14 | myHouse.goToTheBathroom(); 15 | myHouse.getBathroom().doTheLaundry(); 16 | myHouse.getRoom().getLamp().turnOnOfftheLamp(false); 17 | myHouse.getRoom().gotoSleep(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /OOP-2-composition-encapsulation-polymorphism/composition-challenge/Room.java: -------------------------------------------------------------------------------- 1 | public class Room { 2 | private Bed bed; 3 | private String nightStand; 4 | private Lamp lamp; 5 | private String wardrobe; 6 | 7 | public Room(Bed bed, String nightStand, Lamp lamp, String wardrobe) { 8 | this.bed = bed; 9 | this.nightStand = nightStand; 10 | this.lamp = lamp; 11 | this.wardrobe = wardrobe; 12 | } 13 | 14 | public void gotoSleep() { 15 | bed.goToBed(); 16 | } 17 | 18 | public void readABook() { 19 | lamp.turnOnOfftheLamp(true); 20 | System.out.println("You've read a very interesting book."); 21 | } 22 | 23 | public Bed getBed() { 24 | return bed; 25 | } 26 | 27 | public String getNightStand() { 28 | return nightStand; 29 | } 30 | 31 | public Lamp getLamp() { 32 | return lamp; 33 | } 34 | 35 | public String getWardrobe() { 36 | return wardrobe; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /OOP-2-composition-encapsulation-polymorphism/composition/Car.java: -------------------------------------------------------------------------------- 1 | public class Car extends Vehicle { 2 | 3 | private int doors; 4 | private int engineCapacity; 5 | 6 | public Car(String name, int doors, int engineCapacity) { 7 | super(name); 8 | this.doors = doors; 9 | this.engineCapacity = engineCapacity; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /OOP-2-composition-encapsulation-polymorphism/composition/Case.java: -------------------------------------------------------------------------------- 1 | public class Case { 2 | private String model; 3 | private String manufacturer; 4 | private String powersSupply; 5 | private Dimensions dimensions; 6 | 7 | public Case(String model, String manufacturer, String powersSupply, Dimensions dimensions) { 8 | this.model = model; 9 | this.manufacturer = manufacturer; 10 | this.powersSupply = powersSupply; 11 | this.dimensions = dimensions; 12 | } 13 | 14 | public void pressPowerButton() { 15 | System.out.println("Power button pressed."); 16 | } 17 | 18 | public String getModel() { 19 | return model; 20 | } 21 | 22 | public String getManufacturer() { 23 | return manufacturer; 24 | } 25 | 26 | public String getPowersSupply() { 27 | return powersSupply; 28 | } 29 | 30 | public Dimensions getDimensions() { 31 | return dimensions; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /OOP-2-composition-encapsulation-polymorphism/composition/Dimensions.java: -------------------------------------------------------------------------------- 1 | public class Dimensions { 2 | 3 | private int width; 4 | private int height; 5 | private int depth; 6 | 7 | public Dimensions(int width, int height, int depth) { 8 | this.width = width; 9 | this.height = height; 10 | this.depth = depth; 11 | } 12 | 13 | public int getWidth() { 14 | return width; 15 | } 16 | 17 | public int getHeight() { 18 | return height; 19 | } 20 | 21 | public int getDepth() { 22 | return depth; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /OOP-2-composition-encapsulation-polymorphism/composition/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | Dimensions dimensions = new Dimensions(20, 20, 5); 5 | Case theCase = new Case("220B", "Dell", "240", dimensions); 6 | 7 | Monitor theMonitor = new Monitor("27inch Beast", "Acer", 27, new Resolution(2540, 1440)); 8 | 9 | Motherboard theMotherboard = new Motherboard("BJ-200", "Asus", 4, 6, "v2.44"); 10 | 11 | PC thePC = new PC(theCase, theMonitor, theMotherboard); 12 | thePC.powerUp(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /OOP-2-composition-encapsulation-polymorphism/composition/Monitor.java: -------------------------------------------------------------------------------- 1 | public class Monitor { 2 | 3 | private String model; 4 | private String manufacturer; 5 | private int size; 6 | private Resolution nativeResolution; 7 | 8 | public Monitor(String model, String manufacturer, int size, Resolution nativeResolution) { 9 | this.model = model; 10 | this.manufacturer = manufacturer; 11 | this.size = size; 12 | this.nativeResolution = nativeResolution; 13 | } 14 | 15 | public void drawPixelAt(int x, int y, String color) { 16 | System.out.println("Drawing pixel at " + x + ", " + y + " in colour " + color); 17 | } 18 | 19 | public String getModel() { 20 | return model; 21 | } 22 | 23 | public String getManufacturer() { 24 | return manufacturer; 25 | } 26 | 27 | public int getSize() { 28 | return size; 29 | } 30 | 31 | public Resolution getNativeResolution() { 32 | return nativeResolution; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /OOP-2-composition-encapsulation-polymorphism/composition/Motherboard.java: -------------------------------------------------------------------------------- 1 | public class Motherboard { 2 | 3 | private String model; 4 | private String manufacturer; 5 | private int ramSlots; 6 | private int cardSlots; 7 | private String bios; 8 | 9 | public Motherboard(String model, String manufacturer, int ramSlots, int cardSlots, String bios) { 10 | this.model = model; 11 | this.manufacturer = manufacturer; 12 | this.ramSlots = ramSlots; 13 | this.cardSlots = cardSlots; 14 | this.bios = bios; 15 | } 16 | 17 | public void loadProgram(String programName) { 18 | System.out.println("Program " + programName + " is now loading..."); 19 | } 20 | 21 | public String getModel() { 22 | return model; 23 | } 24 | 25 | public String getManufacturer() { 26 | return manufacturer; 27 | } 28 | 29 | public int getRamSlots() { 30 | return ramSlots; 31 | } 32 | 33 | public int getCardSlots() { 34 | return cardSlots; 35 | } 36 | 37 | public String getBios() { 38 | return bios; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /OOP-2-composition-encapsulation-polymorphism/composition/PC.java: -------------------------------------------------------------------------------- 1 | public class PC { 2 | private Case theCase; 3 | private Monitor monitor; 4 | private Motherboard motherboard; 5 | 6 | public PC(Case theCase, Monitor monitor, Motherboard motherboard) { 7 | this.theCase = theCase; 8 | this.monitor = monitor; 9 | this.motherboard = motherboard; 10 | } 11 | 12 | public void powerUp() { 13 | theCase.pressPowerButton(); 14 | drawLogo(); 15 | } 16 | 17 | private void drawLogo() { 18 | // Fancy graphics 19 | monitor.drawPixelAt(1200, 50, "yellow"); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /OOP-2-composition-encapsulation-polymorphism/composition/Resolution.java: -------------------------------------------------------------------------------- 1 | public class Resolution { 2 | 3 | private int width; 4 | private int height; 5 | 6 | public Resolution(int width, int height) { 7 | this.width = width; 8 | this.height = height; 9 | } 10 | 11 | public int getWidth() { 12 | return width; 13 | } 14 | 15 | public int getHeight() { 16 | return height; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /OOP-2-composition-encapsulation-polymorphism/composition/Vehicle.java: -------------------------------------------------------------------------------- 1 | public class Vehicle { 2 | 3 | private String name; 4 | 5 | public Vehicle(String name) { 6 | this.name = name; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /OOP-2-composition-encapsulation-polymorphism/encapsulation-challenge/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | Printer myPrinter = new Printer(50, true); 5 | System.out.println("Initial page count is " + myPrinter.getNumberOfPrintedPages()); 6 | int pagesPrinted = myPrinter.printPages(4); 7 | System.out.println("Pages printed was " + pagesPrinted + " new total print count for printer = " + myPrinter.getNumberOfPrintedPages() + "."); 8 | pagesPrinted = myPrinter.printPages(2); 9 | System.out.println("Pages printed was " + pagesPrinted + " new total print count for printer = " + myPrinter.getNumberOfPrintedPages() + "."); 10 | 11 | System.out.println("\nPrinter without duplex: \n"); 12 | 13 | Printer mySecondPrinter = new Printer(50, false); 14 | System.out.println("Initial page count is " + mySecondPrinter.getNumberOfPrintedPages()); 15 | pagesPrinted = mySecondPrinter.printPages(4); 16 | System.out.println("Pages printed was " + pagesPrinted + " new total print count for printer = " + mySecondPrinter.getNumberOfPrintedPages() + "."); 17 | pagesPrinted = mySecondPrinter.printPages(2); 18 | System.out.println("Pages printed was " + pagesPrinted + " new total print count for printer = " + mySecondPrinter.getNumberOfPrintedPages() + "."); 19 | 20 | 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /OOP-2-composition-encapsulation-polymorphism/encapsulation-challenge/Printer.java: -------------------------------------------------------------------------------- 1 | public class Printer { 2 | private int tonerLevel; 3 | private int numberOfPrintedPages; 4 | private boolean duplex; 5 | 6 | public Printer(int tonerLevel, boolean duplex) { 7 | if (tonerLevel > -1 && tonerLevel <= 100) { 8 | this.tonerLevel = tonerLevel; 9 | } else { 10 | this.tonerLevel = -1; 11 | } 12 | this.duplex = duplex; 13 | this.numberOfPrintedPages = 0; 14 | } 15 | 16 | public int addToner(int tonerAmount) { 17 | if (tonerAmount > 0 && tonerAmount <= 100) { 18 | if (this.tonerLevel + tonerAmount > 100) { 19 | return -1; 20 | } 21 | this.tonerLevel += tonerLevel; 22 | return this.tonerLevel; 23 | } else { 24 | return -1; 25 | } 26 | } 27 | 28 | public int printPages(int pages) { 29 | int pagesToPrint = pages; 30 | if (this.duplex) { 31 | pagesToPrint = (pages / 2) + (pages % 2); 32 | System.out.println("Printing in duplex mode."); 33 | } 34 | this.numberOfPrintedPages += pagesToPrint; 35 | return pagesToPrint; 36 | } 37 | 38 | public int getNumberOfPrintedPages() { 39 | return numberOfPrintedPages; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /OOP-2-composition-encapsulation-polymorphism/encapsulation/EnhancedPlayer.java: -------------------------------------------------------------------------------- 1 | public class EnhancedPlayer { 2 | private String name; 3 | private int hitPoints = 100; 4 | private String weapon; 5 | 6 | public EnhancedPlayer(String name, int health, String weapon) { 7 | this.name = name; 8 | // validation of the health value 9 | if (health > 0 && health <= 200){ 10 | this.hitPoints = health; 11 | } 12 | this.weapon = weapon; 13 | } 14 | 15 | public void loseHealth(int damage) { 16 | this.hitPoints = this.hitPoints - damage; 17 | if (this.hitPoints <= 0) { 18 | System.out.println("Player knocked out."); 19 | } 20 | } 21 | 22 | public int getHealth() { 23 | return hitPoints; 24 | 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /OOP-2-composition-encapsulation-polymorphism/encapsulation/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | 5 | EnhancedPlayer player2 = new EnhancedPlayer("Michal", 50, "Sword"); 6 | System.out.println("Initial health is " + player2.getHealth()); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /OOP-2-composition-encapsulation-polymorphism/oop-master-challenge-by-tim/DeluxeBurger.java: -------------------------------------------------------------------------------- 1 | public class DeluxeBurger extends Hamburger { 2 | 3 | public DeluxeBurger() { 4 | super("Deluxe", "Sausage & Bacon", 14.54, "Whire"); 5 | super.addHamburgerAdditon1("Chips", 2.75); 6 | super.addHamburgerAdditon2("Drink", 1.818); 7 | } 8 | 9 | @Override 10 | public void addHamburgerAdditon1(String name, double price) { 11 | System.out.println("Cannot add additional item to a Deluxe Burger"); 12 | } 13 | 14 | @Override 15 | public void addHamburgerAdditon2(String name, double price) { 16 | System.out.println("Cannot add additional item to a Deluxe Burger"); 17 | } 18 | 19 | @Override 20 | public void addHamburgerAdditon3(String name, double price) { 21 | System.out.println("Cannot add additional item to a Deluxe Burger"); 22 | } 23 | 24 | @Override 25 | public void addHamburgerAdditon4(String name, double price) { 26 | System.out.println("Cannot add additional item to a Deluxe Burger"); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /OOP-2-composition-encapsulation-polymorphism/oop-master-challenge-by-tim/Hamburger.java: -------------------------------------------------------------------------------- 1 | public class Hamburger { 2 | 3 | private String name; 4 | private String meat; 5 | private double price; 6 | private String breadRollType; 7 | 8 | private String addition1Name; 9 | private double addition1Price; 10 | 11 | private String addition2Name; 12 | private double addition2Price; 13 | 14 | private String addition3Name; 15 | private double addition3Price; 16 | 17 | private String addition4Name; 18 | private double addition4Price; 19 | 20 | public Hamburger(String name, String meat, double price, String breadRollType) { 21 | this.name = name; 22 | this.meat = meat; 23 | this.price = price; 24 | this.breadRollType = breadRollType; 25 | } 26 | 27 | public void addHamburgerAdditon1(String name, double price) { 28 | this.addition1Name = name; 29 | this.addition1Price = price; 30 | } 31 | 32 | public void addHamburgerAdditon2(String name, double price) { 33 | this.addition2Name = name; 34 | this.addition2Price = price; 35 | } 36 | 37 | public void addHamburgerAdditon3(String name, double price) { 38 | this.addition3Name = name; 39 | this.addition3Price = price; 40 | } 41 | 42 | public void addHamburgerAdditon4(String name, double price) { 43 | this.addition4Name = name; 44 | this.addition4Price = price; 45 | } 46 | 47 | public double itemizeHamburger() { 48 | double hamburgerPrice = this.price; 49 | System.out.println(this.name + " hamburger " + "on a " + this.breadRollType + " roll " 50 | + "with " + this.meat + ", price is " + this.price); 51 | if(this.addition1Name != null) { 52 | hamburgerPrice += this.addition1Price; 53 | System.out.println("Added " + this.addition1Name + " for an extra " + this.addition1Price); 54 | } 55 | if(this.addition2Name != null) { 56 | hamburgerPrice += this.addition2Price; 57 | System.out.println("Added " + this.addition2Name + " for an extra " + this.addition2Price); 58 | } 59 | if(this.addition3Name != null) { 60 | hamburgerPrice += this.addition3Price; 61 | System.out.println("Added " + this.addition3Name + " for an extra " + this.addition3Price); 62 | } 63 | if(this.addition4Name != null) { 64 | hamburgerPrice += this.addition4Price; 65 | System.out.println("Added " + this.addition4Name + " for an extra " + this.addition4Price); 66 | } 67 | return hamburgerPrice; 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /OOP-2-composition-encapsulation-polymorphism/oop-master-challenge-by-tim/HealthyBurger.java: -------------------------------------------------------------------------------- 1 | public class HealthyBurger extends Hamburger { 2 | 3 | private String healthyExtra1Name; 4 | private double healthyExtra1Price; 5 | 6 | private String healthyExtra2Name; 7 | private double healthyExtra2Price; 8 | 9 | public HealthyBurger(String meat, double price) { 10 | super("Healthy", meat, price, "Brown rye"); 11 | } 12 | 13 | public void addHealthAddition1(String name, double price) { 14 | this.healthyExtra1Name = name; 15 | this.healthyExtra1Price = price; 16 | } 17 | 18 | public void addHealthAddition2(String name, double price) { 19 | this.healthyExtra2Name = name; 20 | this.healthyExtra2Price = price; 21 | } 22 | 23 | @Override 24 | public double itemizeHamburger() { 25 | double hamburgerPrice = super.itemizeHamburger(); 26 | if(this.healthyExtra1Name != null) { 27 | hamburgerPrice += this.healthyExtra1Price; 28 | System.out.println("Added " + this.healthyExtra1Name + " for an extra " + this.healthyExtra1Price); 29 | } 30 | if(this.healthyExtra2Name != null) { 31 | hamburgerPrice += this.healthyExtra2Price; 32 | System.out.println("Added " + this.healthyExtra2Name + " for an extra " + this.healthyExtra2Price); 33 | } 34 | return hamburgerPrice; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /OOP-2-composition-encapsulation-polymorphism/oop-master-challenge-by-tim/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | 5 | Hamburger hamburger = new Hamburger("Basic", "Sausage", 3.56, "White"); 6 | 7 | double price = hamburger.itemizeHamburger(); 8 | 9 | hamburger.addHamburgerAdditon1("Tomato", 0.27); 10 | hamburger.addHamburgerAdditon2("Lettuce", 0.75); 11 | hamburger.addHamburgerAdditon3("Cheese", 1.13); 12 | 13 | System.out.println("Total Burger price is " + hamburger.itemizeHamburger()); 14 | 15 | HealthyBurger healthyBurger = new HealthyBurger("Bacon", 5.67); 16 | healthyBurger.addHamburgerAdditon1("Egg", 5.43); 17 | healthyBurger.addHealthAddition1("Lentils", 3.41); 18 | System.out.println("Total Healthy Burger price is " + healthyBurger.itemizeHamburger()); 19 | 20 | DeluxeBurger db = new DeluxeBurger(); 21 | db.itemizeHamburger(); 22 | db.addHamburgerAdditon1("Cucumber", 1.12); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /OOP-2-composition-encapsulation-polymorphism/oop-master-challenge/Addition.java: -------------------------------------------------------------------------------- 1 | package com.michal; 2 | 3 | public class Addition { 4 | 5 | private String name; 6 | private double price; 7 | 8 | public Addition(String name, double price) { 9 | this.name = name; 10 | this.price = price; 11 | } 12 | 13 | public String getName() { 14 | return name; 15 | } 16 | 17 | public double getPrice() { 18 | return price; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /OOP-2-composition-encapsulation-polymorphism/oop-master-challenge/DeluxeHamburger.java: -------------------------------------------------------------------------------- 1 | package com.michal; 2 | 3 | public class DeluxeHamburger extends Hamburger { 4 | 5 | private Addition chips; 6 | private Addition drink; 7 | 8 | public DeluxeHamburger(String meat, RollType rollType, double standardPrice, Addition chips, Addition drink) { 9 | super(meat, rollType, standardPrice); 10 | this.chips = chips; 11 | this.drink = drink; 12 | } 13 | 14 | @Override 15 | public void showTheFinalPrice() { 16 | System.out.println("The final price of the Deluxe burger (base: " + getStandardPrice() + " PLN), which comes with " + this.chips.getName() + " ("+ this.chips.getPrice() + ") and " + this.drink.getName() + " (" + this.drink.getPrice() + ") as additions is " + (getStandardPrice() + chips.getPrice() + drink.getPrice()) + " PLN."); 17 | } 18 | 19 | @Override 20 | public void showTheStandardPrice() { 21 | System.out.println("The standard price of the Deluxe burger (with no additions) is: " + getStandardPrice() + " PLN."); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /OOP-2-composition-encapsulation-polymorphism/oop-master-challenge/Hamburger.java: -------------------------------------------------------------------------------- 1 | package com.michal; 2 | 3 | public class Hamburger { 4 | 5 | private String meat; 6 | private RollType breadRoll; 7 | private double standardPrice; 8 | private double finalPrice; 9 | private Addition firstAddition; 10 | private Addition secondAddition; 11 | private Addition thirdAddition; 12 | private Addition fourthAddition; 13 | private int additionsQuantity; 14 | 15 | public Hamburger(String meat, RollType rollType, double standardPrice) { 16 | this.meat = meat; 17 | this.breadRoll = rollType; 18 | this.standardPrice = standardPrice; 19 | } 20 | 21 | public double addAddition(Addition firstAddition) { 22 | finalPrice = this.standardPrice + firstAddition.getPrice(); 23 | this.firstAddition = firstAddition; 24 | additionsQuantity = 1; 25 | return finalPrice; 26 | } 27 | 28 | public double addAddition(Addition firstAddition, Addition secondAddition) { 29 | finalPrice = this.standardPrice + firstAddition.getPrice() + secondAddition.getPrice(); 30 | this.firstAddition = firstAddition; 31 | this.secondAddition = secondAddition; 32 | additionsQuantity = 2; 33 | return finalPrice; 34 | } 35 | 36 | public double addAddition(Addition firstAddition, Addition secondAddition, Addition thirdAddition) { 37 | finalPrice = this.standardPrice + firstAddition.getPrice() + secondAddition.getPrice() + thirdAddition.getPrice(); 38 | this.firstAddition = firstAddition; 39 | this.secondAddition = secondAddition; 40 | this.thirdAddition = thirdAddition; 41 | additionsQuantity = 3; 42 | return finalPrice; 43 | } 44 | 45 | public double addAddition(Addition firstAddition, Addition secondAddition, Addition thirdAddition, Addition fourthAddition) { 46 | finalPrice = this.standardPrice + firstAddition.getPrice() + secondAddition.getPrice() + thirdAddition.getPrice() + fourthAddition.getPrice(); 47 | this.firstAddition = firstAddition; 48 | this.secondAddition = secondAddition; 49 | this.thirdAddition = thirdAddition; 50 | this.fourthAddition = fourthAddition; 51 | additionsQuantity = 4; 52 | return finalPrice; 53 | } 54 | 55 | public void showTheStandardPrice() { 56 | System.out.println("The standard price of the burger (with no additions) is: " + getStandardPrice() + " PLN."); 57 | } 58 | 59 | public void showTheFinalPrice() { 60 | if (finalPrice != getStandardPrice()) { 61 | switch (additionsQuantity) { 62 | case 1: 63 | System.out.println("The final price of the burger (base: " + getStandardPrice() + " PLN) with following additions: " + firstAddition.getName() + " (" + firstAddition.getPrice() + "), is " + finalPrice + " PLN."); 64 | break; 65 | case 2: 66 | System.out.println("The final price of the burger (base: " + getStandardPrice() + " PLN) with following additions: " + firstAddition.getName() + " (" + firstAddition.getPrice() + "), " + secondAddition.getName() + " (" + secondAddition.getPrice() + "), is " + finalPrice + " PLN."); 67 | break; 68 | case 3: 69 | System.out.println("The final price of the burger (base: " + getStandardPrice() + " PLN) with following additions: " + firstAddition.getName() + " (" + firstAddition.getPrice() + "), " + secondAddition.getName() + " (" + secondAddition.getPrice() + "), " + thirdAddition.getName() + " (" + thirdAddition.getPrice() + "), is " + finalPrice + " PLN."); 70 | break; 71 | case 4: 72 | System.out.println("The final price of the burger (base: " + getStandardPrice() + " PLN) with following additions: " + firstAddition.getName() + " (" + firstAddition.getPrice() + "), " + secondAddition.getName() + " (" + secondAddition.getPrice() + "), " + thirdAddition.getName() + " (" + thirdAddition.getPrice() + "), " + fourthAddition.getName() + " (" + fourthAddition.getPrice() + "), is " + finalPrice + " PLN."); 73 | break; 74 | } 75 | } else { 76 | System.out.println("The final price of the burger is " + getStandardPrice() + " PLN, since you've selected no additions."); 77 | 78 | } 79 | } 80 | 81 | 82 | public double getStandardPrice() { 83 | return standardPrice; 84 | } 85 | 86 | public int getAdditionsQuantity() { 87 | return additionsQuantity; 88 | } 89 | 90 | public void setAdditionsQuantity(int additionsQuantity) { 91 | this.additionsQuantity = additionsQuantity; 92 | } 93 | 94 | public Addition getFirstAddition() { 95 | return firstAddition; 96 | } 97 | 98 | 99 | public Addition getSecondAddition() { 100 | return secondAddition; 101 | } 102 | 103 | 104 | public Addition getThirdAddition() { 105 | return thirdAddition; 106 | } 107 | 108 | 109 | public Addition getFourthAddition() { 110 | return fourthAddition; 111 | } 112 | 113 | 114 | public double getFinalPrice() { 115 | return finalPrice; 116 | } 117 | 118 | public void setFirstAddition(Addition firstAddition) { 119 | this.firstAddition = firstAddition; 120 | } 121 | 122 | public void setSecondAddition(Addition secondAddition) { 123 | this.secondAddition = secondAddition; 124 | } 125 | 126 | public void setThirdAddition(Addition thirdAddition) { 127 | this.thirdAddition = thirdAddition; 128 | } 129 | 130 | public void setFourthAddition(Addition fourthAddition) { 131 | this.fourthAddition = fourthAddition; 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /OOP-2-composition-encapsulation-polymorphism/oop-master-challenge/HealthyBurger.java: -------------------------------------------------------------------------------- 1 | package com.michal; 2 | 3 | public class HealthyBurger extends Hamburger { 4 | 5 | private Addition fifthAddition; 6 | private Addition sixthAddition; 7 | private double finalPrice; 8 | 9 | public HealthyBurger(String meat, RollType rollType, double standardPrice) { 10 | super(meat, rollType, standardPrice); 11 | } 12 | 13 | public double addAddition(Addition firstAddition, Addition secondAddition, Addition thirdAddition, Addition fourthAddition, Addition fifthAddition) { 14 | setFirstAddition(firstAddition); 15 | setSecondAddition(secondAddition); 16 | setThirdAddition(thirdAddition); 17 | setFourthAddition(fourthAddition); 18 | this.fifthAddition = fifthAddition; 19 | this.finalPrice = getStandardPrice() + firstAddition.getPrice() + secondAddition.getPrice() + thirdAddition.getPrice() + fourthAddition.getPrice() + fifthAddition.getPrice(); 20 | setAdditionsQuantity(5); 21 | return this.finalPrice; 22 | } 23 | 24 | public double addAddition(Addition firstAddition, Addition secondAddition, Addition thirdAddition, Addition fourthAddition, Addition fifthAddition, Addition sixthAddition) { 25 | setFirstAddition(firstAddition); 26 | setSecondAddition(secondAddition); 27 | setThirdAddition(thirdAddition); 28 | setFourthAddition(fourthAddition); 29 | this.fifthAddition = fifthAddition; 30 | this.sixthAddition = sixthAddition; 31 | this.finalPrice = getStandardPrice() + firstAddition.getPrice() + secondAddition.getPrice() + thirdAddition.getPrice() + fourthAddition.getPrice() + fifthAddition.getPrice() + sixthAddition.getPrice(); 32 | setAdditionsQuantity(6); 33 | return this.finalPrice; 34 | } 35 | 36 | @Override 37 | public void showTheStandardPrice() { 38 | System.out.println("The standard price of the Healthy Burger (with no additions) is: " + getStandardPrice() + " PLN."); 39 | } 40 | 41 | public void showTheFinalPrice() { 42 | if (finalPrice != getStandardPrice()) { 43 | switch (getAdditionsQuantity()) { 44 | case 1: 45 | System.out.println("The final price of the Healthy Burger (base: " + getStandardPrice() + " PLN) with following additions: " + getFirstAddition().getName() + " (" + getFirstAddition().getPrice() + "), is " + getFinalPrice() + " PLN."); 46 | break; 47 | case 2: 48 | System.out.println("The final price of the Healthy Burger (base: " + getStandardPrice() + " PLN) with following additions: " + getFirstAddition().getName() + " (" + getFirstAddition().getPrice() + "), " + getSecondAddition().getName() + " (" + getSecondAddition().getPrice() + "), is " + getFinalPrice() + " PLN."); 49 | break; 50 | case 3: 51 | System.out.println("The final price of the Healthy Burger (base: " + getStandardPrice() + " PLN) with following additions: " + getFirstAddition().getName() + " (" + getFirstAddition().getPrice() + "), " + getSecondAddition().getName() + " (" + getSecondAddition().getPrice() + "), " + getThirdAddition().getName() + " (" + getThirdAddition().getPrice() + "), is " + getFinalPrice() + " PLN."); 52 | break; 53 | case 4: 54 | System.out.println("The final price of the Healthy Burger (base: " + getStandardPrice() + " PLN) with following additions: " + getFirstAddition().getName() + " (" + getFirstAddition().getPrice() + "), " + getSecondAddition().getName() + " (" + getSecondAddition().getPrice() + "), " + getThirdAddition().getName() + " (" + getThirdAddition().getPrice() + "), " + getFourthAddition().getName() + " (" + getFourthAddition().getPrice() + "), is " + getFinalPrice() + " PLN."); 55 | break; 56 | case 5: 57 | System.out.println("The final price of the Healthy Burger (base: " + getStandardPrice() + " PLN) with following additions: " + getFirstAddition().getName() + " (" + getFirstAddition().getPrice() + "), " + getSecondAddition().getName() + " (" + getSecondAddition().getPrice() + "), " + getThirdAddition().getName() + " (" + getThirdAddition().getPrice() + "), " + getFourthAddition().getName() + " (" + getFourthAddition().getPrice() + "), " + fifthAddition.getName() + " (" + fifthAddition.getPrice() + "), is " + this.finalPrice + " PLN."); 58 | break; 59 | case 6: 60 | System.out.println("The final price of the Healthy Burger (base: " + getStandardPrice() + " PLN) with following additions: " + getFirstAddition().getName() + " (" + getFirstAddition().getPrice() + "), " + getSecondAddition().getName() + " (" + getSecondAddition().getPrice() + "), " + getThirdAddition().getName() + " (" + getThirdAddition().getPrice() + "), " + getFourthAddition().getName() + " (" + getFourthAddition().getPrice() + "), " + fifthAddition.getName() + " (" + fifthAddition.getPrice() + "), " + sixthAddition.getName() + " (" + sixthAddition.getPrice() + "), is " + this.finalPrice + " PLN."); 61 | break; 62 | } 63 | } else { 64 | System.out.println("The final price of the Healthy Burger is " + getStandardPrice() + " PLN, since you've selected no additions."); 65 | 66 | } 67 | } 68 | 69 | 70 | 71 | 72 | } 73 | 74 | -------------------------------------------------------------------------------- /OOP-2-composition-encapsulation-polymorphism/oop-master-challenge/Main.java: -------------------------------------------------------------------------------- 1 | package com.michal; 2 | 3 | 4 | public class Main { 5 | 6 | public static void main(String[] args) { 7 | RollType white = new RollType("white"); 8 | Addition lettuce = new Addition("lettuce", 2.50); 9 | Addition potato = new Addition("potato", 3.00); 10 | Addition ketchup = new Addition("ketchup", 5.40); 11 | Addition cucumber = new Addition("cucumber", 1.40); 12 | Addition chips = new Addition("chips", 3.00); 13 | Addition drink = new Addition("drink", 3.50); 14 | Addition tomato = new Addition("tomato", 4.70); 15 | 16 | Hamburger myHamburger = new Hamburger("chicken", white, 7.40); 17 | Hamburger ivanHamburger = new Hamburger("chicken", white, 7.40); 18 | Hamburger dubaskaHamburger = new Hamburger("chicken", white, 7.40); 19 | Hamburger karolHamburger = new Hamburger("chicken", white, 7.40); 20 | 21 | DeluxeHamburger deluxeHamburger = new DeluxeHamburger("chicken", white, 9.40, chips, drink); 22 | HealthyBurger oneHealthyBurger = new HealthyBurger("chicken", white, 13.5); 23 | HealthyBurger secondHealthyBurger = new HealthyBurger("chicken", white, 11.70); 24 | HealthyBurger thirdHealthyBurger = new HealthyBurger("chicken", white, 9.30); 25 | HealthyBurger fourthHealthyBurger = new HealthyBurger("chicken", white, 5.30); 26 | 27 | // burger with 4 additions 28 | karolHamburger.addAddition(lettuce, ketchup, tomato, drink); 29 | karolHamburger.showTheFinalPrice(); 30 | System.out.println(); 31 | // burger with 3 additions 32 | ivanHamburger.addAddition(tomato, potato, ketchup); 33 | ivanHamburger.showTheFinalPrice(); 34 | System.out.println(); 35 | // burger with 2 additions 36 | dubaskaHamburger.addAddition(cucumber, lettuce); 37 | dubaskaHamburger.showTheFinalPrice(); 38 | System.out.println(); 39 | // burger with 1 addition 40 | myHamburger.addAddition(chips); 41 | myHamburger.showTheFinalPrice(); 42 | System.out.println(); 43 | // Deluxe Hamburger which comes with chips and a drink 44 | deluxeHamburger.showTheFinalPrice(); 45 | System.out.println(); 46 | // Healthy burger with 1 addition; 47 | oneHealthyBurger.addAddition(ketchup); 48 | oneHealthyBurger.showTheStandardPrice(); 49 | oneHealthyBurger.showTheFinalPrice(); 50 | System.out.println(); 51 | // Healthy burger with two additions 52 | secondHealthyBurger.addAddition(lettuce, potato); 53 | secondHealthyBurger.showTheStandardPrice(); 54 | secondHealthyBurger.showTheFinalPrice(); 55 | System.out.println(); 56 | // Healthy burger with 5 additions 57 | thirdHealthyBurger.addAddition(lettuce, potato, tomato, tomato, tomato); 58 | thirdHealthyBurger.showTheStandardPrice(); 59 | thirdHealthyBurger.showTheFinalPrice(); 60 | System.out.println(); 61 | // Healthy burger with 6 additions 62 | fourthHealthyBurger.addAddition(tomato, potato, tomato, ketchup, cucumber, chips); 63 | fourthHealthyBurger.showTheStandardPrice(); 64 | fourthHealthyBurger.showTheFinalPrice(); 65 | 66 | 67 | 68 | 69 | 70 | // TODO: 71 | // should do some refactoring with overriding and overloading methods 72 | 73 | // DONE: 74 | // to deal with nullPointerException 75 | // printing the value of the base, each addition and total sum of each type of burger 76 | 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /OOP-2-composition-encapsulation-polymorphism/oop-master-challenge/RollType.java: -------------------------------------------------------------------------------- 1 | package com.michal; 2 | 3 | public class RollType { 4 | 5 | private String name; 6 | 7 | public RollType(String name) { 8 | this.name = name; 9 | } 10 | 11 | public String getName() { 12 | return name; 13 | } 14 | 15 | public void setName(String name) { 16 | this.name = name; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /OOP-2-composition-encapsulation-polymorphism/polymorphism-challenge/PolymorphismChallenge.java: -------------------------------------------------------------------------------- 1 | class Car { 2 | 3 | private String name; 4 | private boolean engine; 5 | private int cylinders; 6 | private int wheels; 7 | 8 | public Car(String name, int cylinders) { 9 | this.name = name; 10 | this.engine = true; 11 | this.cylinders = cylinders; 12 | this.wheels = 4; 13 | } 14 | 15 | public String startEngine() { 16 | return "Engine started"; 17 | } 18 | 19 | public String accelerate() { 20 | return "Car accelerated"; 21 | } 22 | 23 | public String brake() { 24 | return "Car stopped"; 25 | } 26 | 27 | public String getName() { 28 | return name; 29 | } 30 | 31 | public boolean isEngine() { 32 | return engine; 33 | } 34 | 35 | public int getCylinders() { 36 | return cylinders; 37 | } 38 | 39 | public int getWheels() { 40 | return wheels; 41 | } 42 | } 43 | 44 | class Karoq extends Car { 45 | 46 | public Karoq() { 47 | super("Karoq", 2311); 48 | } 49 | 50 | @Override 51 | public String startEngine() { 52 | return "Karoq has a very powerful engine. You've pressed the button but it started very quietly."; 53 | } 54 | 55 | @Override 56 | public String accelerate() { 57 | return "Karoq accelerated quite well."; 58 | } 59 | 60 | @Override 61 | public String brake() { 62 | return "Karoq has a very good brakes!"; 63 | } 64 | } 65 | 66 | class Mazda extends Car { 67 | 68 | public Mazda() { 69 | super("Mazda 6", 2600); 70 | } 71 | 72 | @Override 73 | public String startEngine() { 74 | return "You've started the engine with your key. Mazda still has it."; 75 | } 76 | 77 | @Override 78 | public String accelerate() { 79 | return "Mazda 6 has definitely better acceleration than any SUV!"; 80 | } 81 | 82 | @Override 83 | public String brake() { 84 | return "ABS works fine in Mazda."; 85 | } 86 | } 87 | 88 | class Malczan extends Car { 89 | 90 | public Malczan() { 91 | super("Fiat 126p", 250); 92 | } 93 | 94 | @Override 95 | public String startEngine() { 96 | return "You've started the engine of your Malczan. That's a real success!"; 97 | } 98 | 99 | @Override 100 | public String accelerate() { 101 | return "Malczan does not accelerate. Never. Or, at least, it seems that it does not."; 102 | } 103 | 104 | @Override 105 | public String brake() { 106 | return "You've pushed a brake at your Malczan. That was scary!"; 107 | } 108 | } 109 | 110 | public class PolymorphismChallenge { 111 | 112 | public static void main(String[] args) { 113 | for (int i = 1; i < 6; i++) { 114 | Car car = randomCar(); 115 | System.out.println("\nDrawing lots..." + "\n\nCar # " + i + " : " + car.getName() + "\n" + "Engine: " + car.startEngine() + "\n" + "Acceleration: " + car.accelerate() + "\n" + "Brakes: " + car.brake() + "\n"); 116 | } 117 | } 118 | 119 | public static Car randomCar() { 120 | int randomCarNumber = (int) ((Math.random() * 5) + 1); 121 | System.out.println("Random number generated was: " + randomCarNumber); 122 | 123 | switch (randomCarNumber) { 124 | case 1: case 4: case 8: 125 | return new Karoq(); 126 | case 2: case 5: case 9: 127 | return new Mazda(); 128 | case 3: case 6: case 7: 129 | return new Malczan(); 130 | default: 131 | return null; 132 | } 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /OOP-2-composition-encapsulation-polymorphism/polymorphism/Polymorphism.java: -------------------------------------------------------------------------------- 1 | class Movie { 2 | private String name; 3 | 4 | public Movie(String name) { 5 | this.name = name; 6 | } 7 | 8 | public String plot() { 9 | return "No plot here"; 10 | } 11 | 12 | public String getName() { 13 | return name; 14 | } 15 | } 16 | 17 | class Jaws extends Movie { 18 | public Jaws() { 19 | super("Jaws"); 20 | } 21 | 22 | public String plot() { 23 | return "A shark eats lots of people"; 24 | } 25 | } 26 | 27 | class IndependenceDay extends Movie { 28 | 29 | public IndependenceDay() { 30 | super("Independence Day"); 31 | } 32 | 33 | @Override 34 | public String plot() { 35 | return "Aliens attempt to take over planet earth"; 36 | } 37 | } 38 | 39 | class MazeRunner extends Movie { 40 | 41 | public MazeRunner() { 42 | super("Maze Runner"); 43 | } 44 | 45 | @Override 46 | public String plot() { 47 | return "Kids try and escape a maze."; 48 | } 49 | } 50 | 51 | class StarWars extends Movie { 52 | 53 | public StarWars() { 54 | super("Star Wars"); 55 | } 56 | 57 | @Override 58 | public String plot() { 59 | return "Imperial forces try to take over the universe"; 60 | } 61 | } 62 | 63 | class Forgetable extends Movie { 64 | 65 | public Forgetable() { 66 | super("Forgetable"); 67 | } 68 | 69 | // No plot method 70 | } 71 | 72 | 73 | public class Polymorphism { 74 | 75 | public static void main(String[] args) { 76 | for (int i = 1; i < 11; i++) { 77 | Movie movie = randomMovie(); 78 | System.out.println("Movie # " + i + " : " + movie.getName() + "\n" + "Plot: " + movie.plot() + "\n"); 79 | } 80 | } 81 | 82 | public static Movie randomMovie() { 83 | int randomNumber = (int) (Math.random() * 5) + 1; 84 | System.out.println("Random number generated was: " + randomNumber); 85 | 86 | switch (randomNumber) { 87 | case 1: 88 | return new Jaws(); 89 | case 2: 90 | return new IndependenceDay(); 91 | case 3: 92 | return new MazeRunner(); 93 | case 4: 94 | return new StarWars(); 95 | case 5: 96 | return new Forgetable(); 97 | } 98 | return null; 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # java-buchalka 2 | Contains a bunch of exercises I've done from Tim Buchalka's :link: [Complete Java Masterclass](https://www.udemy.com/java-the-complete-java-developer-course) 3 | 4 | :wrench: Language: Java 8 5 | 6 | :ballot_box_with_check: Variables, Datatypes and Operators 7 | :ballot_box_with_check: Expressions, Statements, Code Blocks, Methods and more 8 | :ballot_box_with_check: Control Flow Statements 9 | :ballot_box_with_check: OOP Part 1 - Classes, Constructors and Inheritance 10 | :ballot_box_with_check: OOP Part 2 - Composition, Encapsulation, and Polymorphism 11 | :ballot_box_with_check: Arrays, Java inbuilt Lists, Autoboxing und Unboxing 12 | -------------------------------------------------------------------------------- /arrays-lists-autoboxing-unboxing/ArrayChallenge/ArrayChallenge.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class ArrayChallenge { 4 | 5 | private static Scanner userInput = new Scanner(System.in); 6 | 7 | public static void main(String[] args) { 8 | 9 | int[] integers = getIntegers(5); 10 | printArray(integers); 11 | sortIntegers(integers); 12 | printArray(integers); 13 | 14 | 15 | } 16 | 17 | public static int[] getIntegers(int input) { 18 | int[] enteredNumbers = new int[input]; 19 | System.out.println("Enter " + enteredNumbers.length + " numbers:\r"); 20 | 21 | for (int i = 0; i < enteredNumbers.length; i++) { 22 | enteredNumbers[i] = userInput.nextInt(); 23 | } 24 | return enteredNumbers; 25 | } 26 | 27 | public static void printArray(int[] array) { 28 | for (int i = 0; i < array.length; i++) { 29 | System.out.println(array[i]); 30 | } 31 | } 32 | 33 | public static void sortIntegers(int[] array) { 34 | for(int i = 0; i < array.length / 2; i++) { 35 | int temp = array[i]; 36 | array[i] = array[array.length - 1 - i]; 37 | array[array.length - 1 - i] = temp; 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /arrays-lists-autoboxing-unboxing/ArrayListChallenge-MobilePhoneApp/Contact.java: -------------------------------------------------------------------------------- 1 | public class Contact { 2 | private String name; 3 | private String phoneNumber; 4 | 5 | public Contact(String name, String phoneNumber) { 6 | this.name = name; 7 | this.phoneNumber = phoneNumber; 8 | } 9 | 10 | public String getName() { 11 | return name; 12 | } 13 | 14 | public String getPhoneNumber() { 15 | return phoneNumber; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /arrays-lists-autoboxing-unboxing/ArrayListChallenge-MobilePhoneApp/Main.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class Main { 4 | 5 | public static void main(String[] args) { 6 | MobilePhone myPhone = new MobilePhone("900500300"); 7 | 8 | Scanner scanner = new Scanner(System.in); 9 | boolean quit = false; 10 | 11 | while(!quit) { 12 | 13 | printMenu(); 14 | 15 | int choice = scanner.nextInt(); 16 | scanner.nextLine(); 17 | 18 | 19 | switch (choice) { 20 | case 0: 21 | System.out.println("Quitting the program..."); 22 | quit = true; 23 | break; 24 | case 1: 25 | myPhone.printContacts(); 26 | break; 27 | case 2: 28 | System.out.println("New contact: "); 29 | String name = scanner.nextLine(); 30 | System.out.println("Enter phone number:"); 31 | String phoneNumber = scanner.nextLine(); 32 | myPhone.addContact(name, phoneNumber); 33 | break; 34 | case 3: 35 | System.out.println("Enter contact name to query:"); 36 | myPhone.queryContactName(scanner.nextLine()); 37 | break; 38 | case 4: 39 | System.out.println("Enter contact name to be updated:"); 40 | String oldName = scanner.nextLine(); 41 | System.out.println("Enter new contact name:"); 42 | String newContactName = scanner.nextLine(); 43 | System.out.println("Enter new phone number:"); 44 | String newPhoneNumber = scanner.nextLine(); 45 | myPhone.updateContact(oldName, newContactName, newPhoneNumber); 46 | break; 47 | case 5: 48 | System.out.println("Enter contact name to be removed:"); 49 | myPhone.removeContact(scanner.nextLine()); 50 | break; 51 | } 52 | } 53 | 54 | } 55 | 56 | private static void printMenu() { 57 | System.out.println("\nYour options: \t1 - to print your contact list." + 58 | "\t2 - to add a new contact." + 59 | "\t3 - to query a contact." + 60 | "\t4 - to update a contact." + 61 | "\t5 - to remove a contact." + 62 | "\t0 - to quit the program."); 63 | } 64 | 65 | 66 | } 67 | -------------------------------------------------------------------------------- /arrays-lists-autoboxing-unboxing/ArrayListChallenge-MobilePhoneApp/MobilePhone.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | public class MobilePhone { 5 | public String myNumber; 6 | public List myContacts = new ArrayList<>(); 7 | 8 | public MobilePhone(String myNumber) { 9 | this.myNumber = myNumber; 10 | } 11 | 12 | public void printContacts() { 13 | System.out.println("\nContact list of the phone number " + myNumber + ":\n"); 14 | for (int i = 0; i < myContacts.size(); i++) { 15 | System.out.println(myContacts.get(i).getName()); 16 | } 17 | } 18 | 19 | public void addContact(String name, String number) { 20 | if (queryContact(name) == -1) { 21 | Contact contact = new Contact(name, number); 22 | myContacts.add(contact); 23 | System.out.println("New contact added."); 24 | } else { 25 | System.out.println("Operation error. Contact " + name + " already on your contact list."); 26 | } 27 | } 28 | 29 | public void updateContact(String oldName, String newName, String number) { 30 | int queryResult = queryContact(oldName); 31 | if (queryResult >= 0) { 32 | Contact updatedContact = new Contact(newName, number); 33 | myContacts.set(queryResult, updatedContact); 34 | System.out.println("Contact " + oldName + " has been replaced with " + newName + " (phone: " + number + ")."); 35 | } else { 36 | System.out.println("Operation error. Contact " + oldName + " was not found on your contact list, so was not updated."); 37 | } 38 | } 39 | 40 | public int queryContact(String contactName) { 41 | for (int i = 0; i < myContacts.size(); i++) { 42 | if (contactName.equals(myContacts.get(i).getName())) { 43 | return i; 44 | } 45 | } 46 | return -1; 47 | } 48 | 49 | public void queryContactName(String contactName) { 50 | int contactIndex = queryContact(contactName); 51 | if (contactIndex >= 0) { 52 | System.out.println("Contact " + contactName + " was found on index " + contactIndex + " on your contact list."); 53 | } else { 54 | System.out.println("Contact " + contactName + " was not found on your contact list."); 55 | } 56 | } 57 | 58 | public void removeContact(String contactName) { 59 | int contactIndex = queryContact(contactName); 60 | if (contactIndex >= 0) { 61 | myContacts.remove(contactIndex); 62 | System.out.println("Contact " + contactName + " successfully removed from your contact list."); 63 | } else { 64 | System.out.println("Contact " + contactName + " was not found on your contact list, so not deleted."); 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /arrays-lists-autoboxing-unboxing/ArrayListTraining-TODOList/Main.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class Main { 4 | 5 | private static Scanner scanner = new Scanner(System.in); 6 | private static ToDoList myToDoList = new ToDoList(); 7 | 8 | public static void main(String[] args) { 9 | 10 | boolean quit = false; 11 | int choice = 0; 12 | printInstructions(); 13 | while (!quit) { 14 | System.out.println("Enter your choice: "); 15 | choice = scanner.nextInt(); 16 | scanner.nextLine(); 17 | 18 | switch (choice) { 19 | case 0: 20 | printInstructions(); 21 | break; 22 | case 1: 23 | myToDoList.printTasks(); 24 | break; 25 | case 2: 26 | addTask(); 27 | break; 28 | case 3: 29 | modifyTask(); 30 | break; 31 | case 4: 32 | removeTask(); 33 | break; 34 | case 5: 35 | searchForTask(); 36 | break; 37 | case 6: 38 | quit = true; 39 | break; 40 | } 41 | } 42 | } 43 | 44 | public static void printInstructions() { 45 | System.out.println("\nPress "); 46 | System.out.println("\t 0 to print the choice options"); 47 | System.out.println("\t 1 to print the TODO list"); 48 | System.out.println("\t 2 to add a task to the list"); 49 | System.out.println("\t 3 to modify a task in the list"); 50 | System.out.println("\t 4 to remove a task from the list"); 51 | System.out.println("\t 5 to search for a task in the list"); 52 | System.out.println("\t 6 to quit the application"); 53 | } 54 | 55 | 56 | public static void addTask() { 57 | System.out.print("Please enter the task:"); 58 | myToDoList.addTask(scanner.nextLine()); 59 | } 60 | 61 | public static void modifyTask() { 62 | System.out.print("Enter task number: "); 63 | int taskNo = scanner.nextInt(); 64 | scanner.nextLine(); 65 | System.out.println("Enter replacement task: "); 66 | String newTask = scanner.nextLine(); 67 | myToDoList.modifyTask(taskNo - 1, newTask); 68 | } 69 | 70 | public static void removeTask() { 71 | System.out.print("Enter task number: "); 72 | int taskNo = scanner.nextInt(); 73 | scanner.nextLine(); 74 | myToDoList.removeTask(taskNo); 75 | } 76 | 77 | public static void searchForTask() { 78 | System.out.println("Task to search for:"); 79 | String searchTask = scanner.nextLine(); 80 | if (myToDoList.findTask(searchTask) != null) { 81 | System.out.println("Found " + searchTask + " in your TODO list"); 82 | } else { 83 | System.out.println(searchTask + " not found in your TODO list"); 84 | } 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /arrays-lists-autoboxing-unboxing/ArrayListTraining-TODOList/ToDoList.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class ToDoList { 4 | 5 | // ArrayList can hold objects 6 | // and handles the size of itself automatically 7 | private ArrayList toDoList = new ArrayList(); 8 | 9 | 10 | // adding an element to the ArrayList 11 | public void addTask(String task) { 12 | toDoList.add(task); 13 | } 14 | 15 | // printing all elements from the ArrayList 16 | public void printTasks() { 17 | System.out.println("You have " + toDoList.size() + " tasks to do."); 18 | for (int i = 0; i < toDoList.size(); i++) { 19 | System.out.println((i + 1) + ". " + toDoList.get(i)); 20 | } 21 | } 22 | 23 | // modifies the element in the ArrayList (by replacing it) 24 | public void modifyTask(int position, String newTask) { 25 | toDoList.set(position, newTask); 26 | System.out.println("Task " + (position + 1) + " has been modified."); 27 | } 28 | 29 | // removing a specfic task (with specific index) 30 | public void removeTask(int position) { 31 | String specificTask = toDoList.get(position); 32 | toDoList.remove(position-1); 33 | System.out.println("Task " + (position) + " has been removed."); 34 | } 35 | 36 | // finding a fask with specified name 37 | public String findTask(String task) { 38 | int position = toDoList.indexOf(task); 39 | if (position >= 0) { 40 | return toDoList.get(position); 41 | } 42 | return null; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /arrays-lists-autoboxing-unboxing/Arrays/Arrays.java: -------------------------------------------------------------------------------- 1 | public class Arrays { 2 | 3 | public static void main(String[] args) { 4 | // decalaration & initialization of an array 5 | int[] myIntArray = new int[18]; 6 | // setting the value of an integer with index 5 in myIntArray to 50 7 | myIntArray[5] = 50; 8 | // declaration & initialization of myDoubleArray 9 | double[] myDoubleArray = new double[10]; 10 | // printing the value with index 5 from myIntArray 11 | System.out.println(myIntArray[5]); 12 | // declaration & initialization myIntArray2 with specified content 13 | int[] myIntArray2 = {5, 3, 7, 2, 10}; 14 | // printing the value with index 3 from myIntArray2 15 | System.out.println(myIntArray2[3]); 16 | // for loop that assigns values into myIntArray in an order 17 | for(int i = 0; i < myIntArray.length; i++) { 18 | myIntArray[i] = i * 10; 19 | } 20 | // for loop that reads the index of an element and print it 21 | for(int i = 0; i < myIntArray.length; i++) { 22 | System.out.println("Element " + i + ", value is " + myIntArray[i]); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /arrays-lists-autoboxing-unboxing/ArraysWithScanner/ArraysWithScanner.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class ArraysWithScanner { 4 | 5 | // method of type Scanner that assigns the user input into a variable scanner 6 | private static Scanner scanner = new Scanner(System.in); 7 | 8 | public static void main(String[] args) { 9 | // array of a type of int which size is equal to a parameter of getInteger method called 'number' 10 | int[] myIntegers = getIntegers(5); 11 | // for loop that prints following values of an array that has been typed by the user 12 | for (int i = 0; i < myIntegers.length; i++) { 13 | System.out.println("Element " + i + ", typed value was " + myIntegers[i]); 14 | } 15 | System.out.println("The average is " + getAverage(myIntegers)); 16 | } 17 | 18 | // method of type array-integers that gets the parameter of an int 19 | public static int[] getIntegers(int number) { 20 | // prints a message to the user with an information how many numbers he should enter 21 | System.out.println("Enter " + number + " integer values.\r"); 22 | // creates an array of integers called 'values' and sets its size to the parameter of the method 23 | int[] values = new int[number]; 24 | // for loop that allows the user to type values that are assigned to the following values of an array 25 | for (int i = 0; i < values.length; i++) { 26 | // each execution of the loop changer the value of the index to higher and assigns user's input there 27 | values[i] = scanner.nextInt(); 28 | } 29 | // returns an array after the execution of the loop (i.e. filling it with user's input 30 | return values; 31 | } 32 | 33 | // method of type double that return the average value of the user's jnput 34 | public static double getAverage(int[] array) { 35 | // a variable sum stores the sum of the user's input 36 | int sum = 0; 37 | // for loop that adds user's input and assigns the result to the variable sum 38 | for(int i = 0; i < array.length; i++) { 39 | sum += array[i]; 40 | } 41 | // method return casted value of sum into double, because the average value of the user's input may be a fraction 42 | return (double) sum / (double)array.length; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /arrays-lists-autoboxing-unboxing/Autoboxing-unboxing/AutoboxingUnboxing.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | class IntClass { 4 | private int myValue; 5 | 6 | public IntClass(int myValue) { 7 | this.myValue = myValue; 8 | } 9 | 10 | public int getMyValue() { 11 | return myValue; 12 | } 13 | 14 | public void setMyValue(int myValue) { 15 | this.myValue = myValue; 16 | } 17 | } 18 | 19 | 20 | public class AutoboxingUnboxing { 21 | 22 | public static void main(String[] args) { 23 | 24 | String[] strArray = new String[10]; 25 | int[] intArray = new int[10]; 26 | 27 | ArrayList strArrayList = new ArrayList(); 28 | strArrayList.add("Michał"); 29 | 30 | ArrayList intClassArrayList = new ArrayList(); 31 | intClassArrayList.add(new IntClass(54)); 32 | 33 | // Unnecessary boxing 34 | Integer integer = new Integer(54); 35 | Double doubleValue = new Double(12.25); 36 | 37 | ArrayList intArrayList = new ArrayList(); 38 | for(int i=0; i<=10; i++) { 39 | intArrayList.add(Integer.valueOf(i)); 40 | } 41 | 42 | for(int i=0; i<=10; i++) { 43 | System.out.println(i + " --> " + intArrayList.get(i).intValue()); 44 | } 45 | 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /arrays-lists-autoboxing-unboxing/AutoboxingUnboxingChallenge/Bank.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class Bank { 4 | private String name; 5 | private ArrayList branches; 6 | 7 | public Bank(String name) { 8 | this.name = name; 9 | this.branches = new ArrayList(); 10 | } 11 | 12 | public boolean addBranch(String branchName) { 13 | if (findBranch(branchName) == null) { 14 | this.branches.add(new Branch(branchName)); 15 | return true; 16 | } 17 | return false; 18 | } 19 | 20 | public boolean addCustomer(String branchName, String customerName, double initialAmount) { 21 | Branch branch = findBranch(branchName); 22 | if (branch != null) { 23 | return branch.newCustomer(customerName, initialAmount); 24 | } 25 | return false; 26 | } 27 | 28 | public boolean addCustomerTransaction(String branchname, String customerName, double transactionAmount) { 29 | Branch branch = findBranch(branchname); 30 | if (branch != null) { 31 | return branch.addCustomerTransaction(customerName, transactionAmount); 32 | } 33 | return false; 34 | } 35 | 36 | 37 | private Branch findBranch(String branchName) { 38 | for (int i = 0; i < this.branches.size(); i++) { 39 | Branch checkedBranch = this.branches.get(i); 40 | if (checkedBranch.getName().equals(branchName)) { 41 | return checkedBranch; 42 | } 43 | } 44 | return null; 45 | } 46 | 47 | public boolean listCustomers(String branchName, boolean showTransactions) { 48 | Branch branch = findBranch(branchName); 49 | if (branch != null) { 50 | System.out.println("Customers details for branch " + branch.getName()); 51 | 52 | ArrayList branchCustomers = branch.getCustomers(); 53 | for (int i = 0; i < branchCustomers.size(); i++) { 54 | Customer branchCustomer = branchCustomers.get(i); 55 | System.out.println("Customer: " + branchCustomer.getName() + "[" + (i + 1) + "]"); 56 | if (showTransactions) { 57 | System.out.println("Transactions"); 58 | ArrayList transactions = branchCustomer.getTransactions(); 59 | for (int j = 0; j < transactions.size(); j++) { 60 | System.out.println("[" + (j + 1) + "] Amount " + transactions.get(j)); 61 | } 62 | } 63 | } 64 | return true; 65 | } else { 66 | return false; 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /arrays-lists-autoboxing-unboxing/AutoboxingUnboxingChallenge/Branch.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class Branch { 4 | private String name; 5 | private ArrayList customers; 6 | 7 | public Branch(String name) { 8 | this.name = name; 9 | this.customers = new ArrayList(); 10 | } 11 | 12 | public String getName() { 13 | return name; 14 | } 15 | 16 | public ArrayList getCustomers() { 17 | return customers; 18 | } 19 | 20 | public boolean newCustomer(String customerName, double initialAmount) { 21 | if(findCustomer(customerName) == null) { 22 | this.customers.add(new Customer(customerName, initialAmount)); 23 | return true; 24 | } 25 | return false; 26 | } 27 | 28 | public boolean addCustomerTransaction(String customerName, double amount) { 29 | Customer existingCustomer = findCustomer(customerName); 30 | if(existingCustomer != null) { 31 | existingCustomer.addTransaction(amount); 32 | return true; 33 | } 34 | return false; 35 | } 36 | 37 | private Customer findCustomer(String customerName) { 38 | for(int i=0; i transactions; 6 | 7 | public Customer(String name, double initialAmount) { 8 | this.name = name; 9 | this.transactions = new ArrayList(); 10 | addTransaction(initialAmount); 11 | } 12 | 13 | public void addTransaction(double amount) { 14 | 15 | this.transactions.add(amount); 16 | } 17 | 18 | public String getName() { 19 | return name; 20 | } 21 | 22 | public ArrayList getTransactions() { 23 | return transactions; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /arrays-lists-autoboxing-unboxing/AutoboxingUnboxingChallenge/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | Bank bank = new Bank("National Australia Bank"); 5 | bank.addBranch("Adelaide"); 6 | bank.addCustomer("Adelaide", "Michal", 50.05); 7 | bank.addCustomer("Adelaide", "Tim", 175.34); 8 | bank.addCustomer("Adelaide", "Percy", 220.12); 9 | 10 | bank.addBranch("Sydney"); 11 | bank.addCustomer("Sydney", "Bob", 150.54); 12 | 13 | bank.addCustomerTransaction("Adelaide", "Michal", 44.22); 14 | bank.addCustomerTransaction("Adelaide", "Michal", 12.44); 15 | bank.addCustomerTransaction("Adelaide", "Tim", 1.65); 16 | 17 | bank.listCustomers("Adelaide", true); 18 | bank.listCustomers("Sydney", true); 19 | 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /arrays-lists-autoboxing-unboxing/GroceryApp/GroceryApp.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class GroceryApp { 4 | private static Scanner scanner = new Scanner(System.in); 5 | private static GroceryList groceryList = new GroceryList(); 6 | 7 | 8 | public static void main(String[] args) { 9 | boolean quit = false; 10 | int choice = 0; 11 | printInstructions(); 12 | while (!quit) { 13 | System.out.println("Enter your choice: "); 14 | choice = scanner.nextInt(); 15 | scanner.nextLine(); 16 | 17 | switch (choice) { 18 | case 0: 19 | printInstructions(); 20 | break; 21 | case 1: 22 | groceryList.printGroceryList(); 23 | break; 24 | case 2: 25 | addItem(); 26 | break; 27 | case 3: 28 | modifyItem(); 29 | break; 30 | case 4: 31 | removeItem(); 32 | break; 33 | case 5: 34 | searchForItem(); 35 | break; 36 | case 6: 37 | quit = true; 38 | break; 39 | } 40 | } 41 | } 42 | 43 | public static void printInstructions() { 44 | System.out.println("\nPress "); 45 | System.out.println("\t 0 to print the choice options"); 46 | System.out.println("\t 1 to print the grocery list"); 47 | System.out.println("\t 2 to add an item to the list"); 48 | System.out.println("\t 3 to modify an item in the list"); 49 | System.out.println("\t 4 to remove an item from the list"); 50 | System.out.println("\t 5 to search for an item in the list"); 51 | System.out.println("\t 6 to quit the application"); 52 | } 53 | 54 | public static void addItem() { 55 | System.out.print("Please enter the grocery item: "); 56 | groceryList.addGroceryItem(scanner.nextLine()); 57 | } 58 | 59 | public static void modifyItem() { 60 | System.out.print("Enter item number:"); 61 | int itemNo = scanner.nextInt(); 62 | scanner.nextLine(); 63 | System.out.println("Enter replacement item"); 64 | String newItem = scanner.nextLine(); 65 | groceryList.modifyGroceryItem(itemNo-1, newItem); 66 | } 67 | 68 | public static void removeItem() { 69 | System.out.print("Enter item number:"); 70 | int itemNo = scanner.nextInt(); 71 | scanner.nextLine(); 72 | groceryList.removeGroceryItem(itemNo-1); 73 | } 74 | 75 | public static void searchForItem() { 76 | System.out.println("Item to search for:"); 77 | String searchItem = scanner.nextLine(); 78 | if(groceryList.findItem(searchItem) != null) { 79 | System.out.println("Found " + searchItem + " in our grocery list"); 80 | } else { 81 | System.out.println(searchItem + " is not in the shopping list"); 82 | } 83 | } 84 | 85 | } 86 | -------------------------------------------------------------------------------- /arrays-lists-autoboxing-unboxing/GroceryApp/GroceryList.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class GroceryList { 4 | 5 | private ArrayList groceryList = new ArrayList(); 6 | 7 | public void addGroceryItem(String item) { 8 | groceryList.add(item); 9 | } 10 | 11 | public void printGroceryList() { 12 | System.out.println("You have " + groceryList.size() + " items in your grocery list."); 13 | for (int i = 0; i < groceryList.size(); i++) { 14 | System.out.println((i + 1) + ". " + groceryList.get(i)); 15 | } 16 | } 17 | 18 | public void modifyGroceryItem(int position, String newItem) { 19 | groceryList.set(position, newItem); 20 | System.out.println("Grocery item " + (position + 1) + " has been modified."); 21 | } 22 | 23 | public void removeGroceryItem(int position) { 24 | String theItem = groceryList.get(position); 25 | groceryList.remove(position); 26 | } 27 | 28 | public String findItem(String searchItem) { 29 | // boolean exists = groceryList.contains(searchItem); 30 | int position = groceryList.indexOf(searchItem); 31 | if (position >= 0) { 32 | return groceryList.get(position); 33 | } 34 | return null; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /arrays-lists-autoboxing-unboxing/LinkedList-Challenge/Album.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.LinkedList; 3 | 4 | public class Album { 5 | private String name; 6 | private String artist; 7 | private ArrayList songs; 8 | 9 | public Album(String name, String artist) { 10 | this.name = name; 11 | this.artist = artist; 12 | this.songs = new ArrayList(); 13 | } 14 | 15 | public boolean addSong(String title, double duration) { 16 | if (findSong(title) == null) { 17 | this.songs.add(new Song(title, duration)); 18 | return true; 19 | } 20 | return false; 21 | } 22 | 23 | private Song findSong(String title) { 24 | for (Song checkedSong : this.songs) { 25 | if (checkedSong.getTitle().equals(title)) { 26 | return checkedSong; 27 | } 28 | } 29 | return null; 30 | } 31 | 32 | public boolean addToPlayList(int trackNumber, LinkedList playlist) { 33 | int index = trackNumber - 1; 34 | if ((index >= 0) && (index <= this.songs.size())) { 35 | playlist.add(this.songs.get(index)); 36 | return true; 37 | } 38 | System.out.println("This album does not have a track " + trackNumber); 39 | return false; 40 | } 41 | 42 | public boolean addToPlaylist(String title, LinkedList playlist) { 43 | Song checkedSong = findSong(title); 44 | if (checkedSong != null) { 45 | playlist.add(checkedSong); 46 | return true; 47 | } 48 | System.out.println("The song " + title + " is not in this album"); 49 | return false; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /arrays-lists-autoboxing-unboxing/LinkedList-Challenge/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | // write your code here 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /arrays-lists-autoboxing-unboxing/LinkedList-Challenge/Song.java: -------------------------------------------------------------------------------- 1 | public class Song { 2 | 3 | private String title; 4 | private double duration; 5 | 6 | public Song(String title, double duration) { 7 | this.title = title; 8 | this.duration = duration; 9 | } 10 | 11 | public String getTitle() { 12 | return title; 13 | } 14 | 15 | @Override 16 | public String toString() { 17 | return this.title + ": " + this.duration; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /arrays-lists-autoboxing-unboxing/LinkedList/Customer.java: -------------------------------------------------------------------------------- 1 | public class Customer { 2 | private String name; 3 | private double balance; 4 | 5 | public Customer(String name, double balance) { 6 | this.name = name; 7 | this.balance = balance; 8 | } 9 | 10 | public String getName() { 11 | return name; 12 | } 13 | 14 | public double getBalance() { 15 | return balance; 16 | } 17 | 18 | public void setName(String name) { 19 | this.name = name; 20 | } 21 | 22 | public void setBalance(double balance) { 23 | this.balance = balance; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /arrays-lists-autoboxing-unboxing/LinkedList/Demo.java: -------------------------------------------------------------------------------- 1 | import java.util.Iterator; 2 | import java.util.LinkedList; 3 | import java.util.ListIterator; 4 | import java.util.Scanner; 5 | 6 | public class Demo { 7 | public static void main(String[] args) { 8 | LinkedList placesToVisit = new LinkedList(); 9 | addInOrder(placesToVisit, "Sydney"); 10 | addInOrder(placesToVisit, "Melbourne"); 11 | addInOrder(placesToVisit, "Brisbane"); 12 | addInOrder(placesToVisit, "Perth"); 13 | addInOrder(placesToVisit, "Canberra"); 14 | addInOrder(placesToVisit, "Adelaide"); 15 | addInOrder(placesToVisit, "Darwin"); 16 | printList(placesToVisit); 17 | 18 | addInOrder(placesToVisit, "Alice Springs"); 19 | addInOrder(placesToVisit, "Darwin"); 20 | visit(placesToVisit); 21 | 22 | } 23 | 24 | private static void printList(LinkedList linkedList) { 25 | Iterator i = linkedList.iterator(); 26 | while (i.hasNext()) { 27 | System.out.println("Visiting " + i.next()); 28 | } 29 | System.out.println("=============="); 30 | } 31 | 32 | private static boolean addInOrder(LinkedList linkedList, String newCity) { 33 | ListIterator stringListIterator = linkedList.listIterator(); 34 | 35 | while (stringListIterator.hasNext()) { 36 | int comparison = stringListIterator.next().compareTo(newCity); 37 | if (comparison == 0) { 38 | System.out.println(newCity + " is already included as a destination."); 39 | return false; 40 | } else if (comparison > 0) { 41 | stringListIterator.previous(); 42 | stringListIterator.add(newCity); 43 | return true; 44 | } 45 | } 46 | stringListIterator.add(newCity); 47 | return true; 48 | } 49 | 50 | private static void visit(LinkedList cities) { 51 | Scanner scanner = new Scanner(System.in); 52 | boolean quit = false; 53 | boolean goingForward = true; 54 | ListIterator listIterator = cities.listIterator(); 55 | 56 | if (cities.isEmpty()) { 57 | System.out.println("No cities in the itenerary"); 58 | return; 59 | } else { 60 | System.out.println("Now visiting " + listIterator.next()); 61 | printMenu(); 62 | } 63 | 64 | while (!quit) { 65 | int action = scanner.nextInt(); 66 | scanner.nextLine(); 67 | 68 | switch (action) { 69 | case 0: 70 | System.out.println("Holiday over."); 71 | quit = true; 72 | break; 73 | case 1: 74 | if (!goingForward) { 75 | if (listIterator.hasNext()) { 76 | listIterator.next(); 77 | } 78 | goingForward = true; 79 | } 80 | if (listIterator.hasNext()) { 81 | System.out.println("Now visiting " + listIterator.next()); 82 | } else { 83 | System.out.println("Reached the end of the list"); 84 | goingForward = false; 85 | } 86 | break; 87 | case 2: 88 | if (goingForward) { 89 | if (listIterator.hasPrevious()) { 90 | listIterator.previous(); 91 | } 92 | goingForward = false; 93 | } 94 | if (listIterator.hasPrevious()) { 95 | System.out.println("Now visiting " + listIterator.previous()); 96 | } else { 97 | System.out.println("Now we are at the start of the list"); 98 | goingForward = true; 99 | } 100 | break; 101 | case 3: 102 | printMenu(); 103 | break; 104 | } 105 | } 106 | } 107 | 108 | private static void printMenu() { 109 | System.out.println("Available actions: \npress "); 110 | System.out.println("0 - quit\n1 - next city\n2 - previous city\n3 - print menu options"); 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /arrays-lists-autoboxing-unboxing/LinkedList/Main.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class Main { 4 | 5 | public static void main(String[] args) { 6 | 7 | Customer customer = new Customer("Michal", 54.96); 8 | Customer anotherCustomer; 9 | anotherCustomer = customer; 10 | anotherCustomer.setBalance(12.18); 11 | System.out.println("Balance for customer: " + customer.getName() + " is " + customer.getBalance()); 12 | 13 | ArrayList intList = new ArrayList(); 14 | 15 | intList.add(1); 16 | intList.add(3); 17 | intList.add(4); 18 | 19 | for(int i=0; i= 0; i--) { 14 | reversedArray[j] = array[i]; 15 | j++; 16 | } 17 | System.out.println("Array: " + Arrays.toString(array)); 18 | System.out.println("Reversed array: " + Arrays.toString(reversedArray)); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /arrays-lists-autoboxing-unboxing/VisitedPlaces-ArrayList-training/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | private static VisitedPlaces visitedPlaces = new VisitedPlaces(); 4 | 5 | public static void main(String[] args) { 6 | 7 | 8 | visitedPlaces.addPlace("Grecja"); 9 | visitedPlaces.addPlace("Węgry"); 10 | visitedPlaces.addPlace("Ukraina"); 11 | visitedPlaces.addPlace("Austria"); 12 | visitedPlaces.addPlace("Białoruś"); 13 | visitedPlaces.addPlace("Niemcy"); 14 | visitedPlaces.printPlaces(); 15 | visitedPlaces.modifyPlace(2, "Czechy"); 16 | visitedPlaces.printPlaces(); 17 | visitedPlaces.queryElement("Ukraina"); 18 | visitedPlaces.queryElement("Czarnogóra"); 19 | visitedPlaces.removePlace("Białoruś"); 20 | visitedPlaces.removePlace("Niemcy"); 21 | visitedPlaces.printPlaces(); 22 | 23 | 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /arrays-lists-autoboxing-unboxing/VisitedPlaces-ArrayList-training/VisitedPlaces.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class VisitedPlaces { 4 | 5 | private ArrayList visitedPlaces = new ArrayList(); 6 | 7 | // adding an element 8 | public void addPlace(String place) { 9 | visitedPlaces.add(place); 10 | System.out.println(place + " has been added to your list of visited places."); 11 | } 12 | 13 | // removing an element 14 | public void removePlace(String place) { 15 | visitedPlaces.remove(place); 16 | System.out.println(place + " has been removed from your list of visited places."); 17 | } 18 | 19 | // modifying an element 20 | public void modifyPlace(int position, String place) { 21 | visitedPlaces.set(position-1, place); 22 | System.out.println("Entry no. " + (position) + " has been modified."); 23 | } 24 | 25 | // querying an element 26 | public void queryElement(String place) { 27 | if (visitedPlaces.contains(place)) { 28 | System.out.println(place + " found on your list of visited places."); 29 | } else { 30 | System.out.println(place + " was not found on your list of visited places."); 31 | } 32 | } 33 | 34 | // printing all elements 35 | public void printPlaces() { 36 | for(int i=0; i= 10) { 15 | int sum = 0; 16 | while (number > 0) { 17 | // extract the least-significant digit 18 | int digit = number % 10; 19 | sum += digit; 20 | 21 | // drop the least-significant digit 22 | number /= 10; // same as number = number / 10; 23 | } 24 | return sum; 25 | } 26 | return -1; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /control-flow-statements/EvenDigitSum.java: -------------------------------------------------------------------------------- 1 | public class EvenDigitSum { 2 | 3 | public static void main(String[] args) { 4 | System.out.println(getEvenDigitSum(123456789)); 5 | System.out.println(getEvenDigitSum(252)); 6 | System.out.println(getEvenDigitSum(-22)); 7 | System.out.println(getEvenDigitSum(0)); 8 | } 9 | 10 | public static int getEvenDigitSum(int number) { 11 | int originalNumber = number; 12 | int lastDigit; 13 | int sumOfEvenDigits = 0; 14 | if (number >= 0) { 15 | while (number > 0) { 16 | lastDigit = number % 10; 17 | if (lastDigit % 2 == 0) { 18 | sumOfEvenDigits += lastDigit; 19 | } 20 | number /= 10; 21 | } 22 | if (originalNumber >= 0) { 23 | System.out.println("The sum of even digits within a number " + originalNumber + " is equal to:"); 24 | } 25 | return sumOfEvenDigits; 26 | } 27 | System.out.println("Invalid input:"); 28 | return -1; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /control-flow-statements/FactorsPrinter.java: -------------------------------------------------------------------------------- 1 | public class FactorsPrinter { 2 | 3 | public static void main(String[] args) { 4 | printFactors(6); 5 | printFactors(32); 6 | printFactors(10); 7 | printFactors(-1); 8 | } 9 | 10 | public static void printFactors(int number) { 11 | if (number >= 1) { 12 | for (int i = number; i > 0; i--) { 13 | int factor = number / i; 14 | if (number % i == 0) { 15 | System.out.println(factor); 16 | } 17 | } 18 | } else { 19 | System.out.println("Invalid Value"); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /control-flow-statements/FirstLastDigitSum.java: -------------------------------------------------------------------------------- 1 | public class FirstLastDigitSum { 2 | 3 | public static void main(String[] args) { 4 | System.out.println(sumFirstAndLastDigit(3564)); 5 | System.out.println(sumFirstAndLastDigit(1)); 6 | System.out.println(sumFirstAndLastDigit(5)); 7 | System.out.println(sumFirstAndLastDigit(-10)); 8 | System.out.println(sumFirstAndLastDigit(90211219)); 9 | System.out.println(sumFirstAndLastDigit(39023117)); 10 | } 11 | 12 | public static int sumFirstAndLastDigit(int number) { 13 | if (number >= 0) { 14 | int originalNumber = number; 15 | // extracting the last digit of a number 16 | int lastDigit = number % 10; 17 | // firstDigit variable initialized as equal to 0 18 | int firstDigit = 0; 19 | // while loop founds the first digit and assigns that to the variable firstDigit 20 | // or assigns the value of lastDigit to firstDigit when the number has only one digit 21 | if (number < 10) { 22 | firstDigit = lastDigit; 23 | } else { 24 | while (number > 1) { 25 | number = number / 10; 26 | if (number == 0) { 27 | break; 28 | } 29 | firstDigit = number; 30 | } 31 | } 32 | // returns the sum of the first and last digits of a given number 33 | if (originalNumber > 9) { 34 | System.out.println("The first digit of " + originalNumber + " is " + firstDigit + ", and the last digit of that number is " + lastDigit + ". The sum of them is equal to: "); 35 | } else { 36 | System.out.println("The first digit of " + originalNumber + " is equal to the last digit, since there is only one digit. Therefore, the sum of them (" + firstDigit + " + " + lastDigit + ") is equal to: "); 37 | } 38 | return firstDigit + lastDigit; 39 | } 40 | // returns -1 when input is invalid 41 | System.out.println("The input was invalid, since the program accepts only positive integers."); 42 | return -1; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /control-flow-statements/FlourPacker.java: -------------------------------------------------------------------------------- 1 | public class FlourPacker { 2 | 3 | public static void main(String[] args) { 4 | System.out.println(canPack(2, 1, 5)); 5 | 6 | } 7 | 8 | public static boolean canPack(int bigCount, int smallCount, int goal) { 9 | if (bigCount < 0 || smallCount < 0 || goal < 0) { 10 | return false; 11 | } 12 | if(goal > ((bigCount * 5) + smallCount)) { 13 | return false; 14 | } 15 | 16 | if((goal % 5) > smallCount) { 17 | return false; 18 | } 19 | return true; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /control-flow-statements/ForLoop.java: -------------------------------------------------------------------------------- 1 | public class ForLoop { 2 | 3 | public static void main(String[] args) { 4 | 5 | for (int i = 2; i <= 8; i++) { 6 | System.out.println("10.000 at " + i + "% interest = " + String.format("%.2f", calculateInterest(10_000, i))); 7 | } 8 | 9 | System.out.println("\n\n"); 10 | 11 | for (int i = 8; i >= 2; i--) { 12 | System.out.println("10.000 at " + i + "% interest = " + String.format("%.2f", calculateInterest(10_000, i))); 13 | } 14 | 15 | System.out.println("\n\n"); 16 | 17 | int count = 0; 18 | for (int i = 0; i <= 50; i++) { 19 | 20 | if (isPrime(i)) { 21 | System.out.println(i + " is a prime number."); 22 | count++; 23 | if (count == 10) { 24 | System.out.println("Found " + count + " prime numbers."); 25 | break; 26 | } 27 | } 28 | } 29 | } 30 | 31 | public static double calculateInterest(double amount, double interestRate) { 32 | return (amount * (interestRate / 100)); 33 | } 34 | 35 | public static boolean isPrime(int n) { 36 | if (n == 1) { 37 | return false; 38 | } 39 | for (int i = 2; i <= n / 2; i++) { 40 | if (n % i == 0) { 41 | return false; 42 | } 43 | } 44 | return true; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /control-flow-statements/GreatestCommonDivisor.java: -------------------------------------------------------------------------------- 1 | public class GreatestCommonDivisor { 2 | 3 | 4 | public static void main(String[] args) { 5 | System.out.println(getGreatestCommonDivisor(25, 15)); 6 | System.out.println(getGreatestCommonDivisor(12, 30)); 7 | System.out.println(getGreatestCommonDivisor(9, 18)); 8 | System.out.println(getGreatestCommonDivisor(81, 153)); 9 | } 10 | 11 | public static int getGreatestCommonDivisor(int first, int second) { 12 | if (first >= 10 && second >= 10) { 13 | // finds the smaller number of the two given and then ascribes that value to int smallerNumber 14 | int smallerNumber = Math.min(first, second); 15 | // iterates by gcd and checks if modulo operations by it are equal to 0 16 | for (int gcd = smallerNumber; gcd > 0; gcd--) { 17 | if ((first % gcd == 0) && (second % gcd == 0)) { 18 | return gcd; 19 | } 20 | } 21 | } 22 | return -1; 23 | } 24 | } 25 | 26 | -------------------------------------------------------------------------------- /control-flow-statements/LargestPrime.java: -------------------------------------------------------------------------------- 1 | public class LargestPrime { 2 | 3 | public static void main(String[] args) { 4 | System.out.println(getLargestPrime(21)); 5 | System.out.println(getLargestPrime(217)); 6 | System.out.println(getLargestPrime(0)); 7 | System.out.println(getLargestPrime(45)); 8 | System.out.println(getLargestPrime(-1)); 9 | } 10 | 11 | public static int getLargestPrime(int number) { 12 | if (number >= 2) { 13 | for (int i = 2; i < number; i++) { 14 | if (number % i == 0) { 15 | number /= i; 16 | i--; 17 | } 18 | } 19 | return number; 20 | } 21 | return -1; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /control-flow-statements/LastDigitChecker.java: -------------------------------------------------------------------------------- 1 | public class LastDigitChecker { 2 | 3 | public static void main(String[] args) { 4 | System.out.println(hasSameLastDigit(41, 22, 71)); 5 | System.out.println(hasSameLastDigit(231, 372, 423)); 6 | System.out.println(hasSameLastDigit(91, 991, 532)); 7 | } 8 | 9 | public static boolean hasSameLastDigit (int firstNumber, int secondNumber, int thirdNumber) { 10 | if ((firstNumber >= 10 && firstNumber <= 1000) && (secondNumber >= 10 && secondNumber <= 1000) && (thirdNumber >= 10 && thirdNumber <= 1000)) { 11 | System.out.println("Do any of given numbers (" + firstNumber + ", " + secondNumber + ", " + thirdNumber + ") share a last digit?"); 12 | return ((firstNumber % 10 == secondNumber % 10) || (firstNumber % 10 == thirdNumber % 10) || (secondNumber % 10 == thirdNumber % 10)); 13 | } 14 | System.out.println("Invalid input"); 15 | return false; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /control-flow-statements/MinMaxInputChallenge.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class MinMaxInputChallenge { 4 | 5 | public static void main(String[] args) { 6 | Scanner scanner = new Scanner(System.in); 7 | int min = 0; 8 | int max = 0; 9 | boolean first = true; 10 | 11 | while (true) { 12 | 13 | System.out.println("Enter number:"); 14 | boolean isInt = scanner.hasNextInt(); 15 | 16 | if (isInt) { 17 | int input = scanner.nextInt(); 18 | 19 | if(first) { 20 | first = false; 21 | min = input; 22 | max = input; 23 | } 24 | 25 | if (max < input) { 26 | max = input; 27 | } 28 | 29 | if (min > input) { 30 | min = input; 31 | } 32 | 33 | } else { 34 | break; 35 | } 36 | scanner.nextLine(); // handling end of the line 37 | } 38 | System.out.println("Maximum entered number: " + max); 39 | System.out.println("Minimum entered number: " + min); 40 | scanner.close(); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /control-flow-statements/NumberInWord.java: -------------------------------------------------------------------------------- 1 | public class NumberInWord { 2 | 3 | public static void main(String[] args) { 4 | printNumberInWord(2); 5 | printNumberInWord(-5); 6 | printNumberInWord(9); 7 | printNumberInWord(22); 8 | } 9 | 10 | 11 | public static void printNumberInWord(int number) { 12 | switch (number) { 13 | case 0: 14 | System.out.println("ZERO"); 15 | break; 16 | case 1: 17 | System.out.println("ONE"); 18 | break; 19 | case 2: 20 | System.out.println("TWO"); 21 | break; 22 | case 3: 23 | System.out.println("THREE"); 24 | break; 25 | case 4: 26 | System.out.println("FOUR"); 27 | break; 28 | case 5: 29 | System.out.println("FIVE"); 30 | break; 31 | case 6: 32 | System.out.println("SIX"); 33 | break; 34 | case 7: 35 | System.out.println("SEVEN"); 36 | break; 37 | case 8: 38 | System.out.println("EIGHT"); 39 | break; 40 | case 9: 41 | System.out.println("NINE"); 42 | break; 43 | default: 44 | System.out.println("OTHER"); 45 | break; 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /control-flow-statements/NumberOfDaysInMonths.java: -------------------------------------------------------------------------------- 1 | public class NumberOfDaysInMonths { 2 | 3 | public static void main(String[] args) { 4 | getDaysInMonth(1, 2020); 5 | getDaysInMonth(2, 2020); 6 | getDaysInMonth(2, 2018); 7 | getDaysInMonth(-1, 2020); 8 | getDaysInMonth(1, -2020); 9 | getDaysInMonth(6, 2018); 10 | getDaysInMonth(2, 2019); 11 | getDaysInMonth(9, 2050); 12 | } 13 | 14 | public static boolean isLeapYear(int year) { 15 | if (year > 0 && year <= 9999) { 16 | if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) { 17 | return true; 18 | } else { 19 | return false; 20 | } 21 | } else { 22 | return false; 23 | } 24 | } 25 | 26 | public static int getDaysInMonth(int month, int year) { 27 | if ((month >= 1 && month <= 12) && (year > 0 && year <= 9999)) { 28 | switch (month) { 29 | case 2: 30 | if (isLeapYear(year)) { 31 | System.out.println("February has 29 days in " + year + " because it is a leap year."); 32 | return 29; 33 | } else { 34 | System.out.println("February has 28 days in " + year + " because it is NOT a leap year"); 35 | return 28; 36 | } 37 | case 1: 38 | System.out.println("January has 31 days."); 39 | return 31; 40 | case 3: 41 | System.out.println("March has 31 days."); 42 | return 31; 43 | case 5: 44 | System.out.println("May has 31 days."); 45 | return 31; 46 | case 7: 47 | System.out.println("July has 31 days."); 48 | return 31; 49 | case 8: 50 | System.out.println("August has 31 days."); 51 | return 31; 52 | case 10: 53 | System.out.println("October has 31 days."); 54 | return 31; 55 | case 12: 56 | System.out.println("December has 31 days."); 57 | return 31; 58 | case 4: 59 | System.out.println("April has 30 days."); 60 | return 30; 61 | case 6: 62 | System.out.println("June has 30 days."); 63 | return 30; 64 | case 9: 65 | System.out.println("September has 30 days."); 66 | return 30; 67 | case 11: 68 | System.out.println("November has 30 days."); 69 | return 30; 70 | } 71 | } else { 72 | System.out.println("Invalid input."); 73 | return -1; 74 | } 75 | return month; 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /control-flow-statements/NumberPalindrome.java: -------------------------------------------------------------------------------- 1 | public class NumberPalindrome { 2 | 3 | public static void main(String[] args) { 4 | System.out.println(isPalindrome(-1221)); 5 | System.out.println(isPalindrome(707)); 6 | System.out.println(isPalindrome(11212)); 7 | System.out.println(isPalindrome(55555)); 8 | System.out.println(isPalindrome(334433)); 9 | 10 | } 11 | 12 | public static boolean isPalindrome(int number) { 13 | int input = number; 14 | int originalNumber = number; 15 | int reversedNumber = 0; 16 | int lastDigit; 17 | if (number < 0) { 18 | number = number * (-1); 19 | originalNumber = originalNumber * (-1); 20 | } 21 | while (number > 0) { 22 | // extracting the last digit 23 | lastDigit = number % 10; 24 | // increasing the place value and adding last digit 25 | reversedNumber = reversedNumber * 10 + lastDigit; 26 | // removing last digit from number 27 | number /= 10; 28 | } 29 | System.out.println("Is a given number of " + input + " a palindrome?"); 30 | return reversedNumber == originalNumber; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /control-flow-statements/NumberToWords.java: -------------------------------------------------------------------------------- 1 | public class NumberToWords { 2 | 3 | public static void main(String[] args) { 4 | 5 | System.out.println(getDigitCount(0)); 6 | System.out.println(getDigitCount(123)); 7 | System.out.println(getDigitCount(-12)); 8 | System.out.println(getDigitCount(5200)); 9 | 10 | System.out.println(reverse(-121)); 11 | System.out.println(reverse(1212)); 12 | System.out.println(reverse(1234)); 13 | System.out.println(reverse(1000)); 14 | 15 | numberToWords(123); 16 | numberToWords(1010); 17 | numberToWords(1000); 18 | numberToWords(-12); 19 | 20 | } 21 | 22 | public static void numberToWords(int number) { 23 | if (number >= 0) { 24 | // reversing the number 25 | int reversed = reverse(number); 26 | // counts the number of digits of given number 27 | int originalNumberDigits = getDigitCount(number); 28 | // iterates till all digits will be printed 29 | for (int i = 0; i < originalNumberDigits; i ++) { 30 | // extracting digit of given number 31 | int digit = reversed % 10; 32 | // printing last digit in words 33 | switch (digit) { 34 | case 0: 35 | System.out.println("Zero"); 36 | break; 37 | case 1: 38 | System.out.println("One"); 39 | break; 40 | case 2: 41 | System.out.println("Two"); 42 | break; 43 | case 3: 44 | System.out.println("Three"); 45 | break; 46 | case 4: 47 | System.out.println("Four"); 48 | break; 49 | case 5: 50 | System.out.println("Five"); 51 | break; 52 | case 6: 53 | System.out.println("Six"); 54 | break; 55 | case 7: 56 | System.out.println("Seven"); 57 | break; 58 | case 8: 59 | System.out.println("Eight"); 60 | break; 61 | case 9: 62 | System.out.println("Nine"); 63 | break; 64 | } 65 | // removing digit from a number 66 | reversed /= 10; 67 | } 68 | } else { 69 | // prints "Invalid Value" when it is less than zero 70 | System.out.println("Invalid Value"); 71 | } 72 | } 73 | 74 | // reverses the given number 75 | public static int reverse(int number) { 76 | int reversedNumber = 0; 77 | int lastDigit = 0; 78 | while (number != 0) { 79 | lastDigit = number % 10; 80 | reversedNumber = reversedNumber * 10 + lastDigit; 81 | number /= 10; 82 | } 83 | return reversedNumber; 84 | } 85 | 86 | 87 | // counts the number of digits 88 | public static int getDigitCount(int number) { 89 | int sumOfDigits = 0; 90 | if (number >= 0) { 91 | if (number == 0) { 92 | sumOfDigits = 1; 93 | } 94 | while (number > 0) { 95 | int lastDigit = number % 10; 96 | number /= 10; 97 | sumOfDigits++; 98 | } 99 | return sumOfDigits; 100 | } 101 | return -1; 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /control-flow-statements/ParsingValuesFromString.java: -------------------------------------------------------------------------------- 1 | public class ParsingValuesFromString { 2 | 3 | public static void main(String[] args) { 4 | String numberAsString = "2018.125"; 5 | System.out.println("numberAsString = " + numberAsString); 6 | 7 | double number = Double.parseDouble(numberAsString); // parsing String into Double 8 | System.out.println("number = " + number); 9 | 10 | numberAsString += 1; 11 | number += 1; 12 | 13 | System.out.println("numberAsString = " + numberAsString); // concatenation 14 | System.out.println("number = " + number); // addition 15 | 16 | 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /control-flow-statements/PerfectNumber.java: -------------------------------------------------------------------------------- 1 | public class PerfectNumber { 2 | 3 | public static void main(String[] args) { 4 | System.out.println(isPerfectNumber(6)); 5 | System.out.println(isPerfectNumber(28)); 6 | System.out.println(isPerfectNumber(5)); 7 | System.out.println(isPerfectNumber(-1)); 8 | } 9 | 10 | public static boolean isPerfectNumber(int number) { 11 | int sumOfProperDivisors = 0; 12 | if (number > 0) { 13 | for (int i = 1; i < number; i++) { 14 | int operation = number % i; 15 | if (operation == 0) { 16 | sumOfProperDivisors += i; 17 | } 18 | } 19 | return sumOfProperDivisors == number; 20 | } 21 | return false; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /control-flow-statements/ReadingUserInput.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class ReadingUserInput { 4 | 5 | public static void main(String[] args) { 6 | Scanner scanner = new Scanner(System.in); 7 | System.out.println("Enter your year of birth: "); 8 | 9 | boolean hasNextInt = scanner.hasNextInt(); 10 | if (hasNextInt) { 11 | int yearOfBirth = scanner.nextInt(); 12 | scanner.nextLine(); // handle nextline character (enter key) 13 | 14 | System.out.println("Enter your name: "); 15 | String name = scanner.nextLine(); 16 | 17 | int age = 2018 - yearOfBirth; 18 | 19 | if (age >= 0 && age <= 100) { 20 | System.out.println("Your name is " + name + ", and you are " + age + " years old."); 21 | } else { 22 | System.out.println("Invalid year of birth"); 23 | } 24 | } else { 25 | System.out.println("Unable to parse year of birth."); 26 | } 27 | scanner.close(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /control-flow-statements/ReadingUserInputChallenge.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class ReadingUserInputChallenge { 4 | 5 | public static void main(String[] args) { 6 | Scanner scanner = new Scanner(System.in); 7 | int enteredNumbers = 0; 8 | int sumOfEnteredNumbers = 0; 9 | 10 | 11 | while (enteredNumbers < 10) { 12 | int inputOrder = enteredNumbers + 1; 13 | System.out.println("Enter the number #" + inputOrder + ":"); 14 | 15 | boolean isInt = scanner.hasNextInt(); 16 | 17 | if (isInt) { 18 | int number = scanner.nextInt(); 19 | enteredNumbers++; 20 | sumOfEnteredNumbers += number; 21 | } else { 22 | System.out.println("Invalid Number"); 23 | } 24 | scanner.nextLine(); // handling end of the line 25 | } 26 | System.out.println("Sum of entered numbers " + sumOfEnteredNumbers); 27 | scanner.close(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /control-flow-statements/SharedDigit.java: -------------------------------------------------------------------------------- 1 | public class SharedDigit { 2 | 3 | public static void main(String[] args) { 4 | System.out.println(hasSharedDigit(12, 23)); 5 | System.out.println(hasSharedDigit(9, 90)); 6 | System.out.println(hasSharedDigit(15, 55)); 7 | System.out.println(hasSharedDigit(12, 93)); 8 | System.out.println(hasSharedDigit(77, 17)); 9 | } 10 | 11 | 12 | public static boolean hasSharedDigit(int firstNumber, int secondNumber) { 13 | if ((firstNumber >= 10 && firstNumber <= 99) && (secondNumber >= 10 && secondNumber <= 99)) { 14 | int firstNumberLastDigit = firstNumber % 10; 15 | int secondNumberLastDigit = secondNumber % 10; 16 | firstNumber /= 10; 17 | secondNumber /= 10; 18 | int firstNumberFirstDigit = firstNumber; 19 | int secondNumberFirstDigit = secondNumber; 20 | System.out.println("Is there any shared digit in both given numbers?"); 21 | return ((firstNumberFirstDigit == secondNumberFirstDigit) || (firstNumberFirstDigit == secondNumberLastDigit) || (firstNumberLastDigit == secondNumberFirstDigit) || (firstNumberLastDigit == secondNumberLastDigit)); 22 | } 23 | System.out.println("Invalid input."); 24 | return false; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /control-flow-statements/Sum3And5Challenge.java: -------------------------------------------------------------------------------- 1 | public class Sum3And5Challenge { 2 | 3 | public static void main(String[] args) { 4 | 5 | long sumOfTheNumbers = 0; 6 | int count = 0; 7 | System.out.println("Here's the list of the first five numbers divisible by 3 and 5 (starting from 1):"); 8 | for (int i = 1; i <= 1000; i++) { 9 | if ((i % 3 == 0) && (i % 5 == 0)) { 10 | System.out.println(i); 11 | sumOfTheNumbers = sumOfTheNumbers + i; 12 | count++; 13 | if (count == 5) { 14 | break; 15 | } 16 | } 17 | } 18 | System.out.println("And the sum of all of them is " + sumOfTheNumbers + "."); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /control-flow-statements/SumOddRange.java: -------------------------------------------------------------------------------- 1 | public class SumOddRange { 2 | 3 | public static void main(String[] args) { 4 | // program returns the sum of the odd numbers between a given range or -1 if the input is invalid 5 | System.out.println(sumOdd(1, 100)); 6 | System.out.println(sumOdd(-1, 100)); 7 | System.out.println(sumOdd(100, 100)); 8 | System.out.println(sumOdd(100, -100)); 9 | System.out.println(sumOdd(100, 1000)); 10 | System.out.println(sumOdd(10, 5)); 11 | } 12 | 13 | public static boolean isOdd(int number) { 14 | if ((number > 0) && (number % 2 != 0)) { 15 | return true; 16 | } 17 | return false; 18 | } 19 | 20 | public static int sumOdd(int start, int end) { 21 | int sumOfTheOddNumbers = 0; 22 | if (start > 0 && end > 0 && end >= start) { 23 | for (int i = start; i <= end; i++) { 24 | if (isOdd(i)) { 25 | sumOfTheOddNumbers = sumOfTheOddNumbers + i; 26 | } 27 | } 28 | return sumOfTheOddNumbers; 29 | } else { 30 | return -1; 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /control-flow-statements/Switch.java: -------------------------------------------------------------------------------- 1 | public class Switch { 2 | 3 | public static void main(String[] args) { 4 | 5 | int switchValue = 7; 6 | switch (switchValue) { 7 | case 1: 8 | System.out.println("Value was 1"); 9 | break; 10 | case 2: 11 | System.out.println("Value was 2"); 12 | break; 13 | case 3: 14 | case 4: 15 | case 5: 16 | case 6: 17 | System.out.println("Value was 3, 4, 5 or 6"); 18 | System.out.println("Actually it was " + switchValue); 19 | break; 20 | 21 | default: 22 | System.out.println("Value was not 1, 2, 3, 4, 5 or 6"); 23 | break; 24 | } 25 | 26 | 27 | char riterka = 'D'; 28 | switch (riterka) { 29 | case 'A': 30 | case 'B': 31 | case 'C': 32 | case 'D': 33 | case 'E': 34 | System.out.println(riterka + " was found!"); 35 | break; 36 | default: 37 | System.out.println("Nothing was found."); 38 | break; 39 | } 40 | 41 | String day = "tuESdAy"; 42 | switch (day.toLowerCase()) { 43 | case "monday": 44 | case "tuesday": 45 | case "wednesday": 46 | case "thursday": 47 | case "friday": 48 | case "saturday": 49 | case "sunday": 50 | System.out.println("Today is " + day.toLowerCase()); 51 | break; 52 | default: 53 | System.out.println("Invalid data."); 54 | break; 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /control-flow-statements/UserInputTraining.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | // training exercise 4 | public class UserInputTraining { 5 | 6 | public static void main(String[] args) { 7 | int enteredNumbers = 0; 8 | int sum = 0; 9 | 10 | System.out.println("How many number would you like to enter?"); 11 | Scanner scanner = new Scanner(System.in); 12 | 13 | int numbersToEnter = scanner.nextInt(); 14 | 15 | while (enteredNumbers < numbersToEnter) { 16 | int counter = enteredNumbers + 1; 17 | System.out.println("Enter the number #" + counter); 18 | 19 | boolean isValidInt = scanner.hasNextInt(); 20 | 21 | if (isValidInt) { 22 | int number = scanner.nextInt(); 23 | enteredNumbers++; 24 | sum += number; 25 | } else { 26 | System.out.println("Invalid input."); 27 | } 28 | scanner.nextLine(); // handling enter key 29 | } 30 | System.out.println("The sum of the " + numbersToEnter + " entered numbers is " + sum + "."); 31 | scanner.close(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /control-flow-statements/WhileAndDoWhile.java: -------------------------------------------------------------------------------- 1 | public class WhileAndDoWhile { 2 | 3 | public static void main(String[] args) { 4 | // while loop 5 | int count = 1; 6 | while (count != 6) { 7 | System.out.println("Count value is " + count); 8 | count++; 9 | } 10 | 11 | System.out.println("\n\n"); 12 | 13 | count = 1; // re-setting the value of count to 1 14 | while (true) { 15 | if (count == 6) { 16 | break; 17 | } 18 | System.out.println("Count value is " + count); 19 | count++; 20 | } 21 | 22 | System.out.println("\n\n"); 23 | 24 | // do-while loop 25 | count = 1; // re-setting the value of count to 1 26 | do { // do-while executes at least once! 27 | System.out.println("Count value was " + count); 28 | count++; 29 | if (count > 100) { 30 | break; 31 | } 32 | } while (count != 6); 33 | 34 | System.out.println("\n\n"); 35 | 36 | // Challenge: prints first five even number between a given range (4-20), print them, sum them up and print the result as well 37 | 38 | int number = 4; 39 | int startingNumber = number; 40 | int finishNumber = 20; 41 | int sumOfEvenNumbers = 0; 42 | int foundNumbers = 0; 43 | 44 | while (number <= finishNumber) { 45 | number++; 46 | if (!isEvenNumber(number)) { 47 | continue; 48 | } 49 | System.out.println("Even number " + number); 50 | sumOfEvenNumbers = sumOfEvenNumbers + number; 51 | foundNumbers++; 52 | if (foundNumbers == 5) { 53 | break; 54 | } 55 | } 56 | System.out.println("Found " + foundNumbers + " even numbers."); 57 | System.out.println("Sum of the first " + foundNumbers + " even numbers within the range of " + startingNumber + "-" + finishNumber + " is " + sumOfEvenNumbers + "."); 58 | } 59 | 60 | // method that checks whether a given number is an even number 61 | public static boolean isEvenNumber(int number) { 62 | if (number % 2 == 0) { 63 | return true; 64 | } 65 | return false; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /expressions-statements-methods/AreaCalculator.java: -------------------------------------------------------------------------------- 1 | public class AreaCalculator { 2 | 3 | public static void main(String[] args) { 4 | area(5.0); 5 | area(-1); 6 | area(5.0, 4.0); 7 | area(-1.0, 4.0); 8 | } 9 | 10 | public static double area(double radius) { 11 | final double PI = 3.14159; 12 | if (radius >= 0) { 13 | radius = radius * radius * PI; 14 | System.out.println(radius); 15 | return radius; 16 | } else { 17 | System.out.println("-1"); 18 | return -1; 19 | } 20 | } 21 | 22 | public static double area(double x, double y) { 23 | if (x >= 0 && y >= 0) { 24 | double calculatedArea = x * y; 25 | System.out.println(calculatedArea); 26 | return calculatedArea; 27 | } else { 28 | System.out.println("-1"); 29 | return -1; 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /expressions-statements-methods/BarkingDog.java: -------------------------------------------------------------------------------- 1 | public class BarkingDog { 2 | 3 | public static void main(String[] args) { 4 | bark(true, 1); 5 | bark(false, 2); 6 | bark(true, 8); 7 | bark(true, -1); 8 | } 9 | 10 | public static boolean bark(boolean barking, int hourOfDay) { 11 | if (barking && hourOfDay >= 0 && hourOfDay <= 23) { 12 | if (hourOfDay < 8 || hourOfDay > 22) { 13 | System.out.println("true"); 14 | return true; 15 | } 16 | System.out.println("false"); 17 | return false; 18 | } else { 19 | System.out.println("false"); 20 | return false; 21 | 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /expressions-statements-methods/CheckNumber.java: -------------------------------------------------------------------------------- 1 | public class CheckNumber { 2 | 3 | public static void main(String[] args) { 4 | checkNumber(10); 5 | checkNumber(-2); 6 | checkNumber(0); 7 | } 8 | 9 | public static void checkNumber(int number) { 10 | if (number > 0) { 11 | System.out.println("positive"); 12 | } else if (number < 0) { 13 | System.out.println("negative"); 14 | } else if (number == 0) { 15 | System.out.println("zero"); 16 | } 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /expressions-statements-methods/DecimalComparator.java: -------------------------------------------------------------------------------- 1 | public class DecimalComparator { 2 | 3 | public static void main(String[] args) { 4 | areEqualByThreeDecimalPlaces(-3.1756, -3.175); 5 | areEqualByThreeDecimalPlaces(3.175, 3.176); 6 | areEqualByThreeDecimalPlaces(3.0, 3.0); 7 | } 8 | 9 | public static boolean areEqualByThreeDecimalPlaces(double firstNumber, double secondNumber) { 10 | 11 | if ((int) (firstNumber * 1000) == (int) (secondNumber * 1000)) { 12 | return true; 13 | } else { 14 | return false; 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /expressions-statements-methods/EqualSumChecker.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void EqualSumChecker(String[] args) { 4 | hasEqualSum(2, 3, 4); 5 | hasEqualSum(2, 2, 4); 6 | } 7 | 8 | public static boolean hasEqualSum (int firstNumber, int secondNumber, int thirdNumber) { 9 | if((firstNumber + secondNumber) == thirdNumber) { 10 | return true; 11 | } else { 12 | return false; 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /expressions-statements-methods/GallonCalc.java: -------------------------------------------------------------------------------- 1 | public class GallonCalc { 2 | 3 | public static void main(String[] args) { 4 | toQuartsAndGallons(32); 5 | } 6 | 7 | public static double toQuartsAndGallons (double USLiquidQuart, double imperialQuart) { 8 | double USLiquidGallon = USLiquidQuart / 4; 9 | double imperialGallon = imperialQuart / 4; 10 | System.out.println(USLiquidQuart + " US liquid quarts is " + USLiquidGallon + " US liquid gallons."); 11 | System.out.println(imperialQuart + " imperial quarts is " + imperialGallon + " imperial gallons."); 12 | return USLiquidGallon; 13 | } 14 | 15 | public static double toQuartsAndGallons (double litres) { 16 | if (litres >= 0) { 17 | double USLiquidQuart = litres * 0.946d; 18 | double imperialQuart = litres * 1.136d; 19 | System.out.println(litres + " litres is " + USLiquidQuart + " US liquid quarts."); 20 | System.out.println(litres + " litres is " + imperialQuart + " imperial quarts."); 21 | return toQuartsAndGallons(USLiquidQuart, imperialQuart); 22 | } else { 23 | System.out.println("Invalid input."); 24 | return -1; 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /expressions-statements-methods/IfKeywordAndCodeBlocks.java: -------------------------------------------------------------------------------- 1 | public class IfKeywordAndCodeBlocks { 2 | 3 | public static void main(String[] args) { 4 | boolean gameOver = true; 5 | int score = 300; 6 | int levelCompleted = 5; 7 | int bonus = 100; 8 | 9 | int secondScore = 10000; 10 | int secondLevelCompleted = 8; 11 | int secondBonus = 200; 12 | 13 | if(gameOver) { 14 | int finalScore = score + (levelCompleted * bonus); 15 | int secondFinalScore = secondScore + (secondLevelCompleted * secondBonus); 16 | System.out.println("Final score was " + finalScore + ", and second final score was " + secondFinalScore); 17 | } 18 | 19 | 20 | if(score < 5000 && score>1000) { 21 | System.out.println("Your score was less than 5000 but greater than 1000"); 22 | } else if (score < 1000){ 23 | System.out.println("Your score was less than 1000"); 24 | } else { 25 | System.out.println("Got here"); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /expressions-statements-methods/LeapYear.java: -------------------------------------------------------------------------------- 1 | public class LeapYear { 2 | 3 | public static void main(String[] args) { 4 | isLeapYear(-2); 5 | isLeapYear(1600); 6 | isLeapYear(2017); 7 | isLeapYear(2000); 8 | } 9 | 10 | public static boolean isLeapYear(int year) { 11 | if (year >= 1 && year <= 9999) { 12 | if ((year % 4 == 0) && (year % 100 != 0) || year % 400 == 0) { 13 | return true; 14 | } else { 15 | return false; 16 | } 17 | } else { 18 | return false; 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /expressions-statements-methods/MegabytesConverter.java: -------------------------------------------------------------------------------- 1 | public class MegabytesConverter { 2 | 3 | public static void main(String[] args) { 4 | printMegaBytesAndKiloBytes(2048); 5 | printMegaBytesAndKiloBytes(12321312); 6 | printMegaBytesAndKiloBytes(-213); 7 | } 8 | 9 | public static void printMegaBytesAndKiloBytes(int kiloBytes) { 10 | if (kiloBytes < 0) { 11 | System.out.println("Invalid Value"); 12 | } else { 13 | int megaBytes = kiloBytes / 1024; 14 | int remainder = kiloBytes % 1024; 15 | System.out.println(kiloBytes + " KB = " + megaBytes + " MB and " + remainder + " KB"); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /expressions-statements-methods/MethodOverloading.java: -------------------------------------------------------------------------------- 1 | public class MethodOverloading { 2 | 3 | public static void main(String[] args) { 4 | int newScore = calculateScore("Michał", 20); 5 | System.out.println("New score is " + newScore); 6 | calculateScore(500); 7 | 8 | calcFeetAndInchesToCentimeters(157); 9 | } 10 | 11 | 12 | public static int calculateScore(String playerName, int score) { 13 | System.out.println("Player " + playerName + " scored " + score + " points."); 14 | return score * 1000; 15 | } 16 | 17 | public static int calculateScore(int score) { 18 | System.out.println("Unnamed player scored " + score + " points."); 19 | return score * 1000; 20 | } 21 | 22 | public static double calcFeetAndInchesToCentimeters (double feet, double inches) { 23 | if (feet >=0 && inches >= 0 && inches <= 12) { 24 | double centimeters = (feet * 12) * 2.54; 25 | centimeters += inches * 2.54; 26 | System.out.println(feet + " feet, " + inches + " inches = " + centimeters + " cm."); 27 | return centimeters; 28 | } else { 29 | return -1; 30 | } 31 | } 32 | 33 | public static double calcFeetAndInchesToCentimeters (double inches) { 34 | if (inches >= 0) { 35 | double feet = (int) inches / 12; 36 | double remainingInches = (int) inches % 12; 37 | System.out.println(inches + " inches is equal to " + feet + " feet and " + remainingInches + " inches."); 38 | return calcFeetAndInchesToCentimeters(feet, remainingInches); 39 | } else { 40 | return -1; 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /expressions-statements-methods/Methods.java: -------------------------------------------------------------------------------- 1 | public class Methods { 2 | 3 | public static void main(String[] args) { 4 | 5 | int highScore = calculateScore(true, 800, 5, 100); 6 | System.out.println("Final score is " + highScore); 7 | highScore = calculateScore(true, 10000, 8, 200); 8 | System.out.println("Second final score is " + highScore); 9 | 10 | int highScorePosition = calculateHighScorePosition(1340); 11 | displayHighScorePosition("Michał", highScorePosition); 12 | 13 | highScorePosition = calculateHighScorePosition(900); 14 | displayHighScorePosition("Paweł", highScorePosition); 15 | 16 | highScorePosition = calculateHighScorePosition(400); 17 | displayHighScorePosition("Robert", highScorePosition); 18 | 19 | highScorePosition = calculateHighScorePosition(1000); 20 | displayHighScorePosition("Wojciech", highScorePosition); 21 | 22 | highScorePosition = calculateHighScorePosition(22); 23 | displayHighScorePosition("Olaf", highScorePosition); 24 | 25 | } 26 | 27 | public static int calculateScore(boolean gameOver, int score, int levelCompleted, int bonus) { 28 | 29 | if (gameOver) { 30 | int finalScore = score + (levelCompleted * bonus); 31 | finalScore += 2000; 32 | return finalScore; 33 | } else { 34 | return -1; 35 | } 36 | } 37 | 38 | 39 | // Challenge 40 | 41 | 42 | 43 | public static void displayHighScorePosition(String playerName, int playerPosition) { 44 | System.out.println(playerName + " managed to get into position " + playerPosition + " on the high score table."); 45 | } 46 | 47 | public static int calculateHighScorePosition(int playerScore) { 48 | if(playerScore >= 1000) { 49 | return 1; 50 | } else if (playerScore >= 500) { 51 | return 2; 52 | } else if (playerScore >= 100) { 53 | return 3; 54 | } 55 | 56 | return 4; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /expressions-statements-methods/MinutesYearsDaysCalc.java: -------------------------------------------------------------------------------- 1 | public class MinutesYearsDaysCalc { 2 | 3 | public static void main(String[] args) { 4 | printYearsAndDays(525600); 5 | printYearsAndDays(1051200); 6 | printYearsAndDays(561600); 7 | } 8 | 9 | public static void printYearsAndDays (long minutes) { 10 | if (minutes >= 0) { 11 | long days = (minutes / 60) / 24; 12 | long remainingDays = days % 365; 13 | long years = days / 365; 14 | System.out.println(minutes + " min = " + years + " y and " + remainingDays + " d"); 15 | } else { 16 | System.out.println("Invalid Value"); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /expressions-statements-methods/PlayingCat.java: -------------------------------------------------------------------------------- 1 | public class PlayingCat { 2 | 3 | public static void main(String[] args) { 4 | isCatPlaying(true, 10); 5 | isCatPlaying(false, 36); 6 | isCatPlaying(false, 35); 7 | } 8 | 9 | public static boolean isCatPlaying (boolean summer, int temperature) { 10 | if ((summer && temperature >= 25 && temperature <= 45) || (summer == false && temperature >= 25 && temperature <= 35)) { 11 | System.out.println("true"); 12 | return true; 13 | } else { 14 | System.out.println("false"); 15 | return false; 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /expressions-statements-methods/SecondsMinutesHours.java: -------------------------------------------------------------------------------- 1 | public class SecondsMinutesHours { 2 | 3 | public static void main(String[] args) { 4 | String duration = getDurationString(222222222); 5 | System.out.println(duration); 6 | } 7 | 8 | public static String getDurationString(int minutes, int seconds) { 9 | if (minutes >= 0 && seconds >= 0 && seconds <= 59) { 10 | int hours = minutes / 60; 11 | int remainingMinutes = minutes % 60; 12 | int remainingSeconds = seconds % 60; 13 | return (hours + "h " + remainingMinutes + "m " + remainingSeconds + "s"); 14 | } else { 15 | return "Invalid value"; 16 | } 17 | } 18 | 19 | public static String getDurationString (int seconds) { 20 | if (seconds >= 0) { 21 | int minutes = seconds / 60; 22 | int remainingSeconds = seconds % 60; 23 | return getDurationString(minutes, remainingSeconds); 24 | } else { 25 | return "Invalid value"; 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /expressions-statements-methods/TeenNumberChecker.java: -------------------------------------------------------------------------------- 1 | public class TeenNumberChecker { 2 | 3 | public static void main(String[] args) { 4 | hasTeen(9,99,19); 5 | hasTeen(23,15,42); 6 | hasTeen(22,23,24); 7 | } 8 | 9 | public static boolean hasTeen (int firstNumber, int secondNumber, int thirdNumber) { 10 | if(firstNumber >= 13 && firstNumber <= 19) { 11 | return true; 12 | } else if (secondNumber >= 13 && secondNumber <=19) { 13 | System.out.println("True"); 14 | return true; 15 | } else if (thirdNumber >= 13 && thirdNumber <=19) { 16 | System.out.println("True"); 17 | return true; 18 | } else { 19 | System.out.println("False"); 20 | return false; 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /inner-abstract-classes-interfaces/abstract-classes/Animal.java: -------------------------------------------------------------------------------- 1 | 2 | public abstract class Animal { 3 | private String name; 4 | 5 | // constructor 6 | public Animal(String name) { 7 | this.name = name; 8 | } 9 | 10 | // abstract methods 11 | public abstract void eat(); 12 | public abstract void breathe(); 13 | 14 | // getter 15 | public String getName() { 16 | return name; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /inner-abstract-classes-interfaces/abstract-classes/Bird.java: -------------------------------------------------------------------------------- 1 | 2 | public abstract class Bird extends Animal implements CanFly { 3 | // calling constructor from parent class using 'super' keyword 4 | public Bird(String name) { 5 | super(name); 6 | } 7 | 8 | // overriding eat() method 9 | @Override 10 | public void eat() { 11 | System.out.println(getName() + " pecks"); 12 | } 13 | 14 | // overriding breathe() method 15 | @Override 16 | public void breathe() { 17 | System.out.println("Breathe in, breathe out."); 18 | } 19 | 20 | @Override 21 | public void fly() { 22 | System.out.println(getName() + " is flapping its wings!"); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /inner-abstract-classes-interfaces/abstract-classes/CanFly.java: -------------------------------------------------------------------------------- 1 | public interface CanFly { 2 | void fly(); 3 | } 4 | -------------------------------------------------------------------------------- /inner-abstract-classes-interfaces/abstract-classes/Cat.java: -------------------------------------------------------------------------------- 1 | public class Cat extends Animal { 2 | public Cat(String name) { 3 | super(name); 4 | } 5 | 6 | @Override 7 | public void eat() { 8 | System.out.println(getName() + " meows firstly and then eats."); 9 | } 10 | 11 | @Override 12 | public void breathe() { 13 | System.out.println(getName() + " breathes so quietly."); 14 | } 15 | 16 | public void meow() { 17 | System.out.println("Meooowwww!"); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /inner-abstract-classes-interfaces/abstract-classes/Dog.java: -------------------------------------------------------------------------------- 1 | public class Dog extends Animal { 2 | 3 | // calling constructor from parent class 4 | public Dog(String name) { 5 | super(name); 6 | } 7 | 8 | // overriding eat() method 9 | @Override 10 | public void eat() { 11 | System.out.println(getName() + " chews"); 12 | } 13 | 14 | // overriding breathe() method 15 | @Override 16 | public void breathe() { 17 | System.out.println("Breathe in, breathe out. "); 18 | } 19 | 20 | public void bark() { 21 | System.out.println(getName() + " is barking!"); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /inner-abstract-classes-interfaces/abstract-classes/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | Dog dog = new Dog("Odys"); 5 | dog.breathe(); 6 | dog.eat(); 7 | dog.bark(); 8 | 9 | Parrot parrot = new Parrot("Polly"); 10 | parrot.breathe(); 11 | parrot.eat(); 12 | parrot.fly(); 13 | 14 | Penguin penguin = new Penguin("Emperor"); 15 | penguin.fly(); 16 | 17 | Cat myCat = new Cat("Parys"); 18 | myCat.meow(); 19 | myCat.eat(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /inner-abstract-classes-interfaces/abstract-classes/Parrot.java: -------------------------------------------------------------------------------- 1 | public class Parrot extends Bird { 2 | 3 | // calling constructor from parent class 4 | public Parrot(String name) { 5 | super(name); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /inner-abstract-classes-interfaces/abstract-classes/Penguin.java: -------------------------------------------------------------------------------- 1 | public class Penguin extends Bird { 2 | // calling constructor from parent class 3 | public Penguin(String name) { 4 | super(name); 5 | } 6 | 7 | // overriding fly() method 8 | @Override 9 | public void fly() { 10 | System.out.println("I'm not very good at that, can I go for a swim instead?"); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /inner-abstract-classes-interfaces/inner-classes/Gearbox.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class Gearbox { 4 | private ArrayList gears; 5 | private int maxGears; 6 | private int currentGear = 0; 7 | private boolean clutchIsIn; 8 | 9 | public Gearbox(int maxGears) { 10 | this.maxGears = maxGears; 11 | this.gears = new ArrayList<>(); 12 | Gear neutral = new Gear(0, 0.0); 13 | this.gears.add(neutral); 14 | } 15 | 16 | public void operateClutch(boolean in) { 17 | this.clutchIsIn = in; 18 | } 19 | 20 | public void addGear(int newGear) { 21 | if ((newGear >= 0) && newGear < this.gears.size() && this.clutchIsIn) { 22 | this.currentGear = newGear; 23 | System.out.println("Gear " + newGear + " selected."); 24 | } else { 25 | System.out.println("Grind!"); 26 | this.currentGear = 0; 27 | } 28 | } 29 | 30 | public double wheelSpeed(int revs) { 31 | if (clutchIsIn) { 32 | System.out.println("Scream!"); 33 | return 0.0; 34 | } 35 | return revs * gears.get(currentGear).getRatio(); 36 | } 37 | 38 | 39 | public class Gear { 40 | private int gearNumber; 41 | private double ratio; 42 | 43 | public Gear(int gearNumber, double ratio) { 44 | this.gearNumber = gearNumber; 45 | this.ratio = ratio; 46 | } 47 | 48 | public double getRatio() { 49 | return ratio; 50 | } 51 | 52 | public double driveSpeed(int revs) { 53 | return revs * (this.ratio); 54 | } 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /inner-abstract-classes-interfaces/inner-classes/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | Gearbox mcLaren = new Gearbox(6); 5 | Gearbox.Gear first = mcLaren.new Gear(1, 12.3); 6 | System.out.println(first.driveSpeed(1000)); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /inner-abstract-classes-interfaces/interface-challenge/ISaveable.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | 3 | public interface ISaveable { 4 | List write(); 5 | void read(List savedValues); 6 | 7 | 8 | } 9 | -------------------------------------------------------------------------------- /inner-abstract-classes-interfaces/interface-challenge/Main.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Scanner; 3 | 4 | public class Main { 5 | 6 | public static void main(String[] args) { 7 | 8 | Player johnnyCash = new Player("Johnny Cash", 10, 15); 9 | System.out.println(johnnyCash.toString()); 10 | saveObject(johnnyCash); 11 | 12 | ISaveable werewolf = new Monster("Werewolf", 20, 80); 13 | saveObject(werewolf); 14 | 15 | } 16 | 17 | public static ArrayList readValues() { 18 | ArrayList values = new ArrayList<>(); 19 | 20 | Scanner scanner = new Scanner(System.in); 21 | boolean quit = false; 22 | int index = 0; 23 | System.out.println("Choose\n" + 24 | "1 to enter a String\n" + 25 | "0 to quit"); 26 | 27 | while (!quit) { 28 | System.out.println("Choose an option: "); 29 | // assigns the value of scanner to a variable "choice" 30 | int choice = scanner.nextInt(); 31 | // consuming last newline character 32 | scanner.nextLine(); 33 | 34 | switch (choice) { 35 | case 0: 36 | quit = true; 37 | break; 38 | case 1: 39 | System.out.println("Enter a String: "); 40 | // assigns the value of scanner to a variable "stringInput" 41 | String stringInput = scanner.nextLine(); 42 | values.add(index, stringInput); 43 | index++; 44 | break; 45 | } 46 | } 47 | return values; 48 | } 49 | 50 | public static void saveObject(ISaveable objectToSave) { 51 | for (int i = 0; i < objectToSave.write().size(); i++) { 52 | System.out.println("Saving " + objectToSave.write().get(i) + " to storage device."); 53 | } 54 | } 55 | 56 | public static void loadObject(ISaveable objectToLoad) { 57 | ArrayList values = readValues(); 58 | objectToLoad.read(values); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /inner-abstract-classes-interfaces/interface-challenge/Monster.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | public class Monster implements ISaveable { 5 | private String name; 6 | private int hitPoints; 7 | private int strength; 8 | 9 | public Monster(String name, int hitPoints, int strength) { 10 | this.name = name; 11 | this.hitPoints = hitPoints; 12 | this.strength = strength; 13 | } 14 | 15 | public String getName() { 16 | return name; 17 | } 18 | 19 | public int getHitPoints() { 20 | return hitPoints; 21 | } 22 | 23 | public int getStrength() { 24 | return strength; 25 | } 26 | 27 | @Override 28 | public List write() { 29 | ArrayList values = new ArrayList<>(); 30 | values.add(0, this.name); 31 | values.add(1, "" + this.hitPoints); 32 | values.add(2, "" + this.strength); 33 | return values; 34 | } 35 | 36 | @Override 37 | public void read(List savedValues) { 38 | if (savedValues != null && savedValues.size() > 0) { 39 | this.name = savedValues.get(0); 40 | this.hitPoints = Integer.parseInt(savedValues.get(1)); 41 | this.strength = Integer.parseInt(savedValues.get(2)); 42 | } 43 | } 44 | 45 | @Override 46 | public String toString() { 47 | return "Monster{" + 48 | "name='" + name + '\'' + 49 | ", hitPoints=" + hitPoints + 50 | ", strength=" + strength + 51 | '}'; 52 | } 53 | 54 | 55 | } 56 | -------------------------------------------------------------------------------- /inner-abstract-classes-interfaces/interface-challenge/Player.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | public class Player implements ISaveable { 5 | private String name; 6 | private int hitPoints; 7 | private int strength; 8 | private String weapon; 9 | 10 | public Player(String name, int hitPoints, int strength) { 11 | this.name = name; 12 | this.hitPoints = hitPoints; 13 | this.strength = strength; 14 | this.weapon = "sword"; 15 | } 16 | 17 | public String getName() { 18 | return name; 19 | } 20 | 21 | public void setName(String name) { 22 | this.name = name; 23 | } 24 | 25 | public int getHitPoints() { 26 | return hitPoints; 27 | } 28 | 29 | public void setHitPoints(int hitPoints) { 30 | this.hitPoints = hitPoints; 31 | } 32 | 33 | public int getStrength() { 34 | return strength; 35 | } 36 | 37 | public void setStrength(int strength) { 38 | this.strength = strength; 39 | } 40 | 41 | public String getWeapon() { 42 | return weapon; 43 | } 44 | 45 | public void setWeapon(String weapon) { 46 | this.weapon = weapon; 47 | } 48 | 49 | @Override 50 | public String toString() { 51 | return "Player{" + 52 | "name='" + name + '\'' + 53 | ", hitPoints=" + hitPoints + 54 | ", strength=" + strength + 55 | ", weapon='" + weapon + '\'' + 56 | '}'; 57 | } 58 | 59 | @Override 60 | public List write() { 61 | List values = new ArrayList<>(); 62 | values.add(0, this.name); 63 | values.add(1, "" + this.hitPoints); 64 | values.add(2, "" + this.strength); 65 | values.add(3, this.weapon); 66 | 67 | return values; 68 | } 69 | 70 | @Override 71 | public void read(List savedValues) { 72 | if (savedValues != null && savedValues.size() > 0) { 73 | this.name = savedValues.get(0); 74 | this.hitPoints = Integer.parseInt(savedValues.get(1)); 75 | this.strength = Integer.parseInt(savedValues.get(2)); 76 | this.weapon = savedValues.get(3); 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /inner-abstract-classes-interfaces/interfaces/DeskPhone.java: -------------------------------------------------------------------------------- 1 | public class DeskPhone implements ITelephone { 2 | private int myNumber; 3 | private boolean isRinging; 4 | 5 | public DeskPhone(int myNumber) { 6 | this.myNumber = myNumber; 7 | } 8 | 9 | @Override 10 | public void powerOn() { 11 | System.out.println("No action taken, deskphone does not have a power button"); 12 | } 13 | 14 | @Override 15 | public void dial(int phoneNumber) { 16 | System.out.println("Now ringing " + phoneNumber + " on deskphone"); 17 | } 18 | 19 | @Override 20 | public void answer() { 21 | if (isRinging) { 22 | System.out.println("Answering the deskphone"); 23 | isRinging = false; 24 | } 25 | 26 | } 27 | 28 | @Override 29 | public boolean callPhone(int phoneNumber) { 30 | if (phoneNumber == myNumber) { 31 | isRinging = true; 32 | System.out.println("Ring ring"); 33 | } else { 34 | isRinging = false; 35 | } 36 | return isRinging; 37 | } 38 | 39 | @Override 40 | public boolean isRinging() { 41 | return isRinging; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /inner-abstract-classes-interfaces/interfaces/ITelephone.java: -------------------------------------------------------------------------------- 1 | public interface ITelephone { 2 | void powerOn(); 3 | 4 | void dial(int phoneNumber); 5 | 6 | void answer(); 7 | 8 | boolean callPhone(int phoneNumber); 9 | 10 | boolean isRinging(); 11 | 12 | } 13 | -------------------------------------------------------------------------------- /inner-abstract-classes-interfaces/interfaces/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | ITelephone myPhone; 5 | myPhone = new DeskPhone(332211); 6 | myPhone.powerOn(); 7 | myPhone.callPhone(332211); 8 | myPhone.answer(); 9 | 10 | myPhone = new MobilePhone(12345); 11 | myPhone.powerOn(); 12 | myPhone.callPhone(12345); 13 | myPhone.answer(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /inner-abstract-classes-interfaces/interfaces/MobilePhone.java: -------------------------------------------------------------------------------- 1 | public class MobilePhone implements ITelephone { 2 | private int myNumber; 3 | private boolean isRinging; 4 | private boolean isOn = false; 5 | 6 | public MobilePhone(int myNumber) { 7 | this.myNumber = myNumber; 8 | } 9 | 10 | @Override 11 | public void powerOn() { 12 | isOn = true; 13 | System.out.println("Mobile phone powered up"); 14 | } 15 | 16 | @Override 17 | public void dial(int phoneNumber) { 18 | if(isOn) { 19 | System.out.println("Now ringing " + phoneNumber + " on mobile phone"); 20 | } else { 21 | System.out.println("Phone is switched off"); 22 | } 23 | } 24 | 25 | @Override 26 | public void answer() { 27 | if (isRinging) { 28 | System.out.println("Answering the mobile phone"); 29 | isRinging = false; 30 | } 31 | 32 | } 33 | 34 | @Override 35 | public boolean callPhone(int phoneNumber) { 36 | if (phoneNumber == myNumber && isOn) { 37 | isRinging = true; 38 | System.out.println("Melody playing"); 39 | } else { 40 | isRinging = false; 41 | System.out.println("Mobile phone not on or number different"); 42 | } 43 | return isRinging; 44 | } 45 | 46 | @Override 47 | public boolean isRinging() { 48 | return isRinging; 49 | } 50 | } -------------------------------------------------------------------------------- /variables-datatypes-operators/CharAndBoolean.java: -------------------------------------------------------------------------------- 1 | public class CharAndBoolean { 2 | 3 | public static void main(String[] args) { 4 | char myChar = '\u00A7'; 5 | System.out.println(myChar); 6 | 7 | boolean myBoolean = true; 8 | boolean isMale = true; 9 | 10 | // Challenge 11 | char registeredSymbol = '\u00AE'; 12 | System.out.println(registeredSymbol); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /variables-datatypes-operators/FloatAndDouble.java: -------------------------------------------------------------------------------- 1 | public class FloatAndDouble { 2 | 3 | public static void main(String[] args) { 4 | int myIntValue = 5 / 3; 5 | float myFloatValue = 5f / 3f; 6 | double myDoubleValue = 5d / 3d; 7 | 8 | System.out.println("myIntValue = " + myIntValue); 9 | System.out.println("myFloatValue = " + myFloatValue); 10 | System.out.println("myDoubleValue = " + myDoubleValue); 11 | 12 | // Challenge 13 | double pounds = 200d; 14 | double poundsIntoKilos = pounds * 0.45359237d; 15 | System.out.println(pounds + " pounds is " + poundsIntoKilos + " klograms."); 16 | 17 | 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /variables-datatypes-operators/Operators.java: -------------------------------------------------------------------------------- 1 | public class Operators { 2 | 3 | public static void main(String[] args) { 4 | 5 | int a = 5; 6 | int b = 3; 7 | int c = 10; 8 | boolean isCalculationTrue = false; 9 | 10 | System.out.println("A: " + a); 11 | System.out.println("B: " + b); 12 | System.out.println("C: " + c); 13 | 14 | System.out.println("Is calculation true yet? " + isCalculationTrue); 15 | 16 | int addingResult = a + b + c; 17 | System.out.println("The result of the addition of A, B and C is: " + addingResult); 18 | 19 | if (addingResult == 18) 20 | isCalculationTrue = true; 21 | if (isCalculationTrue == true) System.out.println("He DOES the math correctly, he IS an Alien! Save yourself and run!"); 22 | 23 | 24 | int topScore = 80; 25 | if (topScore < 100) 26 | System.out.println("You got the high score!"); 27 | 28 | int secondTopScore = 81; 29 | if ((topScore > secondTopScore) && topScore < 100) 30 | System.out.println("Greater than second top score and less than 100"); 31 | 32 | if((topScore > 90) || (secondTopScore <= 90)) 33 | System.out.println("One of these tests is true."); 34 | 35 | int newValue = 50; 36 | if (newValue == 50) System.out.println("This is true"); 37 | 38 | // Challenge 39 | 40 | double myDouble = 20d; 41 | double mySecondDouble = 80d; 42 | double myMath = (myDouble + mySecondDouble) * 25; 43 | System.out.println(myMath); 44 | double remainder = myMath % 40; 45 | System.out.println(remainder); 46 | 47 | if(remainder <= 20) 48 | System.out.println("Total was over the limit"); 49 | 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /variables-datatypes-operators/PrimitiveDataTypes.java: -------------------------------------------------------------------------------- 1 | public class PrimitiveDataTypes { 2 | 3 | public static void main(String[] args) { 4 | 5 | 6 | // int has a width of 32 7 | int myMinValue = -2_147_483_648; 8 | int myMaxValue = 2_147_483_647; 9 | int myTotal = (myMinValue/2); 10 | 11 | // byte has a width of 8 12 | byte myByteValue = -128; 13 | byte myNewByteValue = (byte) (myByteValue/2); 14 | 15 | // short has a width of 16 16 | short myShortValue = 32767; 17 | 18 | // long has a width of 64 19 | long myLongValue = 9_223_372_036_854_775_807L; 20 | 21 | int liczba = 1000 + 10 * (10 + 20 + 50); 22 | System.out.println(liczba); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /variables-datatypes-operators/Strings.java: -------------------------------------------------------------------------------- 1 | public class Strings { 2 | 3 | public static void main(String[] args) { 4 | String myString = "This is a String"; 5 | System.out.println(myString); 6 | myString = myString + ", and this is more."; 7 | System.out.println(myString); 8 | myString = myString + " \u00A9 2018"; 9 | System.out.println(myString); 10 | } 11 | } 12 | --------------------------------------------------------------------------------