From ce34f4f537ab2bf558031336b241c58456815640 Mon Sep 17 00:00:00 2001 From: Tiago Garcia Date: Wed, 31 May 2023 20:02:14 +0100 Subject: [PATCH] [POO] Changes (#69) [POO] ATP1 added --> Exercise made in Codecheck [POO] Removed tp_codecheck --> Didn't really have too much there and not worth keeping around [POO] Code reformat --> Optimized and reformated code for all directories in source --- 1ano/2semestre/poo/src/aula01/KmToMiles.java | 19 +-- .../poo/src/aula01/MyFirstClass.java | 16 +-- .../poo/src/aula01/PescadaDeRaboNaBoca.java | 18 +-- .../poo/src/aula01/ReadFileExample.java | 17 +-- .../poo/src/aula01/StringExample.java | 14 +-- .../poo/src/aula02/CelciusToFahrenheit.java | 2 +- 1ano/2semestre/poo/src/aula02/Countdown.java | 4 +- .../poo/src/aula02/DistanceBetweenPoints.java | 5 +- .../poo/src/aula02/EnergyToHeatWater.java | 1 + 1ano/2semestre/poo/src/aula02/Investment.java | 3 +- 1ano/2semestre/poo/src/aula02/KmToMiles.java | 1 + .../poo/src/aula02/PythagoreanTheorem.java | 3 +- .../2semestre/poo/src/aula02/RealNumbers.java | 4 +- 1ano/2semestre/poo/src/aula02/SecsToHMS.java | 3 +- 1ano/2semestre/poo/src/aula03/Calendar.java | 4 +- 1ano/2semestre/poo/src/aula03/Grades.java | 10 +- .../poo/src/aula03/GradesRandom.java | 2 +- 1ano/2semestre/poo/src/aula03/Investment.java | 4 +- .../poo/src/aula03/StringExtras.java | 2 +- 1ano/2semestre/poo/src/aula04/CarDemo.java | 10 +- .../poo/src/aula04/CashRegisterDemo.java | 4 +- 1ano/2semestre/poo/src/aula04/Shapes.java | 10 +- .../poo/src/aula04/SimpleCarDemo.java | 8 +- .../2semestre/poo/src/aula05/AuctionDemo.java | 36 +++--- 1ano/2semestre/poo/src/aula05/Calendar.java | 6 +- 1ano/2semestre/poo/src/aula05/DateYMD.java | 41 +++--- 1ano/2semestre/poo/src/aula06/ex1/Bolser.java | 4 +- 1ano/2semestre/poo/src/aula06/ex1/Person.java | 3 + .../poo/src/aula06/ex1/PersonTest.java | 8 +- .../poo/src/aula06/ex1/Professor.java | 2 + .../2semestre/poo/src/aula06/ex1/Student.java | 4 +- .../2semestre/poo/src/aula06/ex2/Contact.java | 10 +- .../poo/src/aula06/ex2/ContactList.java | 2 + 1ano/2semestre/poo/src/aula06/ex3/Vector.java | 15 ++- .../poo/src/aula06/ex3/VectorTest.java | 13 +- .../poo/src/aula07/ex1/Rectangle.java | 4 +- 1ano/2semestre/poo/src/aula07/ex1/Shape.java | 4 + .../poo/src/aula07/ex1/Triangle.java | 2 +- 1ano/2semestre/poo/src/aula07/ex2/Date.java | 26 ++-- .../poo/src/aula07/ex2/DateTest.java | 35 +++--- .../2semestre/poo/src/aula07/ex2/DateYMD.java | 2 +- 1ano/2semestre/poo/src/aula07/ex3/Game.java | 4 +- 1ano/2semestre/poo/src/aula07/ex3/Main.java | 21 ++-- 1ano/2semestre/poo/src/aula07/ex3/Robot.java | 4 +- 1ano/2semestre/poo/src/aula07/ex3/Team.java | 10 +- .../ex1/Interfaces/IElectricVehicle.java | 1 + .../aula08/ex1/Interfaces/IFuelVehicle.java | 1 + .../aula08/ex1/Interfaces/IKmTravelled.java | 2 + .../src/aula08/ex1/Vehicles/Motorcycle.java | 32 ++--- .../poo/src/aula08/ex2/Aliments/Aliment.java | 4 +- .../poo/src/aula08/ex2/Enums/AlimentType.java | 2 +- .../poo/src/aula08/ex2/Enums/FishState.java | 2 +- .../src/aula08/ex3/Interfaces/IProduct.java | 7 +- .../src/aula08/ex3/Interfaces/IPurchase.java | 2 + .../poo/src/aula08/ex3/Purchase.java | 2 +- .../src/aula08/ex3/ShoppingCartTester.java | 2 +- 1ano/2semestre/poo/src/aula09/ex1/ALDemo.java | 11 +- .../poo/src/aula09/ex2/CollectionTester.java | 28 ++--- .../poo/src/aula09/ex3/PlaneManager.java | 3 +- .../poo/src/aula09/ex3/PlaneTester.java | 3 +- 1ano/2semestre/poo/src/aula10/ex1/Book.java | 29 ++++- .../poo/src/aula10/ex4/FileReaderTest.java | 2 +- .../poo/src/aula11/ex1/WordPairCounter.java | 12 +- .../poo/src/aula11/ex2/Gradebook.java | 6 +- .../poo/src/aula11/ex3/EnergyUsageReport.java | 6 +- .../aula11/ex3/EnergyUsageReportTester.java | 14 +-- .../poo/src/aula11/ex4/FlightManager.java | 24 ++-- 1ano/2semestre/poo/src/aula11/ex4/Time.java | 16 +-- .../src/aula12/ex2/WordCounterByInitial.java | 2 +- 1ano/2semestre/poo/src/aval/aa1/Animal.java | 24 ++-- .../poo/src/aval/aa1/IPetShelter.java | 14 ++- .../poo/src/aval/aa1/PetShelter.java | 8 +- .../poo/src/aval/aa2/Classes/Order.java | 3 +- .../src/aval/aa2/Classes/OrderManager.java | 2 +- .../poo/src/aval/aa2/OrderTester.java | 17 ++- .../poo/src/aval/atp1/RainfallInfo.java | 41 ++++++ .../poo/src/aval/atp1/RainfallTest.java | 118 ++++++++++++++++++ 1ano/2semestre/poo/src/tp_codecheck/README.md | 6 - .../src/tp_codecheck/tp01/BankInterest.java | 59 --------- .../poo/src/tp_codecheck/tp01/Table.java | 28 ----- .../src/tp_codecheck/tp01/Temperature.java | 29 ----- .../poo/src/tp_codecheck/tp02/Array1.md | 23 ---- .../src/tp_codecheck/tp02/NumberOfDays.java | 27 ---- .../poo/src/tp_codecheck/tp02/Numbers.java | 17 --- .../poo/src/tp_codecheck/tp02/Strings1.md | 9 -- .../poo/src/tp_codecheck/tp02/Words.java | 12 -- .../tp03/part1/TrafficLight1.java | 66 ---------- .../tp03/part1/TrafficLight2.java | 68 ---------- .../tp_codecheck/tp03/part2/RentalCar.java | 72 ----------- 1ano/2semestre/poo/src/utils/DateYMD.java | 41 +++--- 90 files changed, 575 insertions(+), 742 deletions(-) create mode 100644 1ano/2semestre/poo/src/aval/atp1/RainfallInfo.java create mode 100644 1ano/2semestre/poo/src/aval/atp1/RainfallTest.java delete mode 100755 1ano/2semestre/poo/src/tp_codecheck/README.md delete mode 100644 1ano/2semestre/poo/src/tp_codecheck/tp01/BankInterest.java delete mode 100644 1ano/2semestre/poo/src/tp_codecheck/tp01/Table.java delete mode 100644 1ano/2semestre/poo/src/tp_codecheck/tp01/Temperature.java delete mode 100644 1ano/2semestre/poo/src/tp_codecheck/tp02/Array1.md delete mode 100644 1ano/2semestre/poo/src/tp_codecheck/tp02/NumberOfDays.java delete mode 100644 1ano/2semestre/poo/src/tp_codecheck/tp02/Numbers.java delete mode 100644 1ano/2semestre/poo/src/tp_codecheck/tp02/Strings1.md delete mode 100644 1ano/2semestre/poo/src/tp_codecheck/tp02/Words.java delete mode 100644 1ano/2semestre/poo/src/tp_codecheck/tp03/part1/TrafficLight1.java delete mode 100644 1ano/2semestre/poo/src/tp_codecheck/tp03/part1/TrafficLight2.java delete mode 100644 1ano/2semestre/poo/src/tp_codecheck/tp03/part2/RentalCar.java diff --git a/1ano/2semestre/poo/src/aula01/KmToMiles.java b/1ano/2semestre/poo/src/aula01/KmToMiles.java index 4cb1057..581ccba 100644 --- a/1ano/2semestre/poo/src/aula01/KmToMiles.java +++ b/1ano/2semestre/poo/src/aula01/KmToMiles.java @@ -1,14 +1,15 @@ package aula01; + import java.util.Scanner; public class KmToMiles { - public static void main(String[] args) { - double km, miles; - Scanner sc = new Scanner(System.in); - System.out.print("Insira distância em km: "); - km = sc.nextDouble(); - miles = km / 1.609; - System.out.println("A distância em milhas é " + miles); - sc.close(); - } + public static void main(String[] args) { + double km, miles; + Scanner sc = new Scanner(System.in); + System.out.print("Insira distância em km: "); + km = sc.nextDouble(); + miles = km / 1.609; + System.out.println("A distância em milhas é " + miles); + sc.close(); + } } diff --git a/1ano/2semestre/poo/src/aula01/MyFirstClass.java b/1ano/2semestre/poo/src/aula01/MyFirstClass.java index 796323a..bdc21aa 100644 --- a/1ano/2semestre/poo/src/aula01/MyFirstClass.java +++ b/1ano/2semestre/poo/src/aula01/MyFirstClass.java @@ -2,12 +2,12 @@ package aula01; public class MyFirstClass { - public static void main(String[] args) { - System.out.println("Hello Eclipse!"); - int sum = 0; - for (int i = 1; i <= 100; i++) { - sum += i; - } - System.out.println(sum); - } + public static void main(String[] args) { + System.out.println("Hello Eclipse!"); + int sum = 0; + for (int i = 1; i <= 100; i++) { + sum += i; + } + System.out.println(sum); + } } \ No newline at end of file diff --git a/1ano/2semestre/poo/src/aula01/PescadaDeRaboNaBoca.java b/1ano/2semestre/poo/src/aula01/PescadaDeRaboNaBoca.java index a9c5728..ad0776f 100644 --- a/1ano/2semestre/poo/src/aula01/PescadaDeRaboNaBoca.java +++ b/1ano/2semestre/poo/src/aula01/PescadaDeRaboNaBoca.java @@ -2,15 +2,15 @@ package aula01; public class PescadaDeRaboNaBoca { - public static void main(String[] args) { - recursivoSimples(100); - } + public static void main(String[] args) { + recursivoSimples(100); + } - public static void recursivoSimples(int x) { - System.out.println(x); - x--; - if (x>0) - recursivoSimples(x); - } + public static void recursivoSimples(int x) { + System.out.println(x); + x--; + if (x > 0) + recursivoSimples(x); + } } diff --git a/1ano/2semestre/poo/src/aula01/ReadFileExample.java b/1ano/2semestre/poo/src/aula01/ReadFileExample.java index 2bd2c8a..a575cc2 100644 --- a/1ano/2semestre/poo/src/aula01/ReadFileExample.java +++ b/1ano/2semestre/poo/src/aula01/ReadFileExample.java @@ -1,4 +1,5 @@ package aula01; + import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; @@ -7,12 +8,12 @@ import java.nio.file.Paths; public class ReadFileExample { - public static void main(String[] args) { - Path fich = Paths.get("datafiles/aula01/major.txt"); - try { - Files.readAllLines(fich).stream().forEach(System.out::println); - } catch (IOException e) { - System.out.println("Certifique-se que o ficheiro \"major.txt\" está na raiz da pasta do projeto"); - } - } + public static void main(String[] args) { + Path fich = Paths.get("datafiles/aula01/major.txt"); + try { + Files.readAllLines(fich).stream().forEach(System.out::println); + } catch (IOException e) { + System.out.println("Certifique-se que o ficheiro \"major.txt\" está na raiz da pasta do projeto"); + } + } } diff --git a/1ano/2semestre/poo/src/aula01/StringExample.java b/1ano/2semestre/poo/src/aula01/StringExample.java index 063ce44..2e49396 100644 --- a/1ano/2semestre/poo/src/aula01/StringExample.java +++ b/1ano/2semestre/poo/src/aula01/StringExample.java @@ -1,11 +1,11 @@ package aula01; public class StringExample { - public static void main(String[] args) { - String s1 = "programar em Java"; - System.out.println(s1.split(" ")[0] + " é engraçado!! :)"); - System.out.println("É giro " + s1); - for (int i=0; i<14; i++) - System.out.println("vamos " + s1 + " na aula " + i); - } + public static void main(String[] args) { + String s1 = "programar em Java"; + System.out.println(s1.split(" ")[0] + " é engraçado!! :)"); + System.out.println("É giro " + s1); + for (int i = 0; i < 14; i++) + System.out.println("vamos " + s1 + " na aula " + i); + } } \ No newline at end of file diff --git a/1ano/2semestre/poo/src/aula02/CelciusToFahrenheit.java b/1ano/2semestre/poo/src/aula02/CelciusToFahrenheit.java index 2a5f030..b4a344e 100644 --- a/1ano/2semestre/poo/src/aula02/CelciusToFahrenheit.java +++ b/1ano/2semestre/poo/src/aula02/CelciusToFahrenheit.java @@ -9,7 +9,7 @@ public class CelciusToFahrenheit { System.out.print("ºC? "); Scanner sin = new Scanner(System.in); double celcius = sin.nextDouble(); - double fahrenheit = 1.8*celcius+32; + double fahrenheit = 1.8 * celcius + 32; System.out.printf("%.2fºC = %.2fºF\n", celcius, fahrenheit); sin.close(); diff --git a/1ano/2semestre/poo/src/aula02/Countdown.java b/1ano/2semestre/poo/src/aula02/Countdown.java index d04bffb..71b2d6f 100644 --- a/1ano/2semestre/poo/src/aula02/Countdown.java +++ b/1ano/2semestre/poo/src/aula02/Countdown.java @@ -5,7 +5,7 @@ import java.util.Scanner; // Solução do exercício 9 public class Countdown { - public static void main(String[] args){ + public static void main(String[] args) { Scanner sin = new Scanner(System.in); System.out.print("N? "); @@ -13,7 +13,7 @@ public class Countdown { for (int i = n; i >= 0; i--) { // If the statement before '?' is true then the expression before the ':' is used, else the expression after the ':' is used. // In python: i + "\n" if i%10 == 0 else i + "," - System.out.print(i%10 == 0 ? i + "\n" : i + ","); + System.out.print(i % 10 == 0 ? i + "\n" : i + ","); } sin.close(); diff --git a/1ano/2semestre/poo/src/aula02/DistanceBetweenPoints.java b/1ano/2semestre/poo/src/aula02/DistanceBetweenPoints.java index f936bec..8e7f57b 100644 --- a/1ano/2semestre/poo/src/aula02/DistanceBetweenPoints.java +++ b/1ano/2semestre/poo/src/aula02/DistanceBetweenPoints.java @@ -2,6 +2,7 @@ package aula02; // Código da package utils disponível em // https://github.com/TiagoRG/uaveiro-leci/tree/master/1ano/2semestre/poo/src/utils + import utils.UserInput; import java.util.Scanner; @@ -9,7 +10,7 @@ import java.util.Scanner; // Solução do exercício 7 public class DistanceBetweenPoints { - public static void main(String[] args){ + public static void main(String[] args) { Scanner sin = new Scanner(System.in); String[] p1 = UserInput.input(sin, "Coordenadas do ponto 1 (separadas por ','): ").split(","); @@ -17,7 +18,7 @@ public class DistanceBetweenPoints { double distance = Math.sqrt( Math.pow(Double.parseDouble(p1[0]) - Double.parseDouble(p2[0]), 2) + - Math.pow(Double.parseDouble(p1[1]) - Double.parseDouble(p2[1]), 2)); + Math.pow(Double.parseDouble(p1[1]) - Double.parseDouble(p2[1]), 2)); System.out.printf("A distância entre os dois pontos é %.3f\n", distance); diff --git a/1ano/2semestre/poo/src/aula02/EnergyToHeatWater.java b/1ano/2semestre/poo/src/aula02/EnergyToHeatWater.java index 1c3b9e0..cb86106 100644 --- a/1ano/2semestre/poo/src/aula02/EnergyToHeatWater.java +++ b/1ano/2semestre/poo/src/aula02/EnergyToHeatWater.java @@ -2,6 +2,7 @@ package aula02; // Código da package utils disponível em // https://github.com/TiagoRG/uaveiro-leci/tree/master/1ano/2semestre/poo/src/utils + import utils.UserInput; import java.util.Scanner; diff --git a/1ano/2semestre/poo/src/aula02/Investment.java b/1ano/2semestre/poo/src/aula02/Investment.java index 19fb880..b3ee7bd 100644 --- a/1ano/2semestre/poo/src/aula02/Investment.java +++ b/1ano/2semestre/poo/src/aula02/Investment.java @@ -2,6 +2,7 @@ package aula02; // Código da package utils disponível em // https://github.com/TiagoRG/uaveiro-leci/tree/master/1ano/2semestre/poo/src/utils + import utils.UserInput; import java.util.Scanner; @@ -15,7 +16,7 @@ public class Investment { double initialWallet = UserInput.getPositiveNumber(sin); System.out.print("Taxa de juro mensal (%)? "); double tax = sin.nextDouble(); - double finalWallet = initialWallet * Math.pow(1 + tax/100, 3); + double finalWallet = initialWallet * Math.pow(1 + tax / 100, 3); System.out.printf("O saldo final será de %.2f euros\n", finalWallet); sin.close(); diff --git a/1ano/2semestre/poo/src/aula02/KmToMiles.java b/1ano/2semestre/poo/src/aula02/KmToMiles.java index ecacd6e..7eb768c 100644 --- a/1ano/2semestre/poo/src/aula02/KmToMiles.java +++ b/1ano/2semestre/poo/src/aula02/KmToMiles.java @@ -2,6 +2,7 @@ package aula02; // Código da package utils disponível em // https://github.com/TiagoRG/uaveiro-leci/tree/master/1ano/2semestre/poo/src/utils + import utils.UserInput; import java.util.Scanner; diff --git a/1ano/2semestre/poo/src/aula02/PythagoreanTheorem.java b/1ano/2semestre/poo/src/aula02/PythagoreanTheorem.java index 2a97f93..66dd2bc 100644 --- a/1ano/2semestre/poo/src/aula02/PythagoreanTheorem.java +++ b/1ano/2semestre/poo/src/aula02/PythagoreanTheorem.java @@ -2,6 +2,7 @@ package aula02; // Código da package utils disponível em // https://github.com/TiagoRG/uaveiro-leci/tree/master/1ano/2semestre/poo/src/utils + import utils.UserInput; import java.util.Scanner; @@ -9,7 +10,7 @@ import java.util.Scanner; // Solução do exercício 8 public class PythagoreanTheorem { - public static void main(String[] args){ + public static void main(String[] args) { Scanner sin = new Scanner(System.in); System.out.println("Cateto A:"); diff --git a/1ano/2semestre/poo/src/aula02/RealNumbers.java b/1ano/2semestre/poo/src/aula02/RealNumbers.java index 9b4675f..d196a5f 100644 --- a/1ano/2semestre/poo/src/aula02/RealNumbers.java +++ b/1ano/2semestre/poo/src/aula02/RealNumbers.java @@ -5,7 +5,7 @@ import java.util.Scanner; // Solução do exercício 10 public class RealNumbers { - public static void main(String[] args){ + public static void main(String[] args) { Scanner sin = new Scanner(System.in); int readNumbers = 1; @@ -27,7 +27,7 @@ public class RealNumbers { ++readNumbers; } while (n != first); - System.out.printf("Valor máximo: %f\nValor mínimo: %f\nMédia: %f\nTotal: %f\n", max, min, (float) sum/readNumbers, sum); + System.out.printf("Valor máximo: %f\nValor mínimo: %f\nMédia: %f\nTotal: %f\n", max, min, (float) sum / readNumbers, sum); sin.close(); } diff --git a/1ano/2semestre/poo/src/aula02/SecsToHMS.java b/1ano/2semestre/poo/src/aula02/SecsToHMS.java index d276bd0..580a55b 100644 --- a/1ano/2semestre/poo/src/aula02/SecsToHMS.java +++ b/1ano/2semestre/poo/src/aula02/SecsToHMS.java @@ -2,6 +2,7 @@ package aula02; // Código da package utils disponível em // https://github.com/TiagoRG/uaveiro-leci/tree/master/1ano/2semestre/poo/src/utils + import utils.UserInput; import java.util.Scanner; @@ -9,7 +10,7 @@ import java.util.Scanner; // Solução do exercício 6 public class SecsToHMS { - public static void main(String[] args){ + public static void main(String[] args) { Scanner sin = new Scanner(System.in); System.out.println("Introduza os segundos totais: "); diff --git a/1ano/2semestre/poo/src/aula03/Calendar.java b/1ano/2semestre/poo/src/aula03/Calendar.java index 5e034cd..dca98e3 100644 --- a/1ano/2semestre/poo/src/aula03/Calendar.java +++ b/1ano/2semestre/poo/src/aula03/Calendar.java @@ -47,13 +47,13 @@ public class Calendar { private static void printCalendar(int[] data, int monthDays) { String[] monthNames = {"Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"}; - System.out.printf("\n%15s %d\n", monthNames[data[0]-1], data[1]); + System.out.printf("\n%15s %d\n", monthNames[data[0] - 1], data[1]); System.out.println("Dom Seg Ter Qua Qui Sex Sab"); if (data[2] != 7) for (int i = 0; i < data[2]; i++) System.out.print(" "); - + for (int monthDay = 1; monthDay <= monthDays; monthDay++) { System.out.printf("%3d ", monthDay); if ((monthDay + data[2]) % 7 == 0) diff --git a/1ano/2semestre/poo/src/aula03/Grades.java b/1ano/2semestre/poo/src/aula03/Grades.java index 493ab79..e170441 100644 --- a/1ano/2semestre/poo/src/aula03/Grades.java +++ b/1ano/2semestre/poo/src/aula03/Grades.java @@ -8,24 +8,24 @@ import java.util.Scanner; public class Grades { private static final Scanner sin = new Scanner(System.in); - + public static void main(String[] args) { System.out.print("Quantos alunos tem a turma? "); int studentCount = sin.nextInt(); Student[] students = new Student[studentCount]; for (int i = 0; i < studentCount; i++) { - System.out.printf("Nota teórica do aluno %d: ", i+1); + System.out.printf("Nota teórica do aluno %d: ", i + 1); double notaT = UserInput.getNumberBetween(sin, 0, 20); - System.out.printf("Nota prática do aluno %d: ", i+1); + System.out.printf("Nota prática do aluno %d: ", i + 1); double notaP = UserInput.getNumberBetween(sin, 0, 20); students[i] = new Student(notaT, notaP); } - + printGrades(students); System.out.println(); } - + private static void printGrades(Student[] students) { System.out.println("NotaT NotaP Pauta"); for (Student student : students) { diff --git a/1ano/2semestre/poo/src/aula03/GradesRandom.java b/1ano/2semestre/poo/src/aula03/GradesRandom.java index 3ee3ad8..cf7b415 100644 --- a/1ano/2semestre/poo/src/aula03/GradesRandom.java +++ b/1ano/2semestre/poo/src/aula03/GradesRandom.java @@ -9,7 +9,7 @@ import java.util.Scanner; public class GradesRandom { private static final Scanner sin = new Scanner(System.in); private static final Random rand = new Random(); - + public static void main(String[] args) { System.out.print("Quantos alunos tem a turma? "); int studentCount = sin.nextInt(); diff --git a/1ano/2semestre/poo/src/aula03/Investment.java b/1ano/2semestre/poo/src/aula03/Investment.java index e3108aa..fbf4630 100644 --- a/1ano/2semestre/poo/src/aula03/Investment.java +++ b/1ano/2semestre/poo/src/aula03/Investment.java @@ -20,8 +20,8 @@ public class Investment { double tax = UserInput.getNumberBetween(sin, 0, 5); for (int i = 1; i <= 12; i++) { - investment *= 1+tax/100; - System.out.printf("Investimento em %d %s: %.2f\n", i, i==1?"mês":"meses", investment); + investment *= 1 + tax / 100; + System.out.printf("Investimento em %d %s: %.2f\n", i, i == 1 ? "mês" : "meses", investment); } sin.close(); diff --git a/1ano/2semestre/poo/src/aula03/StringExtras.java b/1ano/2semestre/poo/src/aula03/StringExtras.java index dcf6908..015953e 100644 --- a/1ano/2semestre/poo/src/aula03/StringExtras.java +++ b/1ano/2semestre/poo/src/aula03/StringExtras.java @@ -11,7 +11,7 @@ public class StringExtras { String str = sin.nextLine(); System.out.println("Frase convertida para minúsculas: " + str.toLowerCase()); - System.out.println("Último caracter da frase: " + str.substring(str.length()-1)); + System.out.println("Último caracter da frase: " + str.substring(str.length() - 1)); System.out.println("Os 3 primeiros caracteres: " + str.substring(0, 3)); System.out.printf("Número de digitos na frase: %d\n", StringMethods.countDigits(str)); System.out.printf("Número de espaços na frase: %d\n", StringMethods.countSpaces(str)); diff --git a/1ano/2semestre/poo/src/aula04/CarDemo.java b/1ano/2semestre/poo/src/aula04/CarDemo.java index cef216e..2ea8f16 100644 --- a/1ano/2semestre/poo/src/aula04/CarDemo.java +++ b/1ano/2semestre/poo/src/aula04/CarDemo.java @@ -23,7 +23,7 @@ public class CarDemo { System.out.println("Dados mal formatados. Tente novamente."); } else { String model = String.join(" ", Arrays.stream(parts, 1, parts.length - 2).toArray(String[]::new)); - cars[i] = new Car(parts[0], model, Integer.parseInt(parts[parts.length-2]), Integer.parseInt(parts[parts.length-1])); + cars[i] = new Car(parts[0], model, Integer.parseInt(parts[parts.length - 2]), Integer.parseInt(parts[parts.length - 1])); } } } @@ -33,8 +33,8 @@ public class CarDemo { static boolean validateData(String[] parts) { if (parts.length < 4) return false; try { - Integer.parseInt(parts[parts.length-1]); - if (String.format("%d", Integer.parseInt(parts[parts.length-2])).length() != 4) return false; + Integer.parseInt(parts[parts.length - 1]); + if (String.format("%d", Integer.parseInt(parts[parts.length - 2])).length() != 4) return false; } catch (NumberFormatException e) { return false; } @@ -80,7 +80,7 @@ public class CarDemo { System.out.println(car); } } - + System.out.println("\n"); } @@ -90,7 +90,7 @@ public class CarDemo { int numCars = registerCars(cars); - if (numCars>0) { + if (numCars > 0) { listCars(cars); registerTrips(cars, numCars); listCars(cars); diff --git a/1ano/2semestre/poo/src/aula04/CashRegisterDemo.java b/1ano/2semestre/poo/src/aula04/CashRegisterDemo.java index 36f6c44..d29bd1b 100644 --- a/1ano/2semestre/poo/src/aula04/CashRegisterDemo.java +++ b/1ano/2semestre/poo/src/aula04/CashRegisterDemo.java @@ -23,7 +23,7 @@ class Product { return price; } - public int getQuantity() { + public int getQuantity() { return quantity; } } @@ -77,7 +77,7 @@ public class CashRegisterDemo { cr.addProduct(new Product("Headphones", 29.99, 2)); cr.addProduct(new Product("Notebook", 19.99, 5)); cr.addProduct(new Product("Phone case", 5.99, 1)); - + // TODO: Listar o conteúdo e valor total System.out.println(cr); diff --git a/1ano/2semestre/poo/src/aula04/Shapes.java b/1ano/2semestre/poo/src/aula04/Shapes.java index 0e739b3..c4cec96 100644 --- a/1ano/2semestre/poo/src/aula04/Shapes.java +++ b/1ano/2semestre/poo/src/aula04/Shapes.java @@ -6,7 +6,7 @@ import java.util.Scanner; class Circle { public double radius; - + public Circle(double radius) { if (!(radius > 0)) throw new IllegalArgumentException("Sizes must be positive."); @@ -48,7 +48,7 @@ class Triangle { public Triangle(double side1, double side2, double side3) { if (!(side1 > 0 && side2 > 0 && side3 > 0)) throw new IllegalArgumentException("Sizes must be positive."); - if(!(side1 < side2 + side3 && side2 < side1 + side3 && side3 < side1 + side2)) + if (!(side1 < side2 + side3 && side2 < side1 + side3 && side3 < side1 + side2)) throw new IllegalArgumentException("Triangle cannot be created with those sides."); this.side1 = side1; this.side2 = side2; @@ -56,13 +56,13 @@ class Triangle { } public double[] getSides() { - return new double[] {this.side1, this.side2, this.side3}; + return new double[]{this.side1, this.side2, this.side3}; } public void setSides(double side1, double side2, double side3) { if (!(side1 > 0 && side2 > 0 && side3 > 0)) throw new IllegalArgumentException("Sizes must be positive."); - if(!(side1 < side2 + side3 && side2 < side1 + side3 && side3 < side1 + side2)) + if (!(side1 < side2 + side3 && side2 < side1 + side3 && side3 < side1 + side2)) throw new IllegalArgumentException("Triangle cannot be created with those sides."); this.side1 = side1; this.side2 = side2; @@ -99,7 +99,7 @@ class Rectangle { } public double[] getSides() { - return new double[] {this.side1, this.side2}; + return new double[]{this.side1, this.side2}; } public void setSides(double side1, double side2) { diff --git a/1ano/2semestre/poo/src/aula04/SimpleCarDemo.java b/1ano/2semestre/poo/src/aula04/SimpleCarDemo.java index 5fe3eaa..4b2d55f 100644 --- a/1ano/2semestre/poo/src/aula04/SimpleCarDemo.java +++ b/1ano/2semestre/poo/src/aula04/SimpleCarDemo.java @@ -32,11 +32,11 @@ public class SimpleCarDemo { listCars(cars); // Adicionar 10 viagens geradas aleatoriamente - for (int i=0; i<10; i++) { - int j = (int)Math.round(Math.random()*2); // escolhe um dos 3 carros - int kms = (int)Math.round(Math.random()*1000); // viagem até 1000 kms + for (int i = 0; i < 10; i++) { + int j = (int) Math.round(Math.random() * 2); // escolhe um dos 3 carros + int kms = (int) Math.round(Math.random() * 1000); // viagem até 1000 kms System.out.printf("Carro %d viajou %d quilómetros.\n", j, kms); - + // TODO: adicionar viagem ao carro j cars[j].drive(kms); } diff --git a/1ano/2semestre/poo/src/aula05/AuctionDemo.java b/1ano/2semestre/poo/src/aula05/AuctionDemo.java index 036e920..1717a3f 100644 --- a/1ano/2semestre/poo/src/aula05/AuctionDemo.java +++ b/1ano/2semestre/poo/src/aula05/AuctionDemo.java @@ -21,23 +21,23 @@ public class AuctionDemo { } class RealEstate { - private final Property[] properties; - private int currentId; + private final Property[] properties; + private int currentId; - public RealEstate() { - this.properties = new Property[10]; - this.currentId = 1000; - } + public RealEstate() { + this.properties = new Property[10]; + this.currentId = 1000; + } - public void newProperty(String address, int rooms, int price) { - Property newProperty = new Property(currentId++, address, rooms, price); - for (int i = 0; i < this.properties.length; i++) { - if (this.properties[i] == null) { - this.properties[i] = newProperty; - break; - } - } - } + public void newProperty(String address, int rooms, int price) { + Property newProperty = new Property(currentId++, address, rooms, price); + for (int i = 0; i < this.properties.length; i++) { + if (this.properties[i] == null) { + this.properties[i] = newProperty; + break; + } + } + } public void sell(int id) { for (Property property : this.properties) { @@ -53,7 +53,7 @@ class RealEstate { } } System.out.printf("Imóvel %d não existe.\n", id); - } + } public void setAuction(int id, DateYMD date, int duration) { for (Property property : this.properties) { @@ -103,9 +103,11 @@ class Property { public int getId() { return this.id; } + public boolean isAvailable() { return this.availability; } + public void setAvailability(boolean availability) { this.availability = availability; } @@ -116,7 +118,7 @@ class Property { } public DateYMD[] getAuction() { - return new DateYMD[] {this.auctionBegin, this.auctionEnd}; + return new DateYMD[]{this.auctionBegin, this.auctionEnd}; } public boolean isAuction() { diff --git a/1ano/2semestre/poo/src/aula05/Calendar.java b/1ano/2semestre/poo/src/aula05/Calendar.java index 04a6677..75716ef 100644 --- a/1ano/2semestre/poo/src/aula05/Calendar.java +++ b/1ano/2semestre/poo/src/aula05/Calendar.java @@ -33,18 +33,18 @@ public class Calendar { day -= 7; day++; } - return day == 7 ? 7 : day%7; + return day == 7 ? 7 : day % 7; } public void printMonth(int month) { String[] monthNames = {"Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"}; - System.out.printf("\n%15s %d\n", monthNames[month-1], year); + System.out.printf("\n%15s %d\n", monthNames[month - 1], year); System.out.println("Dom Seg Ter Qua Qui Sex Sab"); int firstWeekday = this.firstWeekdayOfMonth(month); for (int i = 1; i < firstWeekday; i++) System.out.print(" "); - + for (int monthDay = 1; monthDay <= monthDays(month, year); monthDay++) { System.out.print(this.isEvent(monthDay, month, this.year) ? String.format("*%2d ", monthDay) : String.format("%3d ", monthDay)); if ((monthDay + firstWeekday - 1) % 7 == 0) diff --git a/1ano/2semestre/poo/src/aula05/DateYMD.java b/1ano/2semestre/poo/src/aula05/DateYMD.java index 74392d0..9ed5a54 100644 --- a/1ano/2semestre/poo/src/aula05/DateYMD.java +++ b/1ano/2semestre/poo/src/aula05/DateYMD.java @@ -15,6 +15,27 @@ public class DateYMD { this.year = year; } + static boolean validMonth(int month) { + return month >= 1 && month <= 12; + } + + static int monthDays(int month, int year) { + if (!validMonth(month)) + return -1; + int[] daysPerMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; + if (month == 2 && isLeapYear(year)) + return 29; + return daysPerMonth[month - 1]; + } + + static boolean isLeapYear(int year) { + return year % 100 == 0 ? year % 400 == 0 : year % 4 == 0; + } + + static boolean validDate(int day, int month, int year) { + return day >= 1 && day <= monthDays(month, year); + } + public void set(int day, int month, int year) { if (!validDate(day, month, year)) throw new IllegalArgumentException("Invalid date"); @@ -73,26 +94,6 @@ public class DateYMD { public String toString() { return String.format("%04d-%02d-%02d", this.year, this.month, this.day); } - static boolean validMonth(int month) { - return month >= 1 && month <= 12; - } - - static int monthDays(int month, int year) { - if (!validMonth(month)) - return -1; - int[] daysPerMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; - if (month == 2 && isLeapYear(year)) - return 29; - return daysPerMonth[month - 1]; - } - - static boolean isLeapYear(int year) { - return year % 100 == 0 ? year % 400 == 0 : year % 4 == 0; - } - - static boolean validDate(int day, int month, int year) { - return day >= 1 && day <= monthDays(month, year); - } } class TestDateYMD { diff --git a/1ano/2semestre/poo/src/aula06/ex1/Bolser.java b/1ano/2semestre/poo/src/aula06/ex1/Bolser.java index 721220e..ef603af 100644 --- a/1ano/2semestre/poo/src/aula06/ex1/Bolser.java +++ b/1ano/2semestre/poo/src/aula06/ex1/Bolser.java @@ -2,7 +2,7 @@ package aula06.ex1; import utils.DateYMD; -public class Bolser extends Student{ +public class Bolser extends Student { private Professor supervisor; private double monthlyAmount; @@ -19,6 +19,7 @@ public class Bolser extends Student{ public Professor getSupervisor() { return this.supervisor; } + public void setSupervisor(Professor supervisor) { if (supervisor == null) { throw new IllegalArgumentException("Supervisor cannot be null"); @@ -29,6 +30,7 @@ public class Bolser extends Student{ public double getMonthlyAmount() { return this.monthlyAmount; } + public void setMonthlyAmount(double monthlyAmount) { if (monthlyAmount < 0) { throw new IllegalArgumentException("Monthly amount cannot be negative"); diff --git a/1ano/2semestre/poo/src/aula06/ex1/Person.java b/1ano/2semestre/poo/src/aula06/ex1/Person.java index 4512c05..bc26910 100644 --- a/1ano/2semestre/poo/src/aula06/ex1/Person.java +++ b/1ano/2semestre/poo/src/aula06/ex1/Person.java @@ -18,6 +18,7 @@ public class Person { public String getName() { return this.name; } + public void setName(String name) { if (name == null || name.isEmpty()) throw new IllegalArgumentException("Name cannot be null or empty"); @@ -27,6 +28,7 @@ public class Person { public int getCc() { return this.cc; } + public void setCc(int cc) { if (String.valueOf(cc).length() != 8) throw new IllegalArgumentException("CC must have 8 digits"); @@ -36,6 +38,7 @@ public class Person { public DateYMD getBirthDate() { return this.birthDate; } + public void setBirthDate(DateYMD birthDate) { if (birthDate == null) throw new IllegalArgumentException("Birth date cannot be null"); diff --git a/1ano/2semestre/poo/src/aula06/ex1/PersonTest.java b/1ano/2semestre/poo/src/aula06/ex1/PersonTest.java index 64362c4..0403a8a 100644 --- a/1ano/2semestre/poo/src/aula06/ex1/PersonTest.java +++ b/1ano/2semestre/poo/src/aula06/ex1/PersonTest.java @@ -8,13 +8,13 @@ public class PersonTest { public static void main(String[] args) { Scanner sin = new Scanner(System.in); - Student al = new Student ("Andreia Melo", 98556781,new DateYMD(18, 7, 1990), new DateYMD(1, 9, 2018)); + Student al = new Student("Andreia Melo", 98556781, new DateYMD(18, 7, 1990), new DateYMD(1, 9, 2018)); Professor p1 = new Professor("Jorge Almeida", 34672215, new DateYMD(13, 3, 1967), "Associado", "Informática"); - Bolser bls = new Bolser ("Igor Santos", 89765431, new DateYMD(11, 5, 1985), p1, 900); + Bolser bls = new Bolser("Igor Santos", 89765431, new DateYMD(11, 5, 1985), p1, 900); bls.setMonthlyAmount(1050); - System.out.println("Student:"+ al.getName()); + System.out.println("Student:" + al.getName()); System.out.println(al); - System.out.println("Bolser:"+ bls.getName() + ", NMec: " + bls.getNMec() + ", Bolsa:" + bls.getMonthlyAmount()+ ", Orientador:" + bls.getSupervisor()); + System.out.println("Bolser:" + bls.getName() + ", NMec: " + bls.getNMec() + ", Bolsa:" + bls.getMonthlyAmount() + ", Orientador:" + bls.getSupervisor()); System.out.println(bls); sin.close(); diff --git a/1ano/2semestre/poo/src/aula06/ex1/Professor.java b/1ano/2semestre/poo/src/aula06/ex1/Professor.java index 7f1bfd3..a2fc03b 100644 --- a/1ano/2semestre/poo/src/aula06/ex1/Professor.java +++ b/1ano/2semestre/poo/src/aula06/ex1/Professor.java @@ -15,6 +15,7 @@ public class Professor extends Person { public String getCategory() { return this.category; } + public void setCategory(String category) { if (category == null || category.isEmpty()) throw new IllegalArgumentException("Category cannot be null or empty"); @@ -26,6 +27,7 @@ public class Professor extends Person { public String getDepartment() { return this.department; } + public void setDepartment(String department) { if (department == null || department.isEmpty()) throw new IllegalArgumentException("Department cannot be null or empty"); diff --git a/1ano/2semestre/poo/src/aula06/ex1/Student.java b/1ano/2semestre/poo/src/aula06/ex1/Student.java index b759397..9af2e31 100644 --- a/1ano/2semestre/poo/src/aula06/ex1/Student.java +++ b/1ano/2semestre/poo/src/aula06/ex1/Student.java @@ -5,9 +5,9 @@ import utils.DateYMD; import java.time.LocalDate; public class Student extends Person { + public static int currentNMec = 100; private DateYMD registrationDate; private int nMec; - public static int currentNMec = 100; public Student(String name, int cc, DateYMD birthDate, DateYMD registrationDate) { super(name, cc, birthDate); @@ -22,6 +22,7 @@ public class Student extends Person { public int getNMec() { return this.nMec; } + public void setNMec(int nMec) { this.nMec = nMec; } @@ -29,6 +30,7 @@ public class Student extends Person { public DateYMD getRegistrationDate() { return this.registrationDate; } + public void setRegistrationDate(DateYMD registrationDate) { LocalDate now = LocalDate.now(); this.registrationDate = registrationDate == null ? new DateYMD(now.getDayOfMonth(), now.getMonthValue(), now.getYear()) : registrationDate; diff --git a/1ano/2semestre/poo/src/aula06/ex2/Contact.java b/1ano/2semestre/poo/src/aula06/ex2/Contact.java index 8737fff..666bb62 100644 --- a/1ano/2semestre/poo/src/aula06/ex2/Contact.java +++ b/1ano/2semestre/poo/src/aula06/ex2/Contact.java @@ -3,13 +3,12 @@ package aula06.ex2; import aula06.ex1.Person; public class Contact { + private static int currentId = 1; private final int id; private Person person; private String email; private String phone; - private static int currentId = 1; - public Contact(Person person, String email, String phone) { if ((email == null || email.isEmpty()) && (phone == null || phone.isEmpty())) throw new IllegalArgumentException("Either email or phone must be provided"); @@ -26,6 +25,7 @@ public class Contact { public Person getPerson() { return person; } + public void setPerson(Person person) { if (person == null) throw new IllegalArgumentException("Person must be provided"); @@ -35,9 +35,10 @@ public class Contact { public String getEmail() { return email; } + public void setEmail(String email) { if (!(email == null || email.isEmpty()) && - !email.matches("^[a-zA-Z_0-9.]+@[a-zA-Z_0-9.]+\\.[a-zA-Z_0-9]+$")) + !email.matches("^[a-zA-Z_0-9.]+@[a-zA-Z_0-9.]+\\.[a-zA-Z_0-9]+$")) throw new IllegalArgumentException("Invalid email"); this.email = email; } @@ -45,9 +46,10 @@ public class Contact { public String getPhone() { return phone; } + public void setPhone(String phone) { if (!(phone == null || phone.isEmpty()) && - !phone.matches("^9[0-9]{8}$")) + !phone.matches("^9[0-9]{8}$")) throw new IllegalArgumentException("Invalid phone"); this.phone = phone; } diff --git a/1ano/2semestre/poo/src/aula06/ex2/ContactList.java b/1ano/2semestre/poo/src/aula06/ex2/ContactList.java index 2646ede..3bbb213 100644 --- a/1ano/2semestre/poo/src/aula06/ex2/ContactList.java +++ b/1ano/2semestre/poo/src/aula06/ex2/ContactList.java @@ -40,6 +40,7 @@ public class ContactList { System.out.print("> "); return sin.nextLine(); } + private static void addContact() { System.out.print("Insira o nome: "); String name = sin.nextLine(); @@ -69,6 +70,7 @@ public class ContactList { contacts = newContacts; } } + private static void changeContact() { System.out.print("Insira o nome, email ou telefone do contacto que pretende alterar: "); String query = sin.nextLine(); diff --git a/1ano/2semestre/poo/src/aula06/ex3/Vector.java b/1ano/2semestre/poo/src/aula06/ex3/Vector.java index f50f506..70a0149 100644 --- a/1ano/2semestre/poo/src/aula06/ex3/Vector.java +++ b/1ano/2semestre/poo/src/aula06/ex3/Vector.java @@ -7,12 +7,15 @@ public class Vector { public Vector() { this.vector = new int[0]; } + public Vector(int size) { this.vector = new int[size]; } + public Vector(int[] vector) { this.vector = vector; } + public int[] getVector() { return vector; } @@ -21,12 +24,14 @@ public class Vector { public int size() { return this.vector.length; } + public boolean contains(int value) { for (int n : this.vector) if (n == value) return true; return false; } + public int count(int value) { int count = 0; for (int n : this.vector) @@ -38,13 +43,14 @@ public class Vector { // Method to change values public void insert(int value) { if (this.contains(value)) return; - int[] aux = new int[this.size()+1]; + int[] aux = new int[this.size() + 1]; System.arraycopy(this.vector, 0, aux, 0, this.size()); aux[this.size()] = value; this.vector = aux; } + public void remove(int value) { - int[] aux = new int[this.size()-this.count(value)]; + int[] aux = new int[this.size() - this.count(value)]; int i = 0; for (int n : this.vector) { if (n == value) @@ -54,6 +60,7 @@ public class Vector { } this.vector = aux; } + public void empty() { this.vector = new int[0]; } @@ -69,6 +76,7 @@ public class Vector { result.insert(n); return result; } + public Vector subtract(Vector secondVector) { Vector result = new Vector(); for (int n : this.vector) @@ -76,6 +84,7 @@ public class Vector { result.insert(n); return result; } + public Vector intersect(Vector secondVector) { Vector result = new Vector(); for (int n : this.vector) @@ -90,6 +99,6 @@ public class Vector { StringBuilder result = new StringBuilder(); for (int n : this.vector) result.append(String.format("%d ", n)); - return this.size() > 0 ? result.substring(0, result.length()-1) : result.toString(); + return this.size() > 0 ? result.substring(0, result.length() - 1) : result.toString(); } } diff --git a/1ano/2semestre/poo/src/aula06/ex3/VectorTest.java b/1ano/2semestre/poo/src/aula06/ex3/VectorTest.java index 2fd895c..0f047b3 100644 --- a/1ano/2semestre/poo/src/aula06/ex3/VectorTest.java +++ b/1ano/2semestre/poo/src/aula06/ex3/VectorTest.java @@ -4,19 +4,24 @@ package aula06.ex3; public class VectorTest { public static void main(String[] args) { Vector c1 = new Vector(); - c1.insert(4); c1.insert(7); c1.insert(6); c1.insert(5); + c1.insert(4); + c1.insert(7); + c1.insert(6); + c1.insert(5); Vector c2 = new Vector(); - int[] test = { 7, 3, 2, 5, 4, 6, 7}; + int[] test = {7, 3, 2, 5, 4, 6, 7}; for (int el : test) c2.insert(el); - c2.remove(3); c2.remove(5); c2.remove(6); + c2.remove(3); + c2.remove(5); + c2.remove(6); System.out.println(c1); System.out.println(c2); System.out.println("Número de elementos em c1: " + c1.size()); System.out.println("Número de elementos em c2: " + c2.size()); - + System.out.println("c1 contém 6?: " + ((c1.contains(6) ? "sim" : "não"))); System.out.println("c2 contém 6?: " + ((c2.contains(6) ? "sim" : "não"))); diff --git a/1ano/2semestre/poo/src/aula07/ex1/Rectangle.java b/1ano/2semestre/poo/src/aula07/ex1/Rectangle.java index 868ac62..44f6da9 100644 --- a/1ano/2semestre/poo/src/aula07/ex1/Rectangle.java +++ b/1ano/2semestre/poo/src/aula07/ex1/Rectangle.java @@ -12,7 +12,7 @@ public class Rectangle extends Shape { } public double[] getSides() { - return new double[] {this.side1, this.side2}; + return new double[]{this.side1, this.side2}; } public void setSides(double side1, double side2) { @@ -33,7 +33,7 @@ public class Rectangle extends Shape { @Override public boolean equals(Shape s2) { if (s2 instanceof Rectangle s2Rect) - return Objects.equals(this.color, s2Rect.color) && this.side1 == s2Rect.side1 && this.side2 == s2Rect.side2; + return Objects.equals(this.color, s2Rect.color) && this.side1 == s2Rect.side1 && this.side2 == s2Rect.side2; return false; } diff --git a/1ano/2semestre/poo/src/aula07/ex1/Shape.java b/1ano/2semestre/poo/src/aula07/ex1/Shape.java index 6031cb2..1253b46 100644 --- a/1ano/2semestre/poo/src/aula07/ex1/Shape.java +++ b/1ano/2semestre/poo/src/aula07/ex1/Shape.java @@ -2,8 +2,12 @@ package aula07.ex1; public abstract class Shape { protected String color; + public abstract boolean equals(Shape c2); + public abstract String toString(); + public abstract double getArea(); + public abstract double getPerimeter(); } diff --git a/1ano/2semestre/poo/src/aula07/ex1/Triangle.java b/1ano/2semestre/poo/src/aula07/ex1/Triangle.java index 0c14e68..5c8b427 100644 --- a/1ano/2semestre/poo/src/aula07/ex1/Triangle.java +++ b/1ano/2semestre/poo/src/aula07/ex1/Triangle.java @@ -13,7 +13,7 @@ public class Triangle extends Shape { } public double[] getSides() { - return new double[] {this.side1, this.side2, this.side3}; + return new double[]{this.side1, this.side2, this.side3}; } public void setSides(double side1, double side2, double side3) { diff --git a/1ano/2semestre/poo/src/aula07/ex2/Date.java b/1ano/2semestre/poo/src/aula07/ex2/Date.java index 1d544d7..fa7fd54 100644 --- a/1ano/2semestre/poo/src/aula07/ex2/Date.java +++ b/1ano/2semestre/poo/src/aula07/ex2/Date.java @@ -1,16 +1,6 @@ package aula07.ex2; public abstract class Date { - public abstract int getAbsDay(); - public abstract int getDay(); - public abstract int getMonth(); - public abstract int getYear(); - public abstract void increment(); - public abstract void decrement(); - public abstract void addDays(int days); - public abstract void removeDays(int days); - - public static int monthDays(int month, int year) { if (!validMonth(month)) return -1; @@ -31,4 +21,20 @@ public abstract class Date { public static boolean isLeapYear(int year) { return year % 100 == 0 ? year % 400 == 0 : year % 4 == 0; } + + public abstract int getAbsDay(); + + public abstract int getDay(); + + public abstract int getMonth(); + + public abstract int getYear(); + + public abstract void increment(); + + public abstract void decrement(); + + public abstract void addDays(int days); + + public abstract void removeDays(int days); } diff --git a/1ano/2semestre/poo/src/aula07/ex2/DateTest.java b/1ano/2semestre/poo/src/aula07/ex2/DateTest.java index 303a21c..84612bb 100644 --- a/1ano/2semestre/poo/src/aula07/ex2/DateTest.java +++ b/1ano/2semestre/poo/src/aula07/ex2/DateTest.java @@ -6,7 +6,8 @@ public class DateTest { public static void main(String[] args) { Scanner sin = new Scanner(System.in); - mainLoop: while (true) { + mainLoop: + while (true) { System.out.print("Class to test (0-Quit;1-DateYMD;2-DateND): "); int classoption = sin.nextInt(); @@ -17,7 +18,8 @@ public class DateTest { } case 1 -> { DateYMD date = null; - class1Loop: while (true) { + class1Loop: + while (true) { System.out.println("Date operations:"); System.out.println("1 - Create date"); System.out.println("2 - Show current date"); @@ -28,8 +30,9 @@ public class DateTest { System.out.print("Option: "); int option = sin.nextInt(); if (option == 0) - break class1Loop; - class1Switch: switch (option) { + break; + class1Switch: + switch (option) { case 1 -> { System.out.print("Day: "); int day = sin.nextInt(); @@ -43,21 +46,21 @@ public class DateTest { case 2 -> { if (date == null) { System.out.println("Date not created"); - break class1Switch; + break; } System.out.println("Current date: " + date); } case 3 -> { if (date == null) { System.out.println("Date not created"); - break class1Switch; + break; } System.out.println("Current date: " + new DateND(date.getAbsDay())); } case 4 -> { if (date == null) { System.out.println("Date not created"); - break class1Switch; + break; } System.out.print("Number of days to increment date by: "); int daysToIncrement = sin.nextInt(); @@ -67,7 +70,7 @@ public class DateTest { case 5 -> { if (date == null) { System.out.println("Date not created"); - break class1Switch; + break; } System.out.print("Number of days to decremente date by: "); int daysToDecrement = sin.nextInt(); @@ -80,7 +83,8 @@ public class DateTest { } case 2 -> { DateND date = null; - class2Loop: while (true) { + class2Loop: + while (true) { System.out.println("Date operations:"); System.out.println("1 - Create date"); System.out.println("2 - Show current date"); @@ -91,8 +95,9 @@ public class DateTest { System.out.print("Option: "); int option = sin.nextInt(); if (option == 0) - break class2Loop; - class2Switch: switch (option) { + break; + class2Switch: + switch (option) { case 1 -> { System.out.print("Day: "); int day = sin.nextInt(); @@ -102,21 +107,21 @@ public class DateTest { case 2 -> { if (date == null) { System.out.println("Date not created"); - break class2Switch; + break; } System.out.println("Current date: " + date); } case 3 -> { if (date == null) { System.out.println("Date not created"); - break class2Switch; + break; } System.out.println("Current date: " + new DateYMD(date.getDay(), date.getMonth(), date.getYear())); } case 4 -> { if (date == null) { System.out.println("Date not created"); - break class2Switch; + break; } System.out.print("Number of days to increment date by: "); int daysToIncrement = sin.nextInt(); @@ -126,7 +131,7 @@ public class DateTest { case 5 -> { if (date == null) { System.out.println("Date not created"); - break class2Switch; + break; } System.out.print("Number of days to decremente date by: "); int daysToDecrement = sin.nextInt(); diff --git a/1ano/2semestre/poo/src/aula07/ex2/DateYMD.java b/1ano/2semestre/poo/src/aula07/ex2/DateYMD.java index e946917..6cdf84c 100644 --- a/1ano/2semestre/poo/src/aula07/ex2/DateYMD.java +++ b/1ano/2semestre/poo/src/aula07/ex2/DateYMD.java @@ -69,7 +69,7 @@ public class DateYMD extends Date { if (this.day > 1) this.day--; else { - this.day = monthDays(this.month == 1 ? 12 : this.month-1, this.year); + this.day = monthDays(this.month == 1 ? 12 : this.month - 1, this.year); if (this.month > 1) this.month--; else { diff --git a/1ano/2semestre/poo/src/aula07/ex3/Game.java b/1ano/2semestre/poo/src/aula07/ex3/Game.java index 0858ca8..d27369e 100644 --- a/1ano/2semestre/poo/src/aula07/ex3/Game.java +++ b/1ano/2semestre/poo/src/aula07/ex3/Game.java @@ -3,10 +3,10 @@ package aula07.ex3; public class Game { private final Team team1; private final Team team2; - private int team1Goals; - private int team2Goals; private final Ball ball; private final double gameDuration; + private int team1Goals; + private int team2Goals; private double timeElapsed; public Game(Team team1, Team team2, Ball ball, double gameDuration) { diff --git a/1ano/2semestre/poo/src/aula07/ex3/Main.java b/1ano/2semestre/poo/src/aula07/ex3/Main.java index 2e21af9..0e72758 100644 --- a/1ano/2semestre/poo/src/aula07/ex3/Main.java +++ b/1ano/2semestre/poo/src/aula07/ex3/Main.java @@ -38,13 +38,13 @@ public class Main { } System.out.println("Equipas:"); for (int i = 0; i < teams.length; i++) - System.out.println((i+1) + " - " + teams[i].getName()); + System.out.println((i + 1) + " - " + teams[i].getName()); System.out.print("Escolha a equipa 1: "); int team1Id = Integer.parseInt(sin.nextLine()); System.out.print("Escolha a equipa 2: "); int team2Id = Integer.parseInt(sin.nextLine()); - Team team1 = teams[team1Id-1]; - Team team2 = teams[team2Id-1]; + Team team1 = teams[team1Id - 1]; + Team team2 = teams[team2Id - 1]; System.out.println("Bola para o jogo:"); System.out.print("Cor da bola: "); String color = sin.nextLine(); @@ -60,9 +60,9 @@ public class Main { double duration = Double.parseDouble(durationString.equals("") ? "90" : durationString); Game game = new Game(team1, team2, ball, duration); if (games == null) - games = new Game[] { game }; + games = new Game[]{game}; else { - Game[] newGames = new Game[games.length+1]; + Game[] newGames = new Game[games.length + 1]; System.arraycopy(games, 0, newGames, 0, games.length); newGames[games.length] = game; games = newGames; @@ -75,7 +75,8 @@ public class Main { System.out.println("3 - Adicionar golo"); System.out.print("Opção: "); int option = Integer.parseInt(sin.nextLine()); - swit : switch (option) { + swit: + switch (option) { case 1 -> { System.out.print("Novo X: "); double x = Double.parseDouble(sin.nextLine()); @@ -86,7 +87,7 @@ public class Main { case 2 -> { System.out.println("Robots:"); for (Robot r : game.getTeam1().getRobots()) - System.out.println(r); + System.out.println(r); for (Robot r : game.getTeam2().getRobots()) System.out.println(r); System.out.print("Escolha o ID do robot: "); @@ -151,7 +152,7 @@ public class Main { int nRobots = Integer.parseInt(sin.nextLine()); Robot[] robots = new Robot[nRobots]; for (int i = 0; i < nRobots; i++) { - System.out.println("Robot " + (i+1)); + System.out.println("Robot " + (i + 1)); System.out.print("\n1 - GoalKeeper\n2 - Defender\n3 - Midfielder\n4 - Striker\nPosição: "); PlayerPosition position = PlayerPosition.getPositionById(Integer.parseInt(sin.nextLine())); System.out.print("X inicial: "); @@ -164,9 +165,9 @@ public class Main { } Team team = new Team(name, coach, robots); if (teams == null) - teams = new Team[] {team}; + teams = new Team[]{team}; else { - Team[] newTeams = new Team[teams.length+1]; + Team[] newTeams = new Team[teams.length + 1]; System.arraycopy(teams, 0, newTeams, 0, teams.length); newTeams[teams.length] = team; teams = newTeams; diff --git a/1ano/2semestre/poo/src/aula07/ex3/Robot.java b/1ano/2semestre/poo/src/aula07/ex3/Robot.java index d866d23..9a6828d 100644 --- a/1ano/2semestre/poo/src/aula07/ex3/Robot.java +++ b/1ano/2semestre/poo/src/aula07/ex3/Robot.java @@ -23,6 +23,7 @@ public class Robot extends MovableObject { public PlayerPosition getPlayerPosition() { return this.playerPosition; } + public void setPlayerPosition(PlayerPosition playerPosition) { this.playerPosition = playerPosition; } @@ -30,6 +31,7 @@ public class Robot extends MovableObject { public int getGoalsScored() { return this.goalsScored; } + public void increaseGoalsScored() { this.goalsScored++; } @@ -37,6 +39,6 @@ public class Robot extends MovableObject { @Override public String toString() { return String.format("Robot %d (%s) at (%.2f, %.2f) with %.2f travelled distance and %d goals scored", - this.id, this.playerPosition, this.x, this.y, this.distanceTravelled, this.goalsScored); + this.id, this.playerPosition, this.x, this.y, this.distanceTravelled, this.goalsScored); } } diff --git a/1ano/2semestre/poo/src/aula07/ex3/Team.java b/1ano/2semestre/poo/src/aula07/ex3/Team.java index 4430689..a1b9d47 100644 --- a/1ano/2semestre/poo/src/aula07/ex3/Team.java +++ b/1ano/2semestre/poo/src/aula07/ex3/Team.java @@ -54,17 +54,17 @@ public class Team { public void addRobot(Robot robot) { if (this.robots == null) - this.setRobots(new Robot[] {robot}); + this.setRobots(new Robot[]{robot}); else { - Robot[] newRobots = new Robot[this.robots.length+1]; + Robot[] newRobots = new Robot[this.robots.length + 1]; System.arraycopy(this.robots, 0, newRobots, 0, this.robots.length); - newRobots[newRobots.length-1] = robot; + newRobots[newRobots.length - 1] = robot; this.setRobots(newRobots); } } public void removeRobot(Robot robot) { - Robot[] newRobots = new Robot[this.robots.length-1]; + Robot[] newRobots = new Robot[this.robots.length - 1]; int index = 0; for (Robot r : this.robots) if (r.getId() != robot.getId()) { @@ -80,6 +80,6 @@ public class Team { for (Robot r : this.robots) robotsString.append("\n\t\t").append(r.toString()); return String.format("Team %s\n\tCoach: %s\n\tGoals Scored: %d\n\tGoals Taken: %d\n\tRobots:%s", - this.name, this.coach, this.goalsScored, this.goalsTaken, robotsString); + this.name, this.coach, this.goalsScored, this.goalsTaken, robotsString); } } diff --git a/1ano/2semestre/poo/src/aula08/ex1/Interfaces/IElectricVehicle.java b/1ano/2semestre/poo/src/aula08/ex1/Interfaces/IElectricVehicle.java index 6538386..67609ef 100644 --- a/1ano/2semestre/poo/src/aula08/ex1/Interfaces/IElectricVehicle.java +++ b/1ano/2semestre/poo/src/aula08/ex1/Interfaces/IElectricVehicle.java @@ -2,5 +2,6 @@ package aula08.ex1.Interfaces; public interface IElectricVehicle { int currentBatteryLvl(); + void charge(int percentage); } diff --git a/1ano/2semestre/poo/src/aula08/ex1/Interfaces/IFuelVehicle.java b/1ano/2semestre/poo/src/aula08/ex1/Interfaces/IFuelVehicle.java index 93e9467..d68de4a 100644 --- a/1ano/2semestre/poo/src/aula08/ex1/Interfaces/IFuelVehicle.java +++ b/1ano/2semestre/poo/src/aula08/ex1/Interfaces/IFuelVehicle.java @@ -2,5 +2,6 @@ package aula08.ex1.Interfaces; public interface IFuelVehicle { int fuelLevel(); + void fillTank(int level); } diff --git a/1ano/2semestre/poo/src/aula08/ex1/Interfaces/IKmTravelled.java b/1ano/2semestre/poo/src/aula08/ex1/Interfaces/IKmTravelled.java index cc7f815..ab9df15 100644 --- a/1ano/2semestre/poo/src/aula08/ex1/Interfaces/IKmTravelled.java +++ b/1ano/2semestre/poo/src/aula08/ex1/Interfaces/IKmTravelled.java @@ -2,6 +2,8 @@ package aula08.ex1.Interfaces; public interface IKmTravelled { void trip(int km); + int lastTrip(); + int totalDistance(); } diff --git a/1ano/2semestre/poo/src/aula08/ex1/Vehicles/Motorcycle.java b/1ano/2semestre/poo/src/aula08/ex1/Vehicles/Motorcycle.java index fedac02..9dd79e1 100644 --- a/1ano/2semestre/poo/src/aula08/ex1/Vehicles/Motorcycle.java +++ b/1ano/2semestre/poo/src/aula08/ex1/Vehicles/Motorcycle.java @@ -26,15 +26,15 @@ public class Motorcycle extends Vehicle implements IFuelVehicle { @Override public String toString() { return "Motorcycle {" + - "\n\tplate='" + this.getPlate() + '\'' + - ",\n\tbrand='" + this.getBrand() + '\'' + - ",\n\tmodel='" + this.getModel() + '\'' + - ",\n\tpotency=" + this.getPotency() + - ",\n\ttype=" + this.getType().toString() + - ",\n\tlastTripKm=" + this.lastTrip() + - ",\n\tkm=" + this.totalDistance() + - ",\n\tfuelLevel=" + this.fuelLevel() + - "\n}"; + "\n\tplate='" + this.getPlate() + '\'' + + ",\n\tbrand='" + this.getBrand() + '\'' + + ",\n\tmodel='" + this.getModel() + '\'' + + ",\n\tpotency=" + this.getPotency() + + ",\n\ttype=" + this.getType().toString() + + ",\n\tlastTripKm=" + this.lastTrip() + + ",\n\tkm=" + this.totalDistance() + + ",\n\tfuelLevel=" + this.fuelLevel() + + "\n}"; } @Override @@ -64,13 +64,6 @@ public class Motorcycle extends Vehicle implements IFuelVehicle { public enum MotorcycleType { SPORT, TOURING; - public String toString() { - return switch (this) { - case SPORT -> "Sport"; - case TOURING -> "Touring"; - }; - } - public static MotorcycleType fromString(String s) { return switch (s) { case "SPORT", "Sport", "sport" -> SPORT; @@ -78,5 +71,12 @@ public class Motorcycle extends Vehicle implements IFuelVehicle { default -> throw new IllegalArgumentException("Invalid MotorcycleType: " + s); }; } + + public String toString() { + return switch (this) { + case SPORT -> "Sport"; + case TOURING -> "Touring"; + }; + } } } \ No newline at end of file diff --git a/1ano/2semestre/poo/src/aula08/ex2/Aliments/Aliment.java b/1ano/2semestre/poo/src/aula08/ex2/Aliments/Aliment.java index 72dcf1f..e18d48c 100644 --- a/1ano/2semestre/poo/src/aula08/ex2/Aliments/Aliment.java +++ b/1ano/2semestre/poo/src/aula08/ex2/Aliments/Aliment.java @@ -5,10 +5,10 @@ import aula08.ex2.Enums.AlimentOrigin; import java.util.Objects; public abstract class Aliment { + final AlimentOrigin alimentOrigin; double proteins; double calories; double weight; - final AlimentOrigin alimentOrigin; public Aliment(double proteins, double calories, double weight, AlimentOrigin alimentOrigin) { setProteins(proteins); @@ -19,7 +19,7 @@ public abstract class Aliment { public double getProteins() { return this.proteins; - }; + } public void setProteins(double proteins) { if (proteins <= 0) diff --git a/1ano/2semestre/poo/src/aula08/ex2/Enums/AlimentType.java b/1ano/2semestre/poo/src/aula08/ex2/Enums/AlimentType.java index 4cb8336..1809d59 100644 --- a/1ano/2semestre/poo/src/aula08/ex2/Enums/AlimentType.java +++ b/1ano/2semestre/poo/src/aula08/ex2/Enums/AlimentType.java @@ -5,7 +5,7 @@ public enum AlimentType { public static AlimentType fromString(String string) { return switch (string.toUpperCase()) { - case "MEAT"-> MEAT; + case "MEAT" -> MEAT; case "FISH" -> FISH; case "CEREAL" -> CEREAL; case "VEGETABLE" -> VEGETABLE; diff --git a/1ano/2semestre/poo/src/aula08/ex2/Enums/FishState.java b/1ano/2semestre/poo/src/aula08/ex2/Enums/FishState.java index db2824b..8b3e583 100644 --- a/1ano/2semestre/poo/src/aula08/ex2/Enums/FishState.java +++ b/1ano/2semestre/poo/src/aula08/ex2/Enums/FishState.java @@ -5,7 +5,7 @@ public enum FishState { public static FishState fromString(String string) { return switch (string.toUpperCase()) { - case "FRESH"-> FRESH; + case "FRESH" -> FRESH; case "FROZEN" -> FROZEN; default -> null; }; diff --git a/1ano/2semestre/poo/src/aula08/ex3/Interfaces/IProduct.java b/1ano/2semestre/poo/src/aula08/ex3/Interfaces/IProduct.java index 976274b..fe9647e 100644 --- a/1ano/2semestre/poo/src/aula08/ex3/Interfaces/IProduct.java +++ b/1ano/2semestre/poo/src/aula08/ex3/Interfaces/IProduct.java @@ -2,9 +2,14 @@ package aula08.ex3.Interfaces; public interface IProduct { String getName(); - void setPrice(double price); + double getPrice(); + + void setPrice(double price); + int stock(); + void addStock(int amount); + void removeStock(int amount); } diff --git a/1ano/2semestre/poo/src/aula08/ex3/Interfaces/IPurchase.java b/1ano/2semestre/poo/src/aula08/ex3/Interfaces/IPurchase.java index f9a007c..2216d16 100644 --- a/1ano/2semestre/poo/src/aula08/ex3/Interfaces/IPurchase.java +++ b/1ano/2semestre/poo/src/aula08/ex3/Interfaces/IPurchase.java @@ -4,6 +4,8 @@ import aula08.ex3.Product; public interface IPurchase { void addProduct(Product product, int amount); + void listProducts(); + double getTotal(); } diff --git a/1ano/2semestre/poo/src/aula08/ex3/Purchase.java b/1ano/2semestre/poo/src/aula08/ex3/Purchase.java index 35622f9..06afa56 100644 --- a/1ano/2semestre/poo/src/aula08/ex3/Purchase.java +++ b/1ano/2semestre/poo/src/aula08/ex3/Purchase.java @@ -14,7 +14,7 @@ public class Purchase implements IPurchase { product.removeStock(amount); if (products.containsKey(product)) { int currentAmount = products.get(product); - products.replace(product, currentAmount+amount); + products.replace(product, currentAmount + amount); } else products.put(product, amount); } diff --git a/1ano/2semestre/poo/src/aula08/ex3/ShoppingCartTester.java b/1ano/2semestre/poo/src/aula08/ex3/ShoppingCartTester.java index f8ab88f..8c3fc53 100644 --- a/1ano/2semestre/poo/src/aula08/ex3/ShoppingCartTester.java +++ b/1ano/2semestre/poo/src/aula08/ex3/ShoppingCartTester.java @@ -6,7 +6,7 @@ public class ShoppingCartTester { Product p2 = new Product("Calças", 30, 1); Product p3 = new ProductWithDiscount("Sapatilhas", 50, 2, 50); Product p4 = new ProductWithDiscount("Casacos", 100, 1, 10); - + Purchase compra = new Purchase(); compra.addProduct(p2, 5); compra.addProduct(p3, 2); diff --git a/1ano/2semestre/poo/src/aula09/ex1/ALDemo.java b/1ano/2semestre/poo/src/aula09/ex1/ALDemo.java index ba1b60c..02ad709 100644 --- a/1ano/2semestre/poo/src/aula09/ex1/ALDemo.java +++ b/1ano/2semestre/poo/src/aula09/ex1/ALDemo.java @@ -10,13 +10,14 @@ import java.util.Set; public class ALDemo { public static void main(String[] args) { - ArrayList c1= new ArrayList<>(); - for(int i= 10; i<= 100; i+=10) c1.add(i);System.out.println("Size: "+ c1.size()); + ArrayList c1 = new ArrayList<>(); + for (int i = 10; i <= 100; i += 10) c1.add(i); + System.out.println("Size: " + c1.size()); - for(int i= 0; i< c1.size(); i++) - System.out.println("Elemento: "+ c1.get(i)); + for (int i = 0; i < c1.size(); i++) + System.out.println("Elemento: " + c1.get(i)); - ArrayList c2= new ArrayList<>(); + ArrayList c2 = new ArrayList<>(); c2.add("Vento"); c2.add("Calor"); c2.add("Frio"); diff --git a/1ano/2semestre/poo/src/aula09/ex2/CollectionTester.java b/1ano/2semestre/poo/src/aula09/ex2/CollectionTester.java index e860748..66195a4 100644 --- a/1ano/2semestre/poo/src/aula09/ex2/CollectionTester.java +++ b/1ano/2semestre/poo/src/aula09/ex2/CollectionTester.java @@ -6,8 +6,8 @@ import java.util.Iterator; public class CollectionTester { public static void main(String[] args) { - int DIM= 5000; - Collection col= new ArrayList<>(); + int DIM = 5000; + Collection col = new ArrayList<>(); checkPerformance(col, DIM); } @@ -15,32 +15,32 @@ public class CollectionTester { double start, stop, delta; // Add start = System.nanoTime(); // clock snapshot before - for(int i=0; i iterator = col.iterator(); - while(iterator.hasNext()) { + while (iterator.hasNext()) { iterator.next(); iterator.remove(); } stop = System.nanoTime(); // clock snapshot after - delta = (stop-start)/1e6; // convert nanoseconds to milliseconds - System.out.println(col.size() + ": Remove from "+ col.getClass().getSimpleName() +" took "+ delta+ "ms"); + delta = (stop - start) / 1e6; // convert nanoseconds to milliseconds + System.out.println(col.size() + ": Remove from " + col.getClass().getSimpleName() + " took " + delta + "ms"); } } diff --git a/1ano/2semestre/poo/src/aula09/ex3/PlaneManager.java b/1ano/2semestre/poo/src/aula09/ex3/PlaneManager.java index 7917322..56e8012 100644 --- a/1ano/2semestre/poo/src/aula09/ex3/PlaneManager.java +++ b/1ano/2semestre/poo/src/aula09/ex3/PlaneManager.java @@ -67,8 +67,7 @@ public class PlaneManager { for (Plane plane : planes) { if (plane instanceof CommercialPlane && type.equals("commercial")) { System.out.println(plane); - } - else if (plane instanceof MilitaryPlane && type.equals("military")) { + } else if (plane instanceof MilitaryPlane && type.equals("military")) { System.out.println(plane); } } diff --git a/1ano/2semestre/poo/src/aula09/ex3/PlaneTester.java b/1ano/2semestre/poo/src/aula09/ex3/PlaneTester.java index 31e1f59..a625eae 100644 --- a/1ano/2semestre/poo/src/aula09/ex3/PlaneTester.java +++ b/1ano/2semestre/poo/src/aula09/ex3/PlaneTester.java @@ -57,8 +57,7 @@ public class PlaneTester { System.out.print("Enter the plane's crew members count: "); int crewMembersCount = Integer.parseInt(scanner.nextLine()); planeManager.addPlane(new CommercialPlane(id, manufacturer, model, year, passengerCount, maxSpeed, crewMembersCount)); - } - else if (type.equals("military")) { + } else if (type.equals("military")) { System.out.print("Enter the plane's missile count: "); int missileCount = Integer.parseInt(scanner.nextLine()); planeManager.addPlane(new MilitaryPlane(id, manufacturer, model, year, passengerCount, maxSpeed, missileCount)); diff --git a/1ano/2semestre/poo/src/aula10/ex1/Book.java b/1ano/2semestre/poo/src/aula10/ex1/Book.java index 49f16d3..3db833d 100644 --- a/1ano/2semestre/poo/src/aula10/ex1/Book.java +++ b/1ano/2semestre/poo/src/aula10/ex1/Book.java @@ -13,12 +13,29 @@ public class Book { this.setYear(year); } - public String getTitle() { return this.title; } - public void setTitle(String title) { this.title = title; } - public String getAuthor() { return this.author; } - public void setAuthor(String author) { this.author = author; } - public int getYear() { return this.year; } - public void setYear(int year) { this.year = year; } + public String getTitle() { + return this.title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getAuthor() { + return this.author; + } + + public void setAuthor(String author) { + this.author = author; + } + + public int getYear() { + return this.year; + } + + public void setYear(int year) { + this.year = year; + } @Override public String toString() { diff --git a/1ano/2semestre/poo/src/aula10/ex4/FileReaderTest.java b/1ano/2semestre/poo/src/aula10/ex4/FileReaderTest.java index ac5ef6d..1909eef 100644 --- a/1ano/2semestre/poo/src/aula10/ex4/FileReaderTest.java +++ b/1ano/2semestre/poo/src/aula10/ex4/FileReaderTest.java @@ -14,7 +14,7 @@ public class FileReaderTest { } catch (FileNotFoundException e) { throw new RuntimeException(e); } - while(input.hasNext()){ + while (input.hasNext()) { String word = input.next(); if (word.length() > 2) { words.add(word); diff --git a/1ano/2semestre/poo/src/aula11/ex1/WordPairCounter.java b/1ano/2semestre/poo/src/aula11/ex1/WordPairCounter.java index ccf4516..6d53b4e 100644 --- a/1ano/2semestre/poo/src/aula11/ex1/WordPairCounter.java +++ b/1ano/2semestre/poo/src/aula11/ex1/WordPairCounter.java @@ -16,15 +16,15 @@ public class WordPairCounter { String text = ""; Path path = Paths.get((new Scanner(System.in)).nextLine()); try { - text = Files.readString(path); - } catch (IOException e) { - System.out.printf("Certifique-se que o ficheiro \"%s\" está na raiz da pasta do projeto", path); + text = Files.readString(path); + } catch (IOException e) { + System.out.printf("Certifique-se que o ficheiro \"%s\" está na raiz da pasta do projeto", path); System.exit(1); - } + } Object[] words = Arrays.stream(text.split("[\\s.,:'‘’;?!\\-*{}=+&/()\\[\\]”“\"]+")).filter(word -> word.length() > 2).map(String::toLowerCase).toArray(); - for (int i = 1; i < words.length-1; i++) { - String word1 = (String) words[i-1]; + for (int i = 1; i < words.length - 1; i++) { + String word1 = (String) words[i - 1]; String word2 = (String) words[i]; HashMap word1Pair = wordPairs.getOrDefault(word1, new HashMap<>()); diff --git a/1ano/2semestre/poo/src/aula11/ex2/Gradebook.java b/1ano/2semestre/poo/src/aula11/ex2/Gradebook.java index 79cc9f7..4f8a176 100644 --- a/1ano/2semestre/poo/src/aula11/ex2/Gradebook.java +++ b/1ano/2semestre/poo/src/aula11/ex2/Gradebook.java @@ -16,10 +16,10 @@ public class Gradebook { Path path = Paths.get(filename); try { lines = new LinkedList<>(Files.readAllLines(path)); - } catch (IOException e) { - System.out.printf("Certifique-se que o ficheiro \"%s\" está na raiz da pasta do projeto", path); + } catch (IOException e) { + System.out.printf("Certifique-se que o ficheiro \"%s\" está na raiz da pasta do projeto", path); System.exit(1); - } + } for (String line : lines) { String[] data = line.split("\\|"); diff --git a/1ano/2semestre/poo/src/aula11/ex3/EnergyUsageReport.java b/1ano/2semestre/poo/src/aula11/ex3/EnergyUsageReport.java index 77ec61e..a0c5f1f 100644 --- a/1ano/2semestre/poo/src/aula11/ex3/EnergyUsageReport.java +++ b/1ano/2semestre/poo/src/aula11/ex3/EnergyUsageReport.java @@ -18,10 +18,10 @@ public class EnergyUsageReport { Path path = Paths.get(file); try { lines = new LinkedList<>(Files.readAllLines(path)); - } catch (IOException e) { - System.out.printf("Certifique-se que o ficheiro \"%s\" está na raiz da pasta do projeto", path); + } catch (IOException e) { + System.out.printf("Certifique-se que o ficheiro \"%s\" está na raiz da pasta do projeto", path); System.exit(1); - } + } for (String line : lines) { String[] data = line.split("\\|"); diff --git a/1ano/2semestre/poo/src/aula11/ex3/EnergyUsageReportTester.java b/1ano/2semestre/poo/src/aula11/ex3/EnergyUsageReportTester.java index 6669324..766f996 100644 --- a/1ano/2semestre/poo/src/aula11/ex3/EnergyUsageReportTester.java +++ b/1ano/2semestre/poo/src/aula11/ex3/EnergyUsageReportTester.java @@ -7,27 +7,27 @@ import java.util.List; public class EnergyUsageReportTester { public static void main(String[] args) throws IOException { - + // Create an instance of the EnergyUsageReport class EnergyUsageReport energyReport = new EnergyUsageReport(); - + // Load the customer data from a text file using the load() method energyReport.load("datafiles/aula11/ex3/clients.txt"); - + // Add one or more customers to the collection using the addCustomer() method Customer newCustomer = new Customer(999, new LinkedList<>(List.of(1500.0, 2000.0, 2500.0, 3000.0))); energyReport.addCustomer(newCustomer); - + // Remove one or more customers from the collection using the removeCustomer() method energyReport.removeCustomer(1015); - + // Retrieve a customer from the collection using the getCustomer() method Customer retrievedCustomer = energyReport.getCustomer(1025); - + // Calculate the total energy usage for a specific customer using the calculateTotalUsage() method double totalEnergyUsage = energyReport.calculateTotalUsage(1003); System.out.println("Total energy usage for customer 1003: " + totalEnergyUsage); - + // Generate a report of all customers and their total energy usage using the generateReport() method energyReport.generateReport("datafiles/aula11/ex3/energy_report.txt"); } diff --git a/1ano/2semestre/poo/src/aula11/ex4/FlightManager.java b/1ano/2semestre/poo/src/aula11/ex4/FlightManager.java index 327c527..d76745d 100644 --- a/1ano/2semestre/poo/src/aula11/ex4/FlightManager.java +++ b/1ano/2semestre/poo/src/aula11/ex4/FlightManager.java @@ -15,6 +15,16 @@ public class FlightManager { private String delaysTable; private String flightsNTable; + private static Map sortByValue(Map unsortMap) { + List> list = new LinkedList<>(unsortMap.entrySet()); + + // Sorting the list based on values + list.sort((o1, o2) -> o2.getValue().compareTo(o1.getValue()) == 0 + ? o2.getKey().compareTo(o1.getKey()) + : o2.getValue().compareTo(o1.getValue())); + return list.stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> b, LinkedHashMap::new)); + } + public void loadCompanies(String filename) { Scanner input; try { @@ -23,10 +33,10 @@ public class FlightManager { } catch (FileNotFoundException e) { throw new RuntimeException(e); } - while(input.hasNext()){ + while (input.hasNext()) { String line = input.nextLine(); String[] fields = line.split("\t"); - if(fields.length != 2) + if (fields.length != 2) throw new RuntimeException("Invalid file format"); this.companies.add(new Company(fields[0], fields[1], new LinkedList<>())); } @@ -127,14 +137,4 @@ public class FlightManager { } } } - - private static Map sortByValue(Map unsortMap) { - List> list = new LinkedList<>(unsortMap.entrySet()); - - // Sorting the list based on values - list.sort((o1, o2) -> o2.getValue().compareTo(o1.getValue()) == 0 - ? o2.getKey().compareTo(o1.getKey()) - : o2.getValue().compareTo(o1.getValue())); - return list.stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> b, LinkedHashMap::new)); - } } diff --git a/1ano/2semestre/poo/src/aula11/ex4/Time.java b/1ano/2semestre/poo/src/aula11/ex4/Time.java index e9ee148..29991e4 100644 --- a/1ano/2semestre/poo/src/aula11/ex4/Time.java +++ b/1ano/2semestre/poo/src/aula11/ex4/Time.java @@ -11,6 +11,14 @@ public class Time { this.minute = minute; } + public static int timeToMinsInt(Time time) { + return time.hour() * 60 + time.minute(); + } + + public static Time minsIntToTime(int mins) { + return new Time(mins / 60, mins % 60); + } + public Time addTime(Time time) { int newHour = hour + time.hour(); int newMinute = minute + time.minute(); @@ -34,14 +42,6 @@ public class Time { return String.format("%02d:%02d", hour, minute); } - public static int timeToMinsInt(Time time) { - return time.hour() * 60 + time.minute(); - } - - public static Time minsIntToTime(int mins) { - return new Time(mins/60, mins%60); - } - public int hour() { return hour; } diff --git a/1ano/2semestre/poo/src/aula12/ex2/WordCounterByInitial.java b/1ano/2semestre/poo/src/aula12/ex2/WordCounterByInitial.java index 112b8ab..ba3e62b 100644 --- a/1ano/2semestre/poo/src/aula12/ex2/WordCounterByInitial.java +++ b/1ano/2semestre/poo/src/aula12/ex2/WordCounterByInitial.java @@ -24,7 +24,7 @@ public class WordCounterByInitial { }; Arrays.stream(Files.readString(Path.of((new Scanner(System.in)).nextLine())) - .split("[\\s.,:'‘’;?!\\-*{}=+&/()\\[\\]”“\"]+")) + .split("[\\s.,:'‘’;?!\\-*{}=+&/()\\[\\]”“\"]+")) .filter(word -> word.length() > 2) .map(String::toLowerCase) .forEach(word -> { diff --git a/1ano/2semestre/poo/src/aval/aa1/Animal.java b/1ano/2semestre/poo/src/aval/aa1/Animal.java index 7fc1bd6..ac4216d 100644 --- a/1ano/2semestre/poo/src/aval/aa1/Animal.java +++ b/1ano/2semestre/poo/src/aval/aa1/Animal.java @@ -26,11 +26,16 @@ public class Animal { return id; } + public String getName() { + return name; + } + public void setName(String name) { this.name = name; } - public String getName() { - return name; + + public int getWeight() { + return weight; } public void setWeight(int weight) { @@ -38,8 +43,9 @@ public class Animal { throw new IllegalArgumentException("Weight must be positive!"); this.weight = weight; } - public int getWeight() { - return weight; + + public int getAge() { + return age; } public void setAge(int age) { @@ -47,21 +53,20 @@ public class Animal { throw new IllegalArgumentException("Age must be positive!"); this.age = age; } - public int getAge() { - return age; + + public String getSponsor() { + return sponsor; } public void setSponsor(String sponsor) { this.sponsor = sponsor; } - public String getSponsor() { - return sponsor; - } @Override public String toString() { return String.format("ID: %d\nName: %s\nAge: %d\nWeight: %d\nSponsor: %s", this.id, this.name, this.age, this.weight, this.sponsor == null ? "None" : sponsor); } + @Override public boolean equals(Object o) { if (this == o) return true; @@ -69,6 +74,7 @@ public class Animal { Animal animal = (Animal) o; return id == animal.id && weight == animal.weight && age == animal.age && Objects.equals(name, animal.name) && Objects.equals(sponsor, animal.sponsor); } + @Override public int hashCode() { return Objects.hash(id, name, weight, age, sponsor); diff --git a/1ano/2semestre/poo/src/aval/aa1/IPetShelter.java b/1ano/2semestre/poo/src/aval/aa1/IPetShelter.java index f9cd0af..1565e1f 100644 --- a/1ano/2semestre/poo/src/aval/aa1/IPetShelter.java +++ b/1ano/2semestre/poo/src/aval/aa1/IPetShelter.java @@ -1,9 +1,13 @@ package aval.aa1; public interface IPetShelter { - public void addAnimal(Animal animal); - public void removeAnimal(Animal animal); - public Animal searchForAnimal(String name); - public boolean sponsorAnimal(int animalId); - public void listAllAnimals(); + void addAnimal(Animal animal); + + void removeAnimal(Animal animal); + + Animal searchForAnimal(String name); + + boolean sponsorAnimal(int animalId); + + void listAllAnimals(); } diff --git a/1ano/2semestre/poo/src/aval/aa1/PetShelter.java b/1ano/2semestre/poo/src/aval/aa1/PetShelter.java index 594a265..3846346 100644 --- a/1ano/2semestre/poo/src/aval/aa1/PetShelter.java +++ b/1ano/2semestre/poo/src/aval/aa1/PetShelter.java @@ -3,7 +3,7 @@ package aval.aa1; import java.util.Scanner; public class PetShelter implements IPetShelter { - private String shelterName; + private final String shelterName; private Animal[] animals; public PetShelter(String shelterName) { @@ -17,9 +17,7 @@ public class PetShelter implements IPetShelter { animals[0] = animal; } else { Animal[] newAnimals = new Animal[animals.length + 1]; - for (int i = 0; i < animals.length; i++) { - newAnimals[i] = animals[i]; - } + System.arraycopy(animals, 0, newAnimals, 0, animals.length); newAnimals[newAnimals.length - 1] = animal; animals = newAnimals; } @@ -62,6 +60,6 @@ public class PetShelter implements IPetShelter { @Override public void listAllAnimals() { for (Animal a : animals) - System.out.println(a.toString()+"\n"); + System.out.println(a.toString() + "\n"); } } diff --git a/1ano/2semestre/poo/src/aval/aa2/Classes/Order.java b/1ano/2semestre/poo/src/aval/aa2/Classes/Order.java index 6424ed1..04b83e1 100644 --- a/1ano/2semestre/poo/src/aval/aa2/Classes/Order.java +++ b/1ano/2semestre/poo/src/aval/aa2/Classes/Order.java @@ -1,6 +1,5 @@ package aval.aa2.Classes; -import java.time.LocalDate; import java.time.LocalDateTime; import java.util.List; import java.util.Objects; @@ -75,6 +74,6 @@ public class Order { items.forEach(item -> itemsStringBuilder.append(item).append(", ")); return String.format("Order #%d: Client ID: %s, Store ID: %s, Order Datetime: %s, Express order: %b, Total cost: %.2f, Items: {%s};", getId(), getClientId(), getStoreId(), getOrderDateTime().toString().replace('T', ' '), isExpressOrder(), - getPrice(), itemsStringBuilder.substring(0, itemsStringBuilder.length()-2)); + getPrice(), itemsStringBuilder.substring(0, itemsStringBuilder.length() - 2)); } } diff --git a/1ano/2semestre/poo/src/aval/aa2/Classes/OrderManager.java b/1ano/2semestre/poo/src/aval/aa2/Classes/OrderManager.java index b956c08..8b9ae5a 100644 --- a/1ano/2semestre/poo/src/aval/aa2/Classes/OrderManager.java +++ b/1ano/2semestre/poo/src/aval/aa2/Classes/OrderManager.java @@ -20,7 +20,7 @@ public class OrderManager { public double calculateOrderCost(int id) { StandardOrderCostCalculator calculator = new StandardOrderCostCalculator(); - double cost = searchOrder(id) != null ? calculator.calculateOrderCost(searchOrder(id)): -1; + double cost = searchOrder(id) != null ? calculator.calculateOrderCost(searchOrder(id)) : -1; searchOrder(id).setPrice(cost); return cost; } diff --git a/1ano/2semestre/poo/src/aval/aa2/OrderTester.java b/1ano/2semestre/poo/src/aval/aa2/OrderTester.java index 7a04dbd..ca431e4 100644 --- a/1ano/2semestre/poo/src/aval/aa2/OrderTester.java +++ b/1ano/2semestre/poo/src/aval/aa2/OrderTester.java @@ -9,7 +9,6 @@ import java.io.FileReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.time.LocalDate; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Arrays; @@ -21,20 +20,20 @@ public class OrderTester { OrderManager orderManager = new OrderManager(); orderManager.addOrder(new Order(new ArrayList<>(List.of(new Item[]{ - new Item("Chocolate", 2.43) - })), + new Item("Chocolate", 2.43) + })), "104", "23", LocalDateTime.of(2023, 5, 2, 14, 5), false)); orderManager.addOrder(new Order(new ArrayList<>(List.of(new Item[]{ - new Item("Pastel de nata", 7.73), - new Item("Sumo de laranja", 1.20) - })), + new Item("Pastel de nata", 7.73), + new Item("Sumo de laranja", 1.20) + })), "114", "27", LocalDateTime.of(2023, 5, 6, 12, 4), true)); orderManager.addOrder(new Order(new ArrayList<>(List.of(new Item[]{ - new Item("Galão", 1.20), - new Item("Torrada", 1.00) - })), + new Item("Galão", 1.20), + new Item("Torrada", 1.00) + })), "124", "1", LocalDateTime.of(2023, 5, 12, 7, 4), false)); orderManager.printAllOrders(); diff --git a/1ano/2semestre/poo/src/aval/atp1/RainfallInfo.java b/1ano/2semestre/poo/src/aval/atp1/RainfallInfo.java new file mode 100644 index 0000000..4ca3459 --- /dev/null +++ b/1ano/2semestre/poo/src/aval/atp1/RainfallInfo.java @@ -0,0 +1,41 @@ +package aval.atp1; + +import java.time.LocalDate; +// YOU MAY ADD IMPORTS HERE + +public class RainfallInfo { + private final LocalDate date; + private final String location; + private final double rainfall; + + public RainfallInfo(LocalDate date, String location, double rainfall) { + this.date = date; + this.location = location; + this.rainfall = rainfall; + } + + public LocalDate date() { + return date; + } + + public String location() { + return location; + } + + public double rainfall() { + return rainfall; + } + + // YOU MAY ADD METHODS HERE + @Override + public String toString() { + return String.format("(%s, %s, %.1f)", date(), location(), rainfall()); + } + + + @Override + public int hashCode() { + return date.hashCode() | location.hashCode() | Double.hashCode(rainfall); + } + +} diff --git a/1ano/2semestre/poo/src/aval/atp1/RainfallTest.java b/1ano/2semestre/poo/src/aval/atp1/RainfallTest.java new file mode 100644 index 0000000..3869fdc --- /dev/null +++ b/1ano/2semestre/poo/src/aval/atp1/RainfallTest.java @@ -0,0 +1,118 @@ +package aval.atp1; + +import java.io.FileReader; +import java.io.IOError; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.time.LocalDate; +import java.time.Month; +import java.util.*; +// YOU MAY ADD IMPORTS HERE + +public class RainfallTest { + public static List loadData(String filePath) { + List data = null; + try { + // Check if file is csv + if (!filePath.endsWith(".csv")) { + return null; + } + + if (!Files.exists(Paths.get(filePath))) { + return null; + } + + // 1) Read the file and add RainfallInfo objects to a list. + Scanner sc = new Scanner(new FileReader(filePath)); + sc.nextLine(); // skip header + + while (sc.hasNextLine()) { + String[] datacomps = sc.nextLine().split(","); + LocalDate date = LocalDate.parse(datacomps[0]); + String location = datacomps[1]; + double rainfall = Double.parseDouble(datacomps[2]); + if (data == null) data = new ArrayList<>(); + data.add(new RainfallInfo(date, location, rainfall)); + } + } catch (Exception e) { + throw new IOError(e.getCause()); // repackage as error + } + return data; + } + + public static String printLocationData(List data, String loc) { + System.out.printf("Rainfall for location %s:\n", loc); + // 2) Print rainfall values for the given location + data.stream().filter(r -> r.location().equals(loc)).forEach(System.out::println); + return ""; + } + + public static Map totalPerMonth(List data) { + // 3) Calculate and return a map with the total rainfall per month + Map map = new HashMap<>(); + data.forEach(r -> { + Month m = r.date().getMonth(); + if (map.containsKey(m)) { + map.put(m, map.get(m) + r.rainfall()); + } else { + map.put(m, r.rainfall()); + } + }); + return map; + } + + public static String printMapSorted(Map map) { + // 4) Print map sorted by key + map.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(e -> System.out.printf("%s: %.1f\n", e.getKey(), e.getValue())); + return ""; + } + + // YOU MAY ADD METHODS HERE + public static String main() { + Test.lst = null; + Test.map = null; + // Load the file data to the list + List rainfallData = loadData("rainfall_data.csv"); + System.out.printf("Data size: %d\n", rainfallData.size()); + System.out.printf("Data hash: %d\n", rainfallData.hashCode()); + System.out.println(); + + // Show data for a single town + printLocationData(rainfallData, "Braga"); + System.out.println(); + + // Find total rainfall per month + Map rainfallPerMonth = totalPerMonth(rainfallData); + + // Print sorted results + printMapSorted(rainfallPerMonth); + return ""; + } + + public static void main(String[] args) { + main(); + } +} + +class Test { + static List lst = new ArrayList<>(); + static Map map = new HashMap<>(); + // Variables used in unit tests (DON'T USE IN YOUR IMPLEMENTATION!): + private static final LocalDate[] dates = { + LocalDate.parse("2023-03-02"), + LocalDate.parse("2023-04-17"), + LocalDate.parse("2023-05-27"), + }; + + static { + lst.add(new RainfallInfo(dates[2], "Aveiro", 2.2)); + lst.add(new RainfallInfo(dates[1], "Braga", 3.0)); + lst.add(new RainfallInfo(dates[0], "Aveiro", 0.0)); + lst.add(new RainfallInfo(dates[2], "Braga", 4.0)); + lst.add(new RainfallInfo(dates[1], "Aveiro", 1.1)); + map.put(Month.JULY, 7.7); + map.put(Month.MAY, 5.5); + map.put(Month.JUNE, 6.6); + map.put(Month.MARCH, 3.3); + } +} \ No newline at end of file diff --git a/1ano/2semestre/poo/src/tp_codecheck/README.md b/1ano/2semestre/poo/src/tp_codecheck/README.md deleted file mode 100755 index f49dbb0..0000000 --- a/1ano/2semestre/poo/src/tp_codecheck/README.md +++ /dev/null @@ -1,6 +0,0 @@ -# Programação Orientada a Objetos -## Exercícios TP -### Resoluções para exercícios sugeridos nas aulas Teórico-Práticas - ---- -*Pode conter erros, caso encontre algum, crie um* [*ticket*](https://github.com/TiagoRG/uaveiro-leci/issues/new) diff --git a/1ano/2semestre/poo/src/tp_codecheck/tp01/BankInterest.java b/1ano/2semestre/poo/src/tp_codecheck/tp01/BankInterest.java deleted file mode 100644 index 6397ad3..0000000 --- a/1ano/2semestre/poo/src/tp_codecheck/tp01/BankInterest.java +++ /dev/null @@ -1,59 +0,0 @@ -package tp_codecheck.tp01; - -// Solução do exercício 2 - -import java.util.Scanner; - -/** - This program updates an account balance, according to the table below: - Balance Interest Rate Charge - > $100,000.00 2.75 % $ 0.00 - > $25,000.00 2.00 % $ 0.00 - > $10,000.00 1.00 % $ 0.00 - >= $0.00 0.00 % $ 0.00 - < $0.00 0.00 % $ 25.00 - and prints out the new balance. -*/ -public class BankInterest -{ - public static void main(String[] args) - { - // Define constants - final double HI_RATE = 2.75; - final double MD_RATE = 2.00; - final double LO_RATE = 1.00; - final double ZERO_RATE = 0.00; - final double DEB_CHG = -25.00; - - final double HI_LIMIT = 100000.00; - final double MD_LIMIT = 25000.00; - final double LO_LIMIT = 10000.00; - final double ZERO_LIMIT = 0.00; - - // Print prompt to enter a current balence - System.out.print("Enter current balance: "); - - // Read balance - Scanner in = new Scanner(System.in); - double balance = in.nextDouble(); - - // Determine interest rate (or charge) based on current balance - // to compute new balance - - // Your work here - - double newBalance; - if (balance > HI_LIMIT) - newBalance = balance*(1+HI_RATE/100); - else if (balance > MD_LIMIT) - newBalance = balance*(1+MD_RATE/100); - else if (balance > LO_LIMIT) - newBalance = balance*(1+LO_RATE/100); - else if (balance < ZERO_LIMIT) - newBalance = balance+DEB_CHG; - else - newBalance = balance; - - System.out.printf("%.2f\n", newBalance); - } -} \ No newline at end of file diff --git a/1ano/2semestre/poo/src/tp_codecheck/tp01/Table.java b/1ano/2semestre/poo/src/tp_codecheck/tp01/Table.java deleted file mode 100644 index 07fc547..0000000 --- a/1ano/2semestre/poo/src/tp_codecheck/tp01/Table.java +++ /dev/null @@ -1,28 +0,0 @@ -package tp_codecheck.tp01; - -// Solução do exercício 3 - -public class Table { - - public static void main(String[] args) { - System.out.printf("%s | %s | %s | %s\n", "n", "Hn", "log n", "Hn - log n"); - int n = 1; - while (n <= 1000000) { - double f1 = harmonic(n); - double f2 = Math.log((double)n); - System.out.printf("%d | %.3f | %.3f | %.9f\n", n, f1, f2, f1-f2); - n *= 2; - } - } - - /** - * Computes the Harmonic number Hn = 1 + 1/2 + 1/3 + ... + 1/n. - */ - private static double harmonic(int n) { - double sum = 0; - for (int i = 1; i <= n; i++) { - sum += 1/(float)i; - } - return sum; - } -} diff --git a/1ano/2semestre/poo/src/tp_codecheck/tp01/Temperature.java b/1ano/2semestre/poo/src/tp_codecheck/tp01/Temperature.java deleted file mode 100644 index abb7a6c..0000000 --- a/1ano/2semestre/poo/src/tp_codecheck/tp01/Temperature.java +++ /dev/null @@ -1,29 +0,0 @@ -package tp_codecheck.tp01; - -// Solução do exercício 1 - -/* -This is a short Java program to convert -a temperature from Celsius to Fahrenheit. -*/ - -// You may want to import stuff here... - -import java.util.Scanner; - -public class Temperature { - // Create a Scanner to parse standard input: - private static Scanner sc = new Scanner(System.in); - - public static void main(String[] args) { - // Put your code here - System.out.print("Celsius? "); - double celcius = sc.nextDouble(); - double fahrenheit = 1.8*celcius+32; - System.out.printf("%f C = %f F\n", celcius, fahrenheit); - - System.out.println("THE END"); - } -} - -// JMR 2023 \ No newline at end of file diff --git a/1ano/2semestre/poo/src/tp_codecheck/tp02/Array1.md b/1ano/2semestre/poo/src/tp_codecheck/tp02/Array1.md deleted file mode 100644 index 82c4075..0000000 --- a/1ano/2semestre/poo/src/tp_codecheck/tp02/Array1.md +++ /dev/null @@ -1,23 +0,0 @@ -# Exercícios de Arrays - -## Ex1 -```java -final int LENGHT = 100; -int[] a = new int[LENGHT]; -// Code for filling a ommited -for (int = 99; i >= 0; i--) -{ - System.out.print(a[i]); - if (i > 0) { System.out.print(', '); } -} -``` - -## Ex2 -```java -int[] numbers = new int[100]; -for (int k = 0; k < numbers.length; k++) -{ - numbers[k] = k + 1; -} -``` - diff --git a/1ano/2semestre/poo/src/tp_codecheck/tp02/NumberOfDays.java b/1ano/2semestre/poo/src/tp_codecheck/tp02/NumberOfDays.java deleted file mode 100644 index 401c3c1..0000000 --- a/1ano/2semestre/poo/src/tp_codecheck/tp02/NumberOfDays.java +++ /dev/null @@ -1,27 +0,0 @@ -package tp_codecheck.tp02; - -import java.util.Scanner; - -public class NumberOfDays { - public static void main(String[] args) - { - // Declare and initialize daysOfMonth - int[] daysOfMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; - - Scanner in = new Scanner(System.in); - System.out.print("Month (1 - 12): "); - int month = in.nextInt(); - System.out.print("Year: "); - int year = in.nextInt(); - - if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) { - // It's a leap year. Adjust the entry for February - daysOfMonth[1]+=1; - } - - // Get the number of days in the given month - int days = daysOfMonth[month-1]; - - System.out.println("Number of days: " + days); - } -} diff --git a/1ano/2semestre/poo/src/tp_codecheck/tp02/Numbers.java b/1ano/2semestre/poo/src/tp_codecheck/tp02/Numbers.java deleted file mode 100644 index ebaa91c..0000000 --- a/1ano/2semestre/poo/src/tp_codecheck/tp02/Numbers.java +++ /dev/null @@ -1,17 +0,0 @@ -package tp_codecheck.tp02; - -public class Numbers { - public static void main(String[] args) { - // Different arrays will be substituted here. - int[] values = { 3, 1, 4, 1, 5, 9 }; - int[] newValues = new int[values.length/2]; - - for (int x = 0; x < values.length; x+=2) { - newValues[x/2] = values[x]; - } - - for (int i = 0; i < newValues.length; i++) { - System.out.println(newValues[i]); - } - } -} diff --git a/1ano/2semestre/poo/src/tp_codecheck/tp02/Strings1.md b/1ano/2semestre/poo/src/tp_codecheck/tp02/Strings1.md deleted file mode 100644 index ea8d514..0000000 --- a/1ano/2semestre/poo/src/tp_codecheck/tp02/Strings1.md +++ /dev/null @@ -1,9 +0,0 @@ -# Tabela Exercício 1 de Strings - -| Question | Answer | -|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------| -| What is the length of the string below?
String str = "Java Program" | 12 | -| With str as defined above, give a call to the substring method that returns the substring "gram". | str.substring(8) | -| Use the string concatenation operator to change the string variable str to contain the string "Java Programming". | str += "ming" | -| What does the following statement sequence print?

String str = "Harry";
int n = str.length();
String mystery = str.substring(0, 1) + str.substring(n - 1, n);
System.out.println(mystery); | Hy | -| Consider the following statement sequence. If the user provides the input John Q. Public, what is printed? If an error occurs, type error.

Scanner in = new Scanner(System.in);
String first = in.next();
String last = in.next();
System.out.println(last + ", " + first); | Q., John | \ No newline at end of file diff --git a/1ano/2semestre/poo/src/tp_codecheck/tp02/Words.java b/1ano/2semestre/poo/src/tp_codecheck/tp02/Words.java deleted file mode 100644 index d2fdf36..0000000 --- a/1ano/2semestre/poo/src/tp_codecheck/tp02/Words.java +++ /dev/null @@ -1,12 +0,0 @@ -package tp_codecheck.tp02; - -import java.util.Scanner; - -public class Words { - public static void main(String[] args) { - Scanner in = new Scanner(System.in); - String word = in.next(); - word = word.charAt(word.length()-1) + word.substring(1, word.length()-1) + word.charAt(0); - System.out.println(word); - } -} diff --git a/1ano/2semestre/poo/src/tp_codecheck/tp03/part1/TrafficLight1.java b/1ano/2semestre/poo/src/tp_codecheck/tp03/part1/TrafficLight1.java deleted file mode 100644 index b8c314f..0000000 --- a/1ano/2semestre/poo/src/tp_codecheck/tp03/part1/TrafficLight1.java +++ /dev/null @@ -1,66 +0,0 @@ -package tp_codecheck.tp03.part1; - -/** - A simulated traffic light. -*/ -public class TrafficLight1 -{ - private String color; - private int reds; - - /** - Constructs a green traffic light. - */ - public TrafficLight1() - { - this.color = "green"; - this.reds = 0; - } - - /** - Constructs a traffic light. - @param initialColor the initial color "green", "yellow", or "red" - */ - public TrafficLight1(String initialColor) - { - this.color = initialColor; - this.reds = initialColor == "red" ? 1 : 0; - } - - /** - Moves this traffic light to the next color. - */ - public void next() - { - switch (this.color) { - case "red": - this.color = "green"; - break; - case "green": - this.color = "yellow"; - break; - case "yellow": - this.color = "red"; - this.reds += 1; - break; - } - } - - /** - Returns the current color of this traffic light. - @return the current color - */ - public String getColor() - { - return this.color; - } - - /** - Counts how often this traffic light has been red. - @return the number of times this traffic light has been red - */ - public int getReds() - { - return this.reds; - } -} \ No newline at end of file diff --git a/1ano/2semestre/poo/src/tp_codecheck/tp03/part1/TrafficLight2.java b/1ano/2semestre/poo/src/tp_codecheck/tp03/part1/TrafficLight2.java deleted file mode 100644 index a929261..0000000 --- a/1ano/2semestre/poo/src/tp_codecheck/tp03/part1/TrafficLight2.java +++ /dev/null @@ -1,68 +0,0 @@ -package tp_codecheck.tp03.part1; - -/** - A simulated traffic light. -*/ -public class TrafficLight2 -{ - private int steps; - - /** - Constructs a green traffic light. - */ - public TrafficLight2() - { - this.steps = 0; - } - - /** - Constructs a traffic light. - @param initialColor the initial color "green", "yellow", or "red" - */ - public TrafficLight2(String initialColor) - { - switch (initialColor) { - case "green": - this.steps = 0; - break; - case "yellow": - this.steps = 1; - break; - case "red": - this.steps = 2; - break; - } - } - - /** - Moves this traffic light to the next color. - */ - public void next() - { - steps++; - } - - /** - Returns the current color of this traffic light. - @return the current color - */ - public String getColor() - { - int rem = (this.steps + 1) % 3; - if (rem == 0) - return "red"; - else if (rem == 1) - return "green"; - else - return "yellow"; - } - - /** - Counts how often this traffic light has been red. - @return the number of times this traffic light has been red - */ - public int getReds() - { - return (this.steps + 1) / 3; - } -} \ No newline at end of file diff --git a/1ano/2semestre/poo/src/tp_codecheck/tp03/part2/RentalCar.java b/1ano/2semestre/poo/src/tp_codecheck/tp03/part2/RentalCar.java deleted file mode 100644 index f10c708..0000000 --- a/1ano/2semestre/poo/src/tp_codecheck/tp03/part2/RentalCar.java +++ /dev/null @@ -1,72 +0,0 @@ -package tp_codecheck.tp03.part2; - -public class RentalCar { - private boolean rented; - private static int rentedCount = 0; - private static int availableCount = 0; - - /** - * Constructs a rental car. - */ - public RentalCar() { - // your work here - rented = false; - RentalCar.availableCount++; - } - - /** - * Get number of cars available. - * - * @return count of cars that are available - */ - public static int numAvailable() { - // your work here - return RentalCar.availableCount; - } - - /** - * Get number of cars rented. - * - * @return count of cars that are rented - */ - public static int numRented() { - // your work here - return RentalCar.rentedCount; - } - - /** - * Try to rent this car. - * - * @return true if the car was successfully rented, false if it was already - * rented - */ - public boolean rentCar() { - // your work here - if (this.rented) { - return false; - } else { - this.rented = true; - RentalCar.rentedCount++; - RentalCar.availableCount--; - return true; - } - } - - /** - * Return rented car. - * - * @return true if the car was previously rented and is now returned, - * false if it was not previously rented - */ - public boolean returnCar() { - // your work here - if (this.rented) { - this.rented = false; - RentalCar.rentedCount--; - RentalCar.availableCount++; - return true; - } else { - return false; - } - } -} diff --git a/1ano/2semestre/poo/src/utils/DateYMD.java b/1ano/2semestre/poo/src/utils/DateYMD.java index b4723c4..debf3d7 100644 --- a/1ano/2semestre/poo/src/utils/DateYMD.java +++ b/1ano/2semestre/poo/src/utils/DateYMD.java @@ -13,6 +13,27 @@ public class DateYMD { this.year = year; } + static boolean validMonth(int month) { + return month >= 1 && month <= 12; + } + + static int monthDays(int month, int year) { + if (!validMonth(month)) + return -1; + int[] daysPerMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; + if (month == 2 && isLeapYear(year)) + return 29; + return daysPerMonth[month - 1]; + } + + static boolean isLeapYear(int year) { + return year % 100 == 0 ? year % 400 == 0 : year % 4 == 0; + } + + public static boolean validDate(int day, int month, int year) { + return day >= 1 && day <= monthDays(month, year); + } + public void set(int day, int month, int year) { if (!validDate(day, month, year)) throw new IllegalArgumentException("Invalid date"); @@ -71,24 +92,4 @@ public class DateYMD { public String toString() { return String.format("%04d-%02d-%02d", this.year, this.month, this.day); } - static boolean validMonth(int month) { - return month >= 1 && month <= 12; - } - - static int monthDays(int month, int year) { - if (!validMonth(month)) - return -1; - int[] daysPerMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; - if (month == 2 && isLeapYear(year)) - return 29; - return daysPerMonth[month - 1]; - } - - static boolean isLeapYear(int year) { - return year % 100 == 0 ? year % 400 == 0 : year % 4 == 0; - } - - public static boolean validDate(int day, int month, int year) { - return day >= 1 && day <= monthDays(month, year); - } } \ No newline at end of file