diff --git a/HYFBE-java-week-5.iml b/HYFBE-java-week-5.iml new file mode 100644 index 0000000..c90834f --- /dev/null +++ b/HYFBE-java-week-5.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/resources/cat.jpeg b/resources/cat.jpeg deleted file mode 100644 index 50be1e0..0000000 Binary files a/resources/cat.jpeg and /dev/null differ diff --git a/resources/data.txt b/resources/data.txt new file mode 100644 index 0000000..e69de29 diff --git a/resources/introduction/ks_serotonine.txt b/resources/introduction/ks_serotonine.txt new file mode 100644 index 0000000..09e706a --- /dev/null +++ b/resources/introduction/ks_serotonine.txt @@ -0,0 +1,5 @@ +Once upon a time there was a little dinosaur. +This little dinosaur was very sad. Its mom had disappeared for a long time now, and it felt so lonely and insecure! +Our little dinosaur wandered all day through the huge trees and plants of the primary forest, yelling non-stop after its mom. +Rexor the Tyrannosaurus had a very fine ear… and an acute nose. Danger was there! +The sky got darker… the day was vanishing, and the forest filled with shadows. diff --git a/resources/introduction/kwiketa_skwirk.txt b/resources/introduction/kwiketa_skwirk.txt new file mode 100644 index 0000000..e69de29 diff --git a/resources/introduction/new.txt b/resources/introduction/new.txt new file mode 100644 index 0000000..e69de29 diff --git a/resources/introduction/notes.txt b/resources/introduction/notes.txt new file mode 100644 index 0000000..58c2f37 --- /dev/null +++ b/resources/introduction/notes.txt @@ -0,0 +1,2 @@ +Java I/O is powerful. +Streams make reading and writing easier. diff --git a/resources/introduction/smiling_pit.jpg b/resources/introduction/smiling_pit.jpg new file mode 100644 index 0000000..d5a1aff Binary files /dev/null and b/resources/introduction/smiling_pit.jpg differ diff --git a/resources/introduction/smiling_pit_copy.jpg b/resources/introduction/smiling_pit_copy.jpg new file mode 100644 index 0000000..d5a1aff Binary files /dev/null and b/resources/introduction/smiling_pit_copy.jpg differ diff --git a/resources/introduction/students.txt b/resources/introduction/students.txt new file mode 100644 index 0000000..e69de29 diff --git a/resources/introduction/test.txt b/resources/introduction/test.txt new file mode 100644 index 0000000..6cdd5fc --- /dev/null +++ b/resources/introduction/test.txt @@ -0,0 +1 @@ +Once upon a time \ No newline at end of file diff --git a/resources/test/subtest/text.txt b/resources/test/subtest/text.txt new file mode 100644 index 0000000..e925143 --- /dev/null +++ b/resources/test/subtest/text.txt @@ -0,0 +1 @@ +Une souris verte... \ No newline at end of file diff --git a/src/generics/exercises/Exercise2.java b/src/generics/exercises/Exercise2.java index 9170a9d..eb27ce4 100644 --- a/src/generics/exercises/Exercise2.java +++ b/src/generics/exercises/Exercise2.java @@ -1,6 +1,7 @@ package generics.exercises; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; /** @@ -31,50 +32,126 @@ public class Exercise2 { public static void main(String[] args) { + String[] words = {"Hello", "World", "Java", "Zia petit toutou"}; + Integer[] numbers = {0,1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + Double[] doubles = {133.99, 24.50, 33.99, 4d, 575.98}; + List numbersList = new ArrayList<>(List.of(numbers)); + List doublesList = new ArrayList<>(List.of(doubles)); + System.out.println("=== Task 1: Print Array ===\n"); - - // TODO: Call printArray method - String[] words = {"Hello", "World", "Java"}; - Integer[] numbers = {1, 2, 3, 4, 5}; - - + printArray(words); printArray(numbers); printArray(doubles); + System.out.println("\n=== Task 2: Reverse Array ===\n"); - - // TODO: Call reverse method - - + Integer[] reverseNumbers = reverse(numbers); + System.out.println(Arrays.toString(reverseNumbers)); + Double[] reverseDoubles = reverse(doubles); + System.out.println(Arrays.toString(reverseDoubles)); + System.out.println("\n=== Task 3: Find Minimum ===\n"); - - // TODO: Call findMin method - List integers = new ArrayList<>(); - integers.add(10); - integers.add(5); - integers.add(20); - integers.add(3); - + System.out.println("Min: " + findMin(numbersList)); + System.out.println("Min: " + findMin(doublesList)); + System.out.println("\n=== Task 4: Calculator ===\n"); - - // TODO: Create and use Calculator instances - + Calculator ci = new Calculator<>(numbers); + System.out.println("[ADD] " + ci.add()); + System.out.println("[SUBSTRACT] " + ci.substract()); + System.out.println("[MULTIPLY] " + ci.multiply()); + Calculator cd = new Calculator<>(doubles); + System.out.println("[ADD] " + cd.add()); + System.out.println("[SUBSTRACT] " + cd.substract()); + System.out.printf("[MULTIPLY] %.2f %n",cd.multiply()); + + System.out.println("\n=== Task 5: Count Greater Than ===\n"); - - // TODO: Call countGreaterThan method - + System.out.printf("Greater elements: %d%n", countGreaterThan(words, "Vernaculaire")); + System.out.printf("Greater elements: %d%n", countGreaterThan(numbers, 5)); + System.out.printf("Greater elements: %d%n", countGreaterThan(doubles, 100d)); + } - // TODO: Task 1 - Implement printArray method - - - // TODO: Task 2 - Implement reverse method - - - // TODO: Task 3 - Implement findMin method + // Task 1 - Implement printArray method + public static void printArray(T[] array){ + if(array.length == 0){ + System.out.println("Empty array."); + return; + } + for (T item:array){ + System.out.print(item + " "); + } + System.out.println(); + } + + // Task 2 - Implement reverse method + public static T[] reverse(T[] array){ + + T [] reverse = array; + int lg = reverse.length -1; + for(int i = 0; i<= lg / 2; i++){ + T temp = reverse[i]; + reverse[i] = reverse[lg-i]; + reverse[lg-i] = temp; + } + return reverse; + } - // TODO: Task 5 - Implement countGreaterThan method + // Task 3 - Implement findMin method + public static double findMin(List numbers){ + double min = numbers.get(0).doubleValue(); + for(Number item:numbers){ + double i = item.doubleValue(); + min = min < i ? min: i; + } + return min; + } + + + // Task 5 - Implement countGreaterThan method + public static > int countGreaterThan(T[] array, T element ){ + int count = 0; + for(T item:array){ + if( element.compareTo(item) < 0){ + System.out.println(item + " is greater than " + element); + count++; + } + } + return count; + } } -// TODO: Task 4 - Create Calculator class here +// Task 4 - Create Calculator class here +class Calculator{ + T[] array; + public Calculator(T[] array){ + this.array = array; + } + protected double add(){ + double count = this.array[0].doubleValue(); + int lg = this.array.length; + for (int i = 1; i < lg; i++) { + count += this.array[i].doubleValue(); + } + return count; + } + protected double substract(){ + double count = this.array[0].doubleValue(); + int lg = this.array.length; + for (int i = 1; i < lg; i++) { + count -= this.array[i].doubleValue(); + } + return count; + } + protected double multiply(){ + double count = this.array[0].doubleValue(); + int lg = this.array.length ; + for (int i = 1; i < lg; i++) { + count *= this.array[i].doubleValue(); + } + return count; + } + +} + diff --git a/src/generics/exercises/Exercise3.java b/src/generics/exercises/Exercise3.java deleted file mode 100644 index c89e3de..0000000 --- a/src/generics/exercises/Exercise3.java +++ /dev/null @@ -1,93 +0,0 @@ -package generics.exercises; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * Exercise 3: Wildcards and PECS - * - * Tasks: - * 1. Write a method printList(List list) that prints any list - * - Try with different types of lists - * - * 2. Write a method sumList(List numbers) that calculates - * the sum of all numbers - * - Try with List, List, and mixed List - * - * 3. Write a method addThreeIntegers(List list) that adds - * the numbers 10, 20, 30 to the list - * - Try with List, List, and List - * - * 4. Write a method copy(List source, List dest) - * that copies all elements from source to destination - * - Demonstrate PECS principle - * - Try by copying List to List - * - Try by copying List to List - * - * 5. Write a method maxOfTwo(List list1, - * List list2) - * that returns the maximum element from both lists combined - * - Try with different number types - * - * 6. BONUS: Create a method that demonstrates why you can't add to - * List (producer) - * Write a comment explaining why - */ -public class Exercise3 { - - public static void main(String[] args) { - System.out.println("=== Task 1: Print Any List ===\n"); - - // TODO: Call printList with different types - - - System.out.println("\n=== Task 2: Sum Numbers ===\n"); - - // TODO: Call sumList - List integers = Arrays.asList(1, 2, 3, 4, 5); - List doubles = Arrays.asList(1.5, 2.5, 3.5); - - - System.out.println("\n=== Task 3: Add Integers ===\n"); - - // TODO: Call addThreeIntegers with different list types - List intList = new ArrayList<>(); - List numList = new ArrayList<>(); - List objList = new ArrayList<>(); - - - System.out.println("\n=== Task 4: Copy Lists (PECS) ===\n"); - - // TODO: Demonstrate PECS with copy method - - - System.out.println("\n=== Task 5: Max of Two Lists ===\n"); - - // TODO: Call maxOfTwo method - - - System.out.println("\n=== Task 6: BONUS - Why Can't Add? ===\n"); - - // TODO: Try to explain and demonstrate - - } - - // TODO: Task 1 - Implement printList - - - // TODO: Task 2 - Implement sumList - - - // TODO: Task 3 - Implement addThreeIntegers - - - // TODO: Task 4 - Implement copy method - - - // TODO: Task 5 - Implement maxOfTwo - - - // TODO: Task 6 - BONUS - -} diff --git a/src/generics/exercises/Exercise5.java b/src/generics/exercises/Exercise5.java index 6ee4345..a178f8a 100644 --- a/src/generics/exercises/Exercise5.java +++ b/src/generics/exercises/Exercise5.java @@ -1,6 +1,8 @@ package generics.exercises; +import java.time.LocalDateTime; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; /** @@ -29,36 +31,88 @@ public class Exercise5 { public static void main(String[] args) { + List words = new ArrayList<>(Arrays.asList("Bernadette", "Scoubidou", "Dinausor")); + List ints = new ArrayList<>(Arrays.asList(518,-43,89,45)); + List dbs = new ArrayList<>(Arrays.asList(55d, -89.89, 54.87)); + List ldt = new ArrayList<>(Arrays.asList( + LocalDateTime.of(2024, 6, 5, 14, 30), + LocalDateTime.now(), + LocalDateTime.of(2027,1,1,1,1) + )); System.out.println("=== Using Box Class ===\n"); - - // TODO: Task 2 - Create and use Box instances - - + Box boxD = new Box<>(5843.879); + Box boxLdt = new Box<>(LocalDateTime.now()); + System.out.println(boxLdt.toString()); + System.out.println(boxD.toString()); + System.out.println("\n=== Using printAll ===\n"); - - // TODO: Task 3 - Call printAll with different lists - - + Box.printAll(words); + Box.printAll(ints); + Box.printAll(dbs); + Box.printAll(ldt); + System.out.println("\n=== Using addDefaults ===\n"); - - // TODO: Task 4 - Call addDefaults - - + System.out.println(Box.addDefaults(ints)); + List dbN = new ArrayList<>(Arrays.asList(55, -89.89, 54.87)); + System.out.println(Box.addDefaults(dbN)); + System.out.println("\n=== Using sumNumbers ===\n"); - - // TODO: Task 5 - Call sumNumbers - + System.out.printf("sumNumbers: %.2f %n" , Box.sumNumbers(dbN)); + } - - // TODO: Task 3 - Implement printAll method - - - // TODO: Task 4 - Implement addDefaults method - - - // TODO: Task 5 - Implement sumNumbers method - } -// TODO: Task 1 - Create Box class here +// Task 1 - Create Box class here +class Box{ + private T value; + public Box(T value){ + setValue(value); + } + // Task 3 - Implement printAll method + public static void printAll(List items) { + + // that prints each element + int count = 0; + for (Object item : items) { + if (count < items.size() - 1) { + System.out.print(item + ", "); + } + else { + System.out.print(item + "\n"); + } + count++; + } + } + // Task 4 - Implement addDefaults method + public static List addDefaults(List numbers) { + numbers.add(1); + numbers.add(2); + numbers.add(3); + return numbers; + } + // Task 5 - Implement sumNumbers method + public static double sumNumbers(List numbers) { + // that returns the sum as double + double output = 0d; + for (Number item:numbers) { + output += item.doubleValue(); + } + return output; + } + // GETTER & SETTER + public T getValue() { + return this.value; + } + + public void setValue(T value) { + this.value = value; + } + // toString + @Override + public String toString() { + //return this.getValue().toString(); + // Better + return String.valueOf(this.value); + } +} diff --git a/src/inputoutput1/examples/Example1.java b/src/inputoutput1/examples/Example1.java index d9e384d..b270f94 100644 --- a/src/inputoutput1/examples/Example1.java +++ b/src/inputoutput1/examples/Example1.java @@ -7,11 +7,12 @@ package inputoutput1.examples; import java.io.File; +import java.io.FileWriter; +import java.io.IOException; public class Example1 { - public static void main(String[] args) - { + public static void main(String[] args) throws IOException { File file = new File("notes.txt"); if (file.exists()) @@ -21,6 +22,15 @@ public static void main(String[] args) else { System.out.println("File not found!"); + try{ + FileWriter writer = new FileWriter(file); + writer.write("Hello World!"); + + } + catch (IOException e){ + System.out.println(e.getMessage()); + } + } } } \ No newline at end of file diff --git a/src/inputoutput1/exercises/Config.java b/src/inputoutput1/exercises/Config.java new file mode 100644 index 0000000..1417def --- /dev/null +++ b/src/inputoutput1/exercises/Config.java @@ -0,0 +1,19 @@ +package inputoutput1.exercises; + + +import java.nio.file.Path; + +public class Config { + + public static Path getResPath(){ + return Path.of(".", + "HYFBE-java-week-5", + "resources"); + } + public static Path getIntroPath(){ + return Path.of(".", + "HYFBE-java-week-5", + "resources", + "introduction"); + } +} diff --git a/src/inputoutput1/exercises/Exercise1.java b/src/inputoutput1/exercises/Exercise1.java index b41e840..520a5fa 100644 --- a/src/inputoutput1/exercises/Exercise1.java +++ b/src/inputoutput1/exercises/Exercise1.java @@ -11,14 +11,28 @@ package inputoutput1.exercises; import java.io.File; +import java.io.IOException; +import java.nio.file.Path; public class Exercise1 { public static void main(String[] args) { - File file = new File("resources" + File.separator + "info.txt"); + String path = Config.getIntroPath() + File.separator + "info.txt"; + File file = new File(path); + if(file.exists()){ + System.out.println("Absolute path: " + file.getAbsolutePath()); + System.out.println("Size: " + file.length() + " bytes"); + System.out.println("Is readable: " +file.canRead()); + System.out.println("Is writable: " +file.canWrite()); + } + + else{ + System.out.println("File not found!"); + } } } + diff --git a/src/inputoutput1/exercises/Exercise2.java b/src/inputoutput1/exercises/Exercise2.java index dad13fd..e3897ee 100644 --- a/src/inputoutput1/exercises/Exercise2.java +++ b/src/inputoutput1/exercises/Exercise2.java @@ -8,13 +8,25 @@ package inputoutput1.exercises; import java.io.File; +import java.io.FileWriter; import java.io.IOException; public class Exercise2 { - public static void main(String[] args) - { - File file = new File("resources" + File.separator + "students.txt"); + public static void main(String[] args) { + File file = new File(STR."\{Config.getIntroPath()}\{File.separator}students.txt"); + if (file.exists()) { + System.out.println("File exists: " + file.getAbsolutePath()); + } else { + System.out.println("File not found!"); + try(FileWriter writer = new FileWriter(file)) { + writer.write("Hello World!"); + System.out.println("File created successfully!"); + } catch (IOException e) { + System.out.println(e.getMessage()); + } + + } } } diff --git a/src/inputoutput1/exercises/Exercise3.java b/src/inputoutput1/exercises/Exercise3.java index c2b3c28..303bb6f 100644 --- a/src/inputoutput1/exercises/Exercise3.java +++ b/src/inputoutput1/exercises/Exercise3.java @@ -13,8 +13,30 @@ public class Exercise3 { + public static void main(String[] args) { - File directory = new File("resources"); + String path = Config.getResPath() + File.separator; + File file = new File(path); + if(file.exists()){ + for(File f:file.listFiles()){ + listFiles(f, 1); + } + } + + } + protected static void listFiles(File file, int depth){ + if(file.isDirectory()){ + System.out.println("-".repeat(depth)+ "[DIR] " + file.getName()); + + for(File j:file.listFiles()){ + listFiles(j, depth + 1); + } + } + else { + System.out.println("-".repeat(depth) + "[FILE] " + file.getName()); + // System.out.println("[PARENT] " + file.getParentFile()); + } + } } diff --git a/src/inputoutput1/exercises/Exercise4.java b/src/inputoutput1/exercises/Exercise4.java index 706e4f2..489d90b 100644 --- a/src/inputoutput1/exercises/Exercise4.java +++ b/src/inputoutput1/exercises/Exercise4.java @@ -17,7 +17,16 @@ public class Exercise4 { public static void main(String[] args) { - String filePath = "resources" + File.separator + "notes.txt"; + String path = STR."\{Config.getIntroPath()}\{File.separator}notes.txt" ; + File file = new File(path); + try(FileWriter writer = new FileWriter(file, true)){ + writer.write("Java I/O is powerful.\n"); + writer.write("Streams make reading and writing easier.\n"); + System.out.println("File written successfully!"); + } + catch (IOException e){ + System.out.println("Error " + e.getMessage()); + } } diff --git a/src/inputoutput1/exercises/Exercise5.java b/src/inputoutput1/exercises/Exercise5.java index 31123e8..66cf159 100644 --- a/src/inputoutput1/exercises/Exercise5.java +++ b/src/inputoutput1/exercises/Exercise5.java @@ -8,15 +8,28 @@ package inputoutput1.exercises; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; +import java.io.*; public class Exercise5 { public static void main(String[] args) { - //try-with-resources can take more than one resource, just use ; between them + String source_path = STR."\{Config.getIntroPath()}\{File.separator}smiling_pit.jpg" ; + String copy_path = STR."\{Config.getIntroPath()}\{File.separator}smiling_pit_copy.jpg" ; + try( + FileInputStream in = new FileInputStream(source_path); + FileOutputStream out = new FileOutputStream(copy_path)){ + int byteData; + while((byteData = in.read()) != -1){ + out.write(byteData); + } + + + System.out.println("File copied successfully!"); + } + catch (IOException e){ + System.out.println("Error " + e.getMessage()); + } } } diff --git a/src/live_coding/Coding1.java b/src/live_coding/Coding1.java new file mode 100644 index 0000000..8d9477d --- /dev/null +++ b/src/live_coding/Coding1.java @@ -0,0 +1,104 @@ +package live_coding; +/* +## Coding Question 1 -- Composition (Car and Engine) + +Create two classes: + +Engine, Car + +## Engine + +Fields: +```java +horsePower +``` +Method: + +start() + +When start() is called, print: + +Engine started + +## Car + +Fields: +```java +brand +``` +Engine engine + +Method: + +drive() + +## Requirements: + +A Car has an Engine (composition). + +When drive() is called: + +The engine should start + +Then print: +```java +Car is driving +``` +In main() + +Create an Engine + +Pass the engine to a Car + +Call drive() + +Example output: +```java +Engine started +Car is driving +``` +Discussion point: + +Why is this example composition instead of inheritance? + */ + +public class Coding1 { + static void main() { + +Car mercedes = new Car("Mercedes"); +mercedes.drive(); + } +} +class Engine{ + private int horsePower; + public Engine(int horsePower){ + setHorsePower(horsePower); + } + // START METHOD + public void start(){ + System.out.println("Engine started."); + } + // SETTER + public void setHorsePower(int horsePower) { + this.horsePower = horsePower; + } + //GETTER + public int getHorsePower() { + return horsePower; + } +} +class Car{ + private Engine engine = new Engine(15); + private String brand; + public Car(String brand){ + setBrand(brand); + } + public void drive(){ + engine.start(); + System.out.println("Car is driving"); + } + // SETTER. + public void setBrand(String brand) { + this.brand = brand; + } +} \ No newline at end of file diff --git a/src/live_coding/Coding2.java b/src/live_coding/Coding2.java new file mode 100644 index 0000000..548e8eb --- /dev/null +++ b/src/live_coding/Coding2.java @@ -0,0 +1,50 @@ +package live_coding; + +public class Coding2 { + static void main() { + int[][] temps = { + {3, 5, 2, 4}, // Week 1 + {6, 1, 0, 2}, // Week 2 + {4, 4, 3, -5} // Week 3 + }; + // 1.Return the average temperature of a single week. + int count = 1; + for (int[] week:temps){ + System.out.println("Week " + count + " average temperature: " + weekAverage(week) + "°C"); + count++; + } + // 2.Return the lowest temperature in the entire 2D array. + System.out.println("Coldest temp: " + coldestTemperature(temps)); + + } + // Return the average temperature of a single week. + public static int weekAverage(int[] week){ + int count = 0; + int lg = week.length; + if(lg == 0){ + return count; + } + + for(int temp:week){ + count += temp; + } + return count / lg; + } + // Return the lowest temperature in the entire 2D array. + public static int coldestTemperature(int[][] temps){ + int coldest = min(temps[0]); + for(int i=1; i services = new ArrayList<>(); + services.add(new Email()); + services.add(new SMS()); + for(NotificationService ns:services){ + notifyAllUsers(ns,"This is a beautiful day!"); + } + + + } + public static void notifyAllUsers(NotificationService ns, String message){ + if(ns instanceof SMS){ + System.out.println("New SMS: " + message); + } + else if(ns instanceof Email){ + System.out.println("New Email: " + message); + } + if(ns instanceof SMS){ + System.out.println(message); + } + + } +} + +abstract class NotificationService{ + +} + +class SMS extends NotificationService{ + +} +class Email extends NotificationService{} \ No newline at end of file diff --git a/src/live_coding/Exo1.java b/src/live_coding/Exo1.java new file mode 100644 index 0000000..ba93924 --- /dev/null +++ b/src/live_coding/Exo1.java @@ -0,0 +1,57 @@ +package live_coding; +/* +/* +Write a method: +public static int readPositiveInt(Scanner scanner) +Requirements: +Ask the user: +Enter a positive integer: +The program must: +Reject inputs that are not integers +Reject integers less than or equal to 0 +If the input is invalid, ask again. +The method should return the valid positive integer. +Example interaction: +Enter a positive integer: -3 Must be greater than 0 +Enter a positive integer: hello Invalid input +Enter a positive integer: 7 You entered: 7 + +In main(): +Create a Scanner +Call readPositiveInt(scanner) +Print the returned value + */ + + +import java.util.Scanner; + +public class Exo1 { + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + int play = -1; + while(play < 0){ + System.out.print("Enter a positive integer: "); + + play = readPositiveInt(scanner); + if(play != -1){ + System.out.println("You entered " + play); + } + } + scanner.close(); + + } + public static int readPositiveInt(Scanner scanner){ + if(!scanner.hasNextInt()){ + System.out.println("Input not valid : Please enter an integer."); + scanner.next(); + return -1 ; + } + int nb = scanner.nextInt(); + if(nb <= 0 ){ + System.out.println("Input not valid : must be greater than 0."); + return -1; + } + return nb; + } +} diff --git a/src/live_coding/Exo2.java b/src/live_coding/Exo2.java new file mode 100644 index 0000000..73416d3 --- /dev/null +++ b/src/live_coding/Exo2.java @@ -0,0 +1,58 @@ +package live_coding; + +/* +Create a utility class: +Statistics +Add a static method: +public static double average(int... numbers) +Requirements: +If no numbers are provided, return 0. +Calculate the average value. +Print the maximum number. +Example usage: +double avg = Statistics.average(5, 8, 12, 3); +Example output: +Average: 7.0 Max: 12 +Bonus: +Convert the numbers varargs into a List and compute the maximum using Collections.max(). + + */ + +import java.lang.reflect.Array; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + + +public class Exo2 { + static void main(String[] args) { + double avg = Statistics.average(5, 8, 12, 3, 334); + + } +} +class Statistics{ + public static double average(int... numbers){ + int lg = numbers.length; + if(lg == 0){ + return 0d; + } + System.out.println(); + // Cast numbers + List integers = new ArrayList<>(); + //int max = Collections.max(numbers); + int count = 0; + for(int nb:numbers){ + // max = max < nb ? max:nb; + integers.add(nb); + count += nb; + } + int max = Collections.max(integers); + double avr = ((double) count / lg); + System.out.printf("Max: %d Average: %.2f %n", max, avr); + + return avr; + } + + +} diff --git a/src/live_coding/Exo3.java b/src/live_coding/Exo3.java new file mode 100644 index 0000000..9222580 --- /dev/null +++ b/src/live_coding/Exo3.java @@ -0,0 +1,105 @@ +package live_coding; +/* +/* +Interfaces + Polymorphism + Collections + (optional) sealed +Design a tiny logging system. +Create an interface: +interface Logger { + void log(String message); +} +Implement two loggers: +ConsoleLogger → prints: "[CONSOLE] " + message +FileLogger → writes logs into a file named app.log (append mode) +Create a class App with a field: +private final List loggers; +Constructor receives the list (constructor injection). +Method: +public void run() +Inside run(): +Log "App started" +Log "Doing work..." +Log "App finished" +In main(): +Create both loggers +Put them into a list +Create App and call run() +Why it's final boss: +Design +Discuss Interface and DIP +Bonus: +Make Logger a sealed interface permitting only those two implementations. + */ + + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +public class Exo3 { + static void main() { + String p = "./HYFBE-java-week-5/resources"; + ConsoleLogger cl = new ConsoleLogger(); + FileLogger fl = new FileLogger(p); + /* String mess = "Hello world!"; + cl.log(mess); + fl.log(mess);*/ + + App app = new App(cl,fl); + app.run(); + + } + +} +class App{ + private final List loggers = new ArrayList<>(); + public App(Logger... logger){ + for(Logger l:logger){ + this.loggers.add(l); + } + } + public void run(){ + System.out.println(); + for(Logger l:loggers){ + l.log("App have started \n"); + l.log("App doing work...\n"); + l.log("App finished."); + } + + } + +} +interface Logger { + void log(String message); +} +class ConsoleLogger implements Logger{ + @Override + public void log(String message) { + System.out.println("[CONSOLE] " + message); + } +} +class FileLogger implements Logger{ + private File file; + private String path; + + public FileLogger(String path){ + this.path = path + File.separator + "app.log"; + this.file = new File(path); + } + @Override + public void log(String message) { + try (FileWriter writer = new FileWriter(path, true)) + { + writer.write(message); + System.out.println("Data successfully written to file."); + } + catch (IOException e) + { + System.out.println("Error writing to file: " + e.getMessage()); + } + + + } +} + diff --git a/src/live_coding/README.md b/src/live_coding/README.md new file mode 100755 index 0000000..122ea55 --- /dev/null +++ b/src/live_coding/README.md @@ -0,0 +1,213 @@ +# Live Coding Exercise -- Group B + +This exercise contains two coding tasks and three theory questions. + +## Instructions + +First, solve the coding questions individually. + +During the pair session, ask your partner to solve one of your questions. + +Observe how they approach the problem and discuss the solution together. + +Focus not only on getting the correct result, but also on code structure and design decisions. + +## Coding Question 1 -- Composition (Car and Engine) + +Create two classes: + +Engine, Car + +## Engine + +Fields: +```java +horsePower +``` +Method: + +start() + +When start() is called, print: + +Engine started + +## Car + +Fields: +```java +brand +``` +Engine engine + +Method: + +drive() + +## Requirements: + +A Car has an Engine (composition). + +When drive() is called: + +The engine should start + +Then print: +```java +Car is driving +``` +In main() + +Create an Engine + +Pass the engine to a Car + +Call drive() + +Example output: +```java +Engine started +Car is driving +``` +Discussion point: + +Why is this example composition instead of inheritance? + +## Coding Question 2 -- Multi-Dimensional Arrays + +You are given a 2D array representing weekly temperatures: +```java +int[][] temps = { +{3, 5, 2, 4}, // Week 1 +{6, 1, 0, 2}, // Week 2 +{4, 4, 3, 5} // Week 3 +}; +``` +Task 1 + +Write a method: +```java +public static int weekAverage(int[] week) +``` +Return the average temperature of a single week. + +Task 2 + +Write another method: +```java +public static int coldestTemperature(int[][] temps) +``` +This method should return the lowest temperature in the entire 2D array. + +In main() + +Print the average temperature for each week + +Print the coldest temperature overall + +Example output: +```java +Week 1 average: 3 +Week 2 average: 2 +Week 3 average: 4 + +Coldest temperature: 0 +``` +## Coding Question 3 Notification System (This one is without hints) + +Design a small notification system. + +Your system should be able to send notifications through different communication channels. + +### Requirements + +Define a common abstraction that represents something capable of sending a notification message. + +Implement at least two different types of notification senders: + +One that sends notifications by email + +One that sends notifications by SMS + +Create a class called NotificationService. + +NotificationService should be able to send the same message through all available notification senders. + +The service should not depend on a specific sender implementation. + +Write a method: +```java +notifyAllUsers(String message) +``` +that sends the message through every available notification sender. + +In main(): + +Create the notification senders + +Register them in the service + +Send a message: + +"System update tonight" +Example Output +```java +Sending EMAIL: System update tonight +Sending SMS: System update tonight +``` +# Theory Questions +## Theory 1 -- Encapsulation vs Abstraction + +Explain the difference between: + +Encapsulation + +Abstraction + +### Hints: + +Encapsulation: + +Hiding internal data + +Controlling access using private fields and methods + +Abstraction: + +Hiding implementation details + +Showing only essential behavior through interfaces or abstract classes + +Give a simple Java example for both. + +## Theory 2 -- final and Immutability + +What does the keyword final mean for: + +a variable? + +a field? + +a reference to an object? + +Example: +```java +final List list = new ArrayList<>(); +``` +Why can we still add elements to the list? + +Explain the difference between final reference and immutable object. + +## Theory 3 -- protected Access Modifier + +What does protected mean in Java? + +Compare the following access levels: + +private +protected +public + +When would you choose protected instead of private? + +Give a small example involving inheritance. \ No newline at end of file diff --git a/src/live_coding/Theory2.java b/src/live_coding/Theory2.java new file mode 100644 index 0000000..c93e725 --- /dev/null +++ b/src/live_coding/Theory2.java @@ -0,0 +1,72 @@ +package live_coding; +/* +Theory 2 -- final and Immutability +What does the keyword final mean for: + +a variable? + +a field? + +a reference to an object? + +Example: + +final List list = new ArrayList<>(); +Why can we still add elements to the list? + +Explain the difference between final reference and immutable object. + + + */ + +import java.util.ArrayList; +import java.util.List; + +public class Theory2 { + static void main() { + System.out.println("Theory 2 -- final and Immutability"); + // What does the keyword final mean for: + // + //a variable? + + // the value of a final variable could not be changed. It's imutable'. + // Variable + System.out.println("The assigned value of a final variable/field cannot be reassigned."); + final String name = "Sophie"; + // name = "Babar"; // Generate an error => java: cannot assign a value to final variable name + + //a field? + // same for a field + System.out.println("When a method is declared final, it means:"); + System.out.println("A subclass cannot override this method."); + + // a reference to an object? + System.out.println("A final object reference cannot change but it could be modified."); + final List names = new ArrayList<>(); + names.add(name); // OK + //names = new ArrayList<>(); // + + Dog zia = new Dog(); + System.out.println(zia.sound); // OK + // System.out.println(zia.fur); // Raise an error => java: fur has private access in live_coding.Animal + zia.setFur(true); + System.out.println(zia.isFur()); + + } +} + +class Animal{ + protected String sound = "noise"; + private boolean fur = false; + public void setFur(boolean hasFur){ + this.fur = hasFur; + } + public boolean isFur(){ + return this.fur; + } +} + +class Dog extends Animal{ + + +} diff --git a/src/live_coding/theory_1.txt b/src/live_coding/theory_1.txt new file mode 100644 index 0000000..d777ea5 --- /dev/null +++ b/src/live_coding/theory_1.txt @@ -0,0 +1,66 @@ +/// Theory 1 -- Encapsulation vs Abstraction /// + +Explain the difference between: + +Encapsulation + +Abstraction + +### Hints: + +Encapsulation: + +Hiding internal data + +Controlling access using private fields and methods + +Abstraction: + +Hiding implementation details + +Showing only essential behavior through interfaces or abstract classes + +Give a simple Java example for both. + +// Encapsulation + +class Encapsulation{ + private int integer; + private String name; + public Encapsulation(String name, int integer){ + setInteger(integer); + setName(name); + } + // START METHOD + protected void protectedMethod(String mess){ + System.out.println(mess); + } + // SETTER + public void setInteger(int integer) { + this.integer = integer; + } + public void setName(String name) { + this.name = name; + } + //GETTER + public int getInteger() { + return this.integer; + } + public String getName() { + return this.name; + } +} + +// Abstraction + +abstract class NotificationService{ + +protected String getMessage(String message){ +return message;} + +} + +class SMS extends NotificationService{ + +} +class Email extends NotificationService{} \ No newline at end of file diff --git a/src/live_coding/theory_2.txt b/src/live_coding/theory_2.txt new file mode 100644 index 0000000..060e161 --- /dev/null +++ b/src/live_coding/theory_2.txt @@ -0,0 +1,33 @@ +// Theory 2 -- final and Immutability // + // What does the keyword final mean for: + // + //a variable? + + // the value of a final variable could not be changed. It's imutable'. + // Variable + System.out.println("The assigned value of a final variable/field cannot be reassigned."); + final String name = "Sophie"; + name = "Babar"; // Generate an error => java: cannot assign a value to final variable name + + + // + //a field? + // same for a field + When a method is declared final, it means: + A subclass cannot override this method. + + + // a reference to an object? + A final object reference cannot change but it could be modified. + final List names = new ArrayList<>(); + names.add(name); // OK + + // Explain the difference between final reference and immutable object. + The state of an immutable cannot change. + String name = "Sophie"; + name += "Babar"; => create new Object; + An ArrayList is mutable => its content could be change + A final ArrayList's reference could not be changed. + final List names = new ArrayList<>(); + names = new ArrayList<>(); // raise an error => java: cannot assign a value to final variable names + An Integer is immutable => its content could not be changed. diff --git a/src/live_coding/theory_3.txt b/src/live_coding/theory_3.txt new file mode 100644 index 0000000..1e1f7b9 --- /dev/null +++ b/src/live_coding/theory_3.txt @@ -0,0 +1,38 @@ +// Theory 3 -- protected Access Modifier // + +What does protected mean in Java? +In Java, a protected field or method can be accessed by subclasses of the class and by other classes in the same package. + +Compare the following access levels: + +private +In Java, a private field or method cannot be accessed from outside its class. +protected +In Java, a protected field or method can be accessed by subclasses of the class and by other classes in the same package. +public +In Java, a public field or method can be accessed by any class from any package. + +When would you choose protected instead of private? +When we want ONLY a subclass or a package class to access or override a method / field. + +Give a small example involving inheritance. + +class Animal{ + protected String sound = "noise"; + private boolean fur = false; + public void setFur(boolean hasFur){ + this.fur = hasFur; + } + public boolean isFur(){ + return this.fur; + } +} + +class Dog extends Animal{} + +//// +Dog zia = new Dog(); +System.out.println(zia.sound); // OK +System.out.println(zia.fur); // Raise an error => java: fur has private access in live_coding.Animal +zia.setFur(true); // OK +System.out.println(zia.isFur()); // OK \ No newline at end of file diff --git a/src/modern/examples/Students.java b/src/modern/examples/Students.java new file mode 100644 index 0000000..f61d2e6 --- /dev/null +++ b/src/modern/examples/Students.java @@ -0,0 +1,95 @@ +package modern.examples; + +/* +OOP Design Challenge — Student Ranking System +You are building a small student ranking system for a school. +The school wants to display students sorted by their grades, from highest to lowest. +Your task is to design a system that makes this possible. + +Step 1 — Create the Student class +Create a class called Student. +Each student has: +name +gradeRequirements: +fields must be private +provide a constructor +provide getters + +override toString() so students can be printed nicely +Example: +Alice (90) +Bob (75) +Charlie (82) + +Step 2 — Create some students +In main(): +create a List + +add at least 5 students +Example: + +List students = new ArrayList<>(); + +students.add(new Student("Alice", 90)); +students.add(new Student("Bob", 75)); +students.add(new Student("Charlie", 82)); +students.add(new Student("Emma", 65)); +students.add(new Student("David", 80)); + +Step 3 — Sort the students +The school wants to print students from highest grade to lowest grade. +Your task: +Sort the students by gradeThink about the following questions: +How can Java know which student is greater or smaller? + +How can two Student objects be compared? +Where should that comparison logic live? +After sorting, print the list. +Expected output: +Students ranked by grade: + +Alice (90) +Charlie (82) +David (80) +Bob (75) +Emma (65) + */ + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +public class Students { + static void main() { + String[] names = new String[]{"Bob", "Andrei", "Capucine", "Gomathi", "Emma", "Preeti", "Alison", "john"," ", "basel", "Kien"}; + Random rd = new Random(); + List students = new ArrayList<>(); + for(String name:names){ + try{ + students.add(new Student(name, rd.nextInt(101))); + } + catch(IllegalArgumentException e){ + System.out.println(e.getMessage()); + } + } + } + +} + + +// 1.Class student +record Student(String name, int grade){ + public Student { + if (name == null || name.isBlank()) { + throw new IllegalArgumentException("Name cannot be blank, please fix!"); + } + if (grade <= 0) { + throw new IllegalArgumentException("Grade cannot be negative or null, please fix!"); + } + } + // Override toString() so students can be printed nicely E.g. Bob (75). + public String toString(){ + return STR."\{this.name()} (\{this.grade()})"; + } + +} \ No newline at end of file diff --git a/src/modern/exercises/Exercise1.java b/src/modern/exercises/Exercise1.java index 101e20a..bb3afe9 100644 --- a/src/modern/exercises/Exercise1.java +++ b/src/modern/exercises/Exercise1.java @@ -10,6 +10,13 @@ public class Exercise1 { public static void main(String[] args) { - + System.out.println("Sum => " + sum(10,30,5,4,1)); + } + public static int sum(int... numbers){ + int result = 0; + for(int nb:numbers ){ + result +=nb; + } + return result; } } diff --git a/src/modern/exercises/Exercise2.java b/src/modern/exercises/Exercise2.java index 389ab8c..9c729bb 100644 --- a/src/modern/exercises/Exercise2.java +++ b/src/modern/exercises/Exercise2.java @@ -10,6 +10,15 @@ public class Exercise2 { public static void main(String[] args) { + System.out.println("Join => " + join("Once", "upon","a","time")); } + public static StringBuilder join(String... words){ + StringBuilder result = new StringBuilder(); + for(String str:words ){ + result.append(str + " "); + } + return result; + } + } diff --git a/src/modern/exercises/Exercise3.java b/src/modern/exercises/Exercise3.java index f2d42cb..7de306a 100644 --- a/src/modern/exercises/Exercise3.java +++ b/src/modern/exercises/Exercise3.java @@ -10,6 +10,19 @@ public class Exercise3 { public static void main(String[] args) { + // Instance of interface Printer. + Printer printer = new Printer(){ + + @Override + public void print(String text) { + System.out.println("Text: " + text); + } + }; + printer.print("Hello World!"); } } + +interface Printer{ + void print(String text); +} diff --git a/src/modern/exercises/Exercise4.java b/src/modern/exercises/Exercise4.java index 48ce715..41c129a 100644 --- a/src/modern/exercises/Exercise4.java +++ b/src/modern/exercises/Exercise4.java @@ -10,6 +10,18 @@ public class Exercise4 { public static void main(String[] args) { + Comparator comparator = new Comparator<>() { + @Override + public int compare(String a, String b) { + return a.length() - b.length(); + } + }; + int c = comparator.compare("Roberta", "Mitchumette"); + System.out.println("Compare: " + c ); + } } +interface Comparator{ + public int compare(T a, T b); +} diff --git a/src/modern/exercises/Exercise5.java b/src/modern/exercises/Exercise5.java index 163e86f..dc6a277 100644 --- a/src/modern/exercises/Exercise5.java +++ b/src/modern/exercises/Exercise5.java @@ -11,6 +11,60 @@ public class Exercise5 { public static void main(String[] args) { + Product product = new Product.Builder() + .name("socks") + .price(22d) + .inStock(true) + .build(); + System.out.printf("%s Price: %.2f %s", product.getName().toUpperCase(), product.getPrice(), product.isInStock()? "in stock":"not in stock"); + + } +} + +class Product{ + String name; + Double price; + boolean inStock; + public Product(Builder builder){ + this.name = builder.name; + this.price = builder.price; + this.inStock = builder.inStock; + } + // GETTERS + + public String getName() { + return name; + } + + public Double getPrice() { + return price; + } + + public boolean isInStock() { + return inStock; + } + + // BUILDER + public static class Builder{ + String name; + Double price; + boolean inStock; + public Builder name(String name){ + this.name = name; + return this; + } + public Builder price(Double price){ + this.price = price; + return this; + } + public Builder inStock(boolean inStock){ + this.inStock = inStock; + return this; + } + + public Product build() { + return new Product(this); + } } } diff --git a/src/modern/exercises/Exercise6.java b/src/modern/exercises/Exercise6.java index b6f69fd..51c41f1 100644 --- a/src/modern/exercises/Exercise6.java +++ b/src/modern/exercises/Exercise6.java @@ -11,6 +11,57 @@ public class Exercise6 { public static void main(String[] args) { + Shape rec = new Rectangle(10d,3d); + Shape circle = new Circle(32d); + printArea(rec); + printArea(circle); + } + + public static void printArea(Shape shape){ + if(shape instanceof Rectangle rec){ + System.out.println("Rectangle aera = " + rec.getWidth() + " * " + rec.getHeight() + " = " + rec.aera()); + } + if(shape instanceof Circle cir){ + System.out.println("Circle aera = " + Math.PI + " * " + cir.getRadius() + " * " + cir.getRadius() + " = " + cir.aera()); + } + } + +} +sealed interface Shape permits Circle, Rectangle { + Double aera(); +} + +final class Circle implements Shape { +Double radius; +public Circle(Double radius){ + this.radius = radius; +} + @Override + public Double aera() { + return Math.PI * radius * radius; + } + + public Double getRadius() { + return radius; + } +} +final class Rectangle implements Shape{ +Double width; +Double height; + public Rectangle(Double w, Double h){ + this.width = w; + this.height= h; + } + @Override + public Double aera() { + return width * height; + } + + public Double getWidth() { + return width; + } + public Double getHeight() { + return height; } } diff --git a/src/modern/exercises/Exercise7.java b/src/modern/exercises/Exercise7.java index d0d8c55..f1d6e13 100644 --- a/src/modern/exercises/Exercise7.java +++ b/src/modern/exercises/Exercise7.java @@ -12,6 +12,17 @@ public class Exercise7 { public static void main(String[] args) { + Product2 chocoEggs = new Product2("Chocolate eggs", 34d); + Product2 otherChocoEggs = new Product2("Chocolate eggs", 34d); + Product2 orientalDelices = new Product2("Oriental delices", 12d); + System.out.println(orientalDelices.name() + " " + orientalDelices.price()); + System.out.println(chocoEggs.name() + " " + chocoEggs.price()); + System.out.println(chocoEggs.toString()); + System.out.println(orientalDelices.toString()); + System.out.println(chocoEggs.equals(otherChocoEggs)); + System.out.println(chocoEggs.equals(orientalDelices)); } } + +record Product2(String name, double price){}; diff --git a/src/modern/exercises/RecordExercise.java b/src/modern/exercises/RecordExercise.java new file mode 100644 index 0000000..6dc3b02 --- /dev/null +++ b/src/modern/exercises/RecordExercise.java @@ -0,0 +1,97 @@ +package modern.exercises; + +import java.util.ArrayList; +import java.util.List; + +public class RecordExercise { + public static void main(String[] args) { + try{ + List students = new ArrayList<>(List.of( + new Student(1, "Robert", 5d), + new Student(2, "Preeti", 15d), + new Student(3, "John", 17d), + new Student(4, "Alison", 12d), + new Student(5, "Catherine", 19d), + new Student(6, "Gomathi", 7d), + new Student(7, "Helena", 0d), + new Student(8, "Basel", 14d), + new Student(9, "Julie", 16d) + )); + System.out.printf("Average grade: %.2f %n",averageGrade(students)); + System.out.println("Students List"); + print(students); + System.out.println("Best student:\n" + bestStudent(students).toString()); + // Curve + Student helena = students.get(6); + students.set(6, helena.curve(12d)); + System.out.println(students.get(6).toString()); + + + } catch (IllegalArgumentException e) { + System.out.println("Error " + e.getMessage()); + } + } + // Methods. + public static double averageGrade(List students){ + double grades = 0d; + for(Student student:students){ + grades += student.grade(); + } + return grades / students.size(); + } + + public static void print(List students) { + for (Student student : students) { + System.out.println("- " + student); + } + } + public static Student bestStudent(List students){ + double max = students.get(0).grade(); + Student best = students.get(0); + for (Student student : students) { + if(student.grade() > max){ + max = student.grade(); + best = student; + } + } + return best; + } +} +record Student(int id, String name, double grade){ + public Student { + if (name == null || name.isBlank()) { + throw new IllegalArgumentException(id + " Student name must be filled"); + } + if (grade < 0d || grade > 20d) { + throw new IllegalArgumentException(name + "'s grade must be in beetween 0,00 and 20,00"); + } + } + public boolean hasPassed(){ + return grade >= 10d; + } + public String gradeMention(){ + if (grade >= 16){ return "Excellent"; } + else if(grade >= 14){ + return "Very Good"; + } + else if(grade >= 12){ + return "Good"; + } + else if(grade >= 10){ + return "Pass"; + } + else{ + return "Fail"; + } + } + + @Override + public String toString() { + return name() + " grade: " + grade() + " mention: " + gradeMention(); + } + public Student curve(double points){ + double increase = grade() + points; + double bonus = increase <= 20 ? increase : 20; + return new Student(id(), name(), bonus ); + } +}