[POO] Code reformat

--> Optimized and reformated code for all directories in source
This commit is contained in:
Tiago Garcia 2023-05-31 19:51:15 +01:00
parent ebdf870158
commit 1e907ab148
No known key found for this signature in database
GPG Key ID: F423E37A2415E160
78 changed files with 439 additions and 344 deletions

View File

@ -1,4 +1,5 @@
package aula01; package aula01;
import java.util.Scanner; import java.util.Scanner;
public class KmToMiles { public class KmToMiles {

View File

@ -1,4 +1,5 @@
package aula01; package aula01;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;

View File

@ -2,6 +2,7 @@ package aula02;
// Código da package utils disponível em // Código da package utils disponível em
// https://github.com/TiagoRG/uaveiro-leci/tree/master/1ano/2semestre/poo/src/utils // https://github.com/TiagoRG/uaveiro-leci/tree/master/1ano/2semestre/poo/src/utils
import utils.UserInput; import utils.UserInput;
import java.util.Scanner; import java.util.Scanner;

View File

@ -2,6 +2,7 @@ package aula02;
// Código da package utils disponível em // Código da package utils disponível em
// https://github.com/TiagoRG/uaveiro-leci/tree/master/1ano/2semestre/poo/src/utils // https://github.com/TiagoRG/uaveiro-leci/tree/master/1ano/2semestre/poo/src/utils
import utils.UserInput; import utils.UserInput;
import java.util.Scanner; import java.util.Scanner;

View File

@ -2,6 +2,7 @@ package aula02;
// Código da package utils disponível em // Código da package utils disponível em
// https://github.com/TiagoRG/uaveiro-leci/tree/master/1ano/2semestre/poo/src/utils // https://github.com/TiagoRG/uaveiro-leci/tree/master/1ano/2semestre/poo/src/utils
import utils.UserInput; import utils.UserInput;
import java.util.Scanner; import java.util.Scanner;

View File

@ -2,6 +2,7 @@ package aula02;
// Código da package utils disponível em // Código da package utils disponível em
// https://github.com/TiagoRG/uaveiro-leci/tree/master/1ano/2semestre/poo/src/utils // https://github.com/TiagoRG/uaveiro-leci/tree/master/1ano/2semestre/poo/src/utils
import utils.UserInput; import utils.UserInput;
import java.util.Scanner; import java.util.Scanner;

View File

@ -2,6 +2,7 @@ package aula02;
// Código da package utils disponível em // Código da package utils disponível em
// https://github.com/TiagoRG/uaveiro-leci/tree/master/1ano/2semestre/poo/src/utils // https://github.com/TiagoRG/uaveiro-leci/tree/master/1ano/2semestre/poo/src/utils
import utils.UserInput; import utils.UserInput;
import java.util.Scanner; import java.util.Scanner;

View File

@ -2,6 +2,7 @@ package aula02;
// Código da package utils disponível em // Código da package utils disponível em
// https://github.com/TiagoRG/uaveiro-leci/tree/master/1ano/2semestre/poo/src/utils // https://github.com/TiagoRG/uaveiro-leci/tree/master/1ano/2semestre/poo/src/utils
import utils.UserInput; import utils.UserInput;
import java.util.Scanner; import java.util.Scanner;

View File

@ -103,9 +103,11 @@ class Property {
public int getId() { public int getId() {
return this.id; return this.id;
} }
public boolean isAvailable() { public boolean isAvailable() {
return this.availability; return this.availability;
} }
public void setAvailability(boolean availability) { public void setAvailability(boolean availability) {
this.availability = availability; this.availability = availability;
} }

View File

@ -15,6 +15,27 @@ public class DateYMD {
this.year = year; 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) { public void set(int day, int month, int year) {
if (!validDate(day, month, year)) if (!validDate(day, month, year))
throw new IllegalArgumentException("Invalid date"); throw new IllegalArgumentException("Invalid date");
@ -73,26 +94,6 @@ public class DateYMD {
public String toString() { public String toString() {
return String.format("%04d-%02d-%02d", this.year, this.month, this.day); 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 { class TestDateYMD {

View File

@ -19,6 +19,7 @@ public class Bolser extends Student{
public Professor getSupervisor() { public Professor getSupervisor() {
return this.supervisor; return this.supervisor;
} }
public void setSupervisor(Professor supervisor) { public void setSupervisor(Professor supervisor) {
if (supervisor == null) { if (supervisor == null) {
throw new IllegalArgumentException("Supervisor cannot be null"); throw new IllegalArgumentException("Supervisor cannot be null");
@ -29,6 +30,7 @@ public class Bolser extends Student{
public double getMonthlyAmount() { public double getMonthlyAmount() {
return this.monthlyAmount; return this.monthlyAmount;
} }
public void setMonthlyAmount(double monthlyAmount) { public void setMonthlyAmount(double monthlyAmount) {
if (monthlyAmount < 0) { if (monthlyAmount < 0) {
throw new IllegalArgumentException("Monthly amount cannot be negative"); throw new IllegalArgumentException("Monthly amount cannot be negative");

View File

@ -18,6 +18,7 @@ public class Person {
public String getName() { public String getName() {
return this.name; return this.name;
} }
public void setName(String name) { public void setName(String name) {
if (name == null || name.isEmpty()) if (name == null || name.isEmpty())
throw new IllegalArgumentException("Name cannot be null or empty"); throw new IllegalArgumentException("Name cannot be null or empty");
@ -27,6 +28,7 @@ public class Person {
public int getCc() { public int getCc() {
return this.cc; return this.cc;
} }
public void setCc(int cc) { public void setCc(int cc) {
if (String.valueOf(cc).length() != 8) if (String.valueOf(cc).length() != 8)
throw new IllegalArgumentException("CC must have 8 digits"); throw new IllegalArgumentException("CC must have 8 digits");
@ -36,6 +38,7 @@ public class Person {
public DateYMD getBirthDate() { public DateYMD getBirthDate() {
return this.birthDate; return this.birthDate;
} }
public void setBirthDate(DateYMD birthDate) { public void setBirthDate(DateYMD birthDate) {
if (birthDate == null) if (birthDate == null)
throw new IllegalArgumentException("Birth date cannot be null"); throw new IllegalArgumentException("Birth date cannot be null");

View File

@ -15,6 +15,7 @@ public class Professor extends Person {
public String getCategory() { public String getCategory() {
return this.category; return this.category;
} }
public void setCategory(String category) { public void setCategory(String category) {
if (category == null || category.isEmpty()) if (category == null || category.isEmpty())
throw new IllegalArgumentException("Category cannot be null or empty"); throw new IllegalArgumentException("Category cannot be null or empty");
@ -26,6 +27,7 @@ public class Professor extends Person {
public String getDepartment() { public String getDepartment() {
return this.department; return this.department;
} }
public void setDepartment(String department) { public void setDepartment(String department) {
if (department == null || department.isEmpty()) if (department == null || department.isEmpty())
throw new IllegalArgumentException("Department cannot be null or empty"); throw new IllegalArgumentException("Department cannot be null or empty");

View File

@ -5,9 +5,9 @@ import utils.DateYMD;
import java.time.LocalDate; import java.time.LocalDate;
public class Student extends Person { public class Student extends Person {
public static int currentNMec = 100;
private DateYMD registrationDate; private DateYMD registrationDate;
private int nMec; private int nMec;
public static int currentNMec = 100;
public Student(String name, int cc, DateYMD birthDate, DateYMD registrationDate) { public Student(String name, int cc, DateYMD birthDate, DateYMD registrationDate) {
super(name, cc, birthDate); super(name, cc, birthDate);
@ -22,6 +22,7 @@ public class Student extends Person {
public int getNMec() { public int getNMec() {
return this.nMec; return this.nMec;
} }
public void setNMec(int nMec) { public void setNMec(int nMec) {
this.nMec = nMec; this.nMec = nMec;
} }
@ -29,6 +30,7 @@ public class Student extends Person {
public DateYMD getRegistrationDate() { public DateYMD getRegistrationDate() {
return this.registrationDate; return this.registrationDate;
} }
public void setRegistrationDate(DateYMD registrationDate) { public void setRegistrationDate(DateYMD registrationDate) {
LocalDate now = LocalDate.now(); LocalDate now = LocalDate.now();
this.registrationDate = registrationDate == null ? new DateYMD(now.getDayOfMonth(), now.getMonthValue(), now.getYear()) : registrationDate; this.registrationDate = registrationDate == null ? new DateYMD(now.getDayOfMonth(), now.getMonthValue(), now.getYear()) : registrationDate;

View File

@ -3,13 +3,12 @@ package aula06.ex2;
import aula06.ex1.Person; import aula06.ex1.Person;
public class Contact { public class Contact {
private static int currentId = 1;
private final int id; private final int id;
private Person person; private Person person;
private String email; private String email;
private String phone; private String phone;
private static int currentId = 1;
public Contact(Person person, String email, String phone) { public Contact(Person person, String email, String phone) {
if ((email == null || email.isEmpty()) && (phone == null || phone.isEmpty())) if ((email == null || email.isEmpty()) && (phone == null || phone.isEmpty()))
throw new IllegalArgumentException("Either email or phone must be provided"); throw new IllegalArgumentException("Either email or phone must be provided");
@ -26,6 +25,7 @@ public class Contact {
public Person getPerson() { public Person getPerson() {
return person; return person;
} }
public void setPerson(Person person) { public void setPerson(Person person) {
if (person == null) if (person == null)
throw new IllegalArgumentException("Person must be provided"); throw new IllegalArgumentException("Person must be provided");
@ -35,6 +35,7 @@ public class Contact {
public String getEmail() { public String getEmail() {
return email; return email;
} }
public void setEmail(String email) { public void setEmail(String email) {
if (!(email == null || email.isEmpty()) && 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]+$"))
@ -45,6 +46,7 @@ public class Contact {
public String getPhone() { public String getPhone() {
return phone; return phone;
} }
public void setPhone(String phone) { public void setPhone(String phone) {
if (!(phone == null || phone.isEmpty()) && if (!(phone == null || phone.isEmpty()) &&
!phone.matches("^9[0-9]{8}$")) !phone.matches("^9[0-9]{8}$"))

View File

@ -40,6 +40,7 @@ public class ContactList {
System.out.print("> "); System.out.print("> ");
return sin.nextLine(); return sin.nextLine();
} }
private static void addContact() { private static void addContact() {
System.out.print("Insira o nome: "); System.out.print("Insira o nome: ");
String name = sin.nextLine(); String name = sin.nextLine();
@ -69,6 +70,7 @@ public class ContactList {
contacts = newContacts; contacts = newContacts;
} }
} }
private static void changeContact() { private static void changeContact() {
System.out.print("Insira o nome, email ou telefone do contacto que pretende alterar: "); System.out.print("Insira o nome, email ou telefone do contacto que pretende alterar: ");
String query = sin.nextLine(); String query = sin.nextLine();

View File

@ -7,12 +7,15 @@ public class Vector {
public Vector() { public Vector() {
this.vector = new int[0]; this.vector = new int[0];
} }
public Vector(int size) { public Vector(int size) {
this.vector = new int[size]; this.vector = new int[size];
} }
public Vector(int[] vector) { public Vector(int[] vector) {
this.vector = vector; this.vector = vector;
} }
public int[] getVector() { public int[] getVector() {
return vector; return vector;
} }
@ -21,12 +24,14 @@ public class Vector {
public int size() { public int size() {
return this.vector.length; return this.vector.length;
} }
public boolean contains(int value) { public boolean contains(int value) {
for (int n : this.vector) for (int n : this.vector)
if (n == value) if (n == value)
return true; return true;
return false; return false;
} }
public int count(int value) { public int count(int value) {
int count = 0; int count = 0;
for (int n : this.vector) for (int n : this.vector)
@ -43,6 +48,7 @@ public class Vector {
aux[this.size()] = value; aux[this.size()] = value;
this.vector = aux; this.vector = aux;
} }
public void remove(int value) { 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; int i = 0;
@ -54,6 +60,7 @@ public class Vector {
} }
this.vector = aux; this.vector = aux;
} }
public void empty() { public void empty() {
this.vector = new int[0]; this.vector = new int[0];
} }
@ -69,6 +76,7 @@ public class Vector {
result.insert(n); result.insert(n);
return result; return result;
} }
public Vector subtract(Vector secondVector) { public Vector subtract(Vector secondVector) {
Vector result = new Vector(); Vector result = new Vector();
for (int n : this.vector) for (int n : this.vector)
@ -76,6 +84,7 @@ public class Vector {
result.insert(n); result.insert(n);
return result; return result;
} }
public Vector intersect(Vector secondVector) { public Vector intersect(Vector secondVector) {
Vector result = new Vector(); Vector result = new Vector();
for (int n : this.vector) for (int n : this.vector)

View File

@ -4,12 +4,17 @@ package aula06.ex3;
public class VectorTest { public class VectorTest {
public static void main(String[] args) { public static void main(String[] args) {
Vector c1 = new Vector(); 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(); 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); 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(c1);
System.out.println(c2); System.out.println(c2);

View File

@ -2,8 +2,12 @@ package aula07.ex1;
public abstract class Shape { public abstract class Shape {
protected String color; protected String color;
public abstract boolean equals(Shape c2); public abstract boolean equals(Shape c2);
public abstract String toString(); public abstract String toString();
public abstract double getArea(); public abstract double getArea();
public abstract double getPerimeter(); public abstract double getPerimeter();
} }

View File

@ -1,16 +1,6 @@
package aula07.ex2; package aula07.ex2;
public abstract class Date { 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) { public static int monthDays(int month, int year) {
if (!validMonth(month)) if (!validMonth(month))
return -1; return -1;
@ -31,4 +21,20 @@ public abstract class Date {
public static boolean isLeapYear(int year) { public static boolean isLeapYear(int year) {
return year % 100 == 0 ? year % 400 == 0 : year % 4 == 0; 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);
} }

View File

@ -6,7 +6,8 @@ public class DateTest {
public static void main(String[] args) { public static void main(String[] args) {
Scanner sin = new Scanner(System.in); Scanner sin = new Scanner(System.in);
mainLoop: while (true) { mainLoop:
while (true) {
System.out.print("Class to test (0-Quit;1-DateYMD;2-DateND): "); System.out.print("Class to test (0-Quit;1-DateYMD;2-DateND): ");
int classoption = sin.nextInt(); int classoption = sin.nextInt();
@ -17,7 +18,8 @@ public class DateTest {
} }
case 1 -> { case 1 -> {
DateYMD date = null; DateYMD date = null;
class1Loop: while (true) { class1Loop:
while (true) {
System.out.println("Date operations:"); System.out.println("Date operations:");
System.out.println("1 - Create date"); System.out.println("1 - Create date");
System.out.println("2 - Show current date"); System.out.println("2 - Show current date");
@ -28,8 +30,9 @@ public class DateTest {
System.out.print("Option: "); System.out.print("Option: ");
int option = sin.nextInt(); int option = sin.nextInt();
if (option == 0) if (option == 0)
break class1Loop; break;
class1Switch: switch (option) { class1Switch:
switch (option) {
case 1 -> { case 1 -> {
System.out.print("Day: "); System.out.print("Day: ");
int day = sin.nextInt(); int day = sin.nextInt();
@ -43,21 +46,21 @@ public class DateTest {
case 2 -> { case 2 -> {
if (date == null) { if (date == null) {
System.out.println("Date not created"); System.out.println("Date not created");
break class1Switch; break;
} }
System.out.println("Current date: " + date); System.out.println("Current date: " + date);
} }
case 3 -> { case 3 -> {
if (date == null) { if (date == null) {
System.out.println("Date not created"); System.out.println("Date not created");
break class1Switch; break;
} }
System.out.println("Current date: " + new DateND(date.getAbsDay())); System.out.println("Current date: " + new DateND(date.getAbsDay()));
} }
case 4 -> { case 4 -> {
if (date == null) { if (date == null) {
System.out.println("Date not created"); System.out.println("Date not created");
break class1Switch; break;
} }
System.out.print("Number of days to increment date by: "); System.out.print("Number of days to increment date by: ");
int daysToIncrement = sin.nextInt(); int daysToIncrement = sin.nextInt();
@ -67,7 +70,7 @@ public class DateTest {
case 5 -> { case 5 -> {
if (date == null) { if (date == null) {
System.out.println("Date not created"); System.out.println("Date not created");
break class1Switch; break;
} }
System.out.print("Number of days to decremente date by: "); System.out.print("Number of days to decremente date by: ");
int daysToDecrement = sin.nextInt(); int daysToDecrement = sin.nextInt();
@ -80,7 +83,8 @@ public class DateTest {
} }
case 2 -> { case 2 -> {
DateND date = null; DateND date = null;
class2Loop: while (true) { class2Loop:
while (true) {
System.out.println("Date operations:"); System.out.println("Date operations:");
System.out.println("1 - Create date"); System.out.println("1 - Create date");
System.out.println("2 - Show current date"); System.out.println("2 - Show current date");
@ -91,8 +95,9 @@ public class DateTest {
System.out.print("Option: "); System.out.print("Option: ");
int option = sin.nextInt(); int option = sin.nextInt();
if (option == 0) if (option == 0)
break class2Loop; break;
class2Switch: switch (option) { class2Switch:
switch (option) {
case 1 -> { case 1 -> {
System.out.print("Day: "); System.out.print("Day: ");
int day = sin.nextInt(); int day = sin.nextInt();
@ -102,21 +107,21 @@ public class DateTest {
case 2 -> { case 2 -> {
if (date == null) { if (date == null) {
System.out.println("Date not created"); System.out.println("Date not created");
break class2Switch; break;
} }
System.out.println("Current date: " + date); System.out.println("Current date: " + date);
} }
case 3 -> { case 3 -> {
if (date == null) { if (date == null) {
System.out.println("Date not created"); System.out.println("Date not created");
break class2Switch; break;
} }
System.out.println("Current date: " + new DateYMD(date.getDay(), date.getMonth(), date.getYear())); System.out.println("Current date: " + new DateYMD(date.getDay(), date.getMonth(), date.getYear()));
} }
case 4 -> { case 4 -> {
if (date == null) { if (date == null) {
System.out.println("Date not created"); System.out.println("Date not created");
break class2Switch; break;
} }
System.out.print("Number of days to increment date by: "); System.out.print("Number of days to increment date by: ");
int daysToIncrement = sin.nextInt(); int daysToIncrement = sin.nextInt();
@ -126,7 +131,7 @@ public class DateTest {
case 5 -> { case 5 -> {
if (date == null) { if (date == null) {
System.out.println("Date not created"); System.out.println("Date not created");
break class2Switch; break;
} }
System.out.print("Number of days to decremente date by: "); System.out.print("Number of days to decremente date by: ");
int daysToDecrement = sin.nextInt(); int daysToDecrement = sin.nextInt();

View File

@ -3,10 +3,10 @@ package aula07.ex3;
public class Game { public class Game {
private final Team team1; private final Team team1;
private final Team team2; private final Team team2;
private int team1Goals;
private int team2Goals;
private final Ball ball; private final Ball ball;
private final double gameDuration; private final double gameDuration;
private int team1Goals;
private int team2Goals;
private double timeElapsed; private double timeElapsed;
public Game(Team team1, Team team2, Ball ball, double gameDuration) { public Game(Team team1, Team team2, Ball ball, double gameDuration) {

View File

@ -75,7 +75,8 @@ public class Main {
System.out.println("3 - Adicionar golo"); System.out.println("3 - Adicionar golo");
System.out.print("Opção: "); System.out.print("Opção: ");
int option = Integer.parseInt(sin.nextLine()); int option = Integer.parseInt(sin.nextLine());
swit : switch (option) { swit:
switch (option) {
case 1 -> { case 1 -> {
System.out.print("Novo X: "); System.out.print("Novo X: ");
double x = Double.parseDouble(sin.nextLine()); double x = Double.parseDouble(sin.nextLine());

View File

@ -23,6 +23,7 @@ public class Robot extends MovableObject {
public PlayerPosition getPlayerPosition() { public PlayerPosition getPlayerPosition() {
return this.playerPosition; return this.playerPosition;
} }
public void setPlayerPosition(PlayerPosition playerPosition) { public void setPlayerPosition(PlayerPosition playerPosition) {
this.playerPosition = playerPosition; this.playerPosition = playerPosition;
} }
@ -30,6 +31,7 @@ public class Robot extends MovableObject {
public int getGoalsScored() { public int getGoalsScored() {
return this.goalsScored; return this.goalsScored;
} }
public void increaseGoalsScored() { public void increaseGoalsScored() {
this.goalsScored++; this.goalsScored++;
} }

View File

@ -2,5 +2,6 @@ package aula08.ex1.Interfaces;
public interface IElectricVehicle { public interface IElectricVehicle {
int currentBatteryLvl(); int currentBatteryLvl();
void charge(int percentage); void charge(int percentage);
} }

View File

@ -2,5 +2,6 @@ package aula08.ex1.Interfaces;
public interface IFuelVehicle { public interface IFuelVehicle {
int fuelLevel(); int fuelLevel();
void fillTank(int level); void fillTank(int level);
} }

View File

@ -2,6 +2,8 @@ package aula08.ex1.Interfaces;
public interface IKmTravelled { public interface IKmTravelled {
void trip(int km); void trip(int km);
int lastTrip(); int lastTrip();
int totalDistance(); int totalDistance();
} }

View File

@ -64,13 +64,6 @@ public class Motorcycle extends Vehicle implements IFuelVehicle {
public enum MotorcycleType { public enum MotorcycleType {
SPORT, TOURING; SPORT, TOURING;
public String toString() {
return switch (this) {
case SPORT -> "Sport";
case TOURING -> "Touring";
};
}
public static MotorcycleType fromString(String s) { public static MotorcycleType fromString(String s) {
return switch (s) { return switch (s) {
case "SPORT", "Sport", "sport" -> SPORT; case "SPORT", "Sport", "sport" -> SPORT;
@ -78,5 +71,12 @@ public class Motorcycle extends Vehicle implements IFuelVehicle {
default -> throw new IllegalArgumentException("Invalid MotorcycleType: " + s); default -> throw new IllegalArgumentException("Invalid MotorcycleType: " + s);
}; };
} }
public String toString() {
return switch (this) {
case SPORT -> "Sport";
case TOURING -> "Touring";
};
}
} }
} }

View File

@ -5,10 +5,10 @@ import aula08.ex2.Enums.AlimentOrigin;
import java.util.Objects; import java.util.Objects;
public abstract class Aliment { public abstract class Aliment {
final AlimentOrigin alimentOrigin;
double proteins; double proteins;
double calories; double calories;
double weight; double weight;
final AlimentOrigin alimentOrigin;
public Aliment(double proteins, double calories, double weight, AlimentOrigin alimentOrigin) { public Aliment(double proteins, double calories, double weight, AlimentOrigin alimentOrigin) {
setProteins(proteins); setProteins(proteins);
@ -19,7 +19,7 @@ public abstract class Aliment {
public double getProteins() { public double getProteins() {
return this.proteins; return this.proteins;
}; }
public void setProteins(double proteins) { public void setProteins(double proteins) {
if (proteins <= 0) if (proteins <= 0)

View File

@ -2,9 +2,14 @@ package aula08.ex3.Interfaces;
public interface IProduct { public interface IProduct {
String getName(); String getName();
void setPrice(double price);
double getPrice(); double getPrice();
void setPrice(double price);
int stock(); int stock();
void addStock(int amount); void addStock(int amount);
void removeStock(int amount); void removeStock(int amount);
} }

View File

@ -4,6 +4,8 @@ import aula08.ex3.Product;
public interface IPurchase { public interface IPurchase {
void addProduct(Product product, int amount); void addProduct(Product product, int amount);
void listProducts(); void listProducts();
double getTotal(); double getTotal();
} }

View File

@ -11,7 +11,8 @@ import java.util.Set;
public class ALDemo { public class ALDemo {
public static void main(String[] args) { public static void main(String[] args) {
ArrayList<Integer> c1 = new ArrayList<>(); ArrayList<Integer> c1 = new ArrayList<>();
for(int i= 10; i<= 100; i+=10) c1.add(i);System.out.println("Size: "+ c1.size()); 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++) for (int i = 0; i < c1.size(); i++)
System.out.println("Elemento: " + c1.get(i)); System.out.println("Elemento: " + c1.get(i));

View File

@ -67,8 +67,7 @@ public class PlaneManager {
for (Plane plane : planes) { for (Plane plane : planes) {
if (plane instanceof CommercialPlane && type.equals("commercial")) { if (plane instanceof CommercialPlane && type.equals("commercial")) {
System.out.println(plane); System.out.println(plane);
} } else if (plane instanceof MilitaryPlane && type.equals("military")) {
else if (plane instanceof MilitaryPlane && type.equals("military")) {
System.out.println(plane); System.out.println(plane);
} }
} }

View File

@ -57,8 +57,7 @@ public class PlaneTester {
System.out.print("Enter the plane's crew members count: "); System.out.print("Enter the plane's crew members count: ");
int crewMembersCount = Integer.parseInt(scanner.nextLine()); int crewMembersCount = Integer.parseInt(scanner.nextLine());
planeManager.addPlane(new CommercialPlane(id, manufacturer, model, year, passengerCount, maxSpeed, crewMembersCount)); 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: "); System.out.print("Enter the plane's missile count: ");
int missileCount = Integer.parseInt(scanner.nextLine()); int missileCount = Integer.parseInt(scanner.nextLine());
planeManager.addPlane(new MilitaryPlane(id, manufacturer, model, year, passengerCount, maxSpeed, missileCount)); planeManager.addPlane(new MilitaryPlane(id, manufacturer, model, year, passengerCount, maxSpeed, missileCount));

View File

@ -13,12 +13,29 @@ public class Book {
this.setYear(year); this.setYear(year);
} }
public String getTitle() { return this.title; } public String getTitle() {
public void setTitle(String title) { this.title = title; } return this.title;
public String getAuthor() { return this.author; } }
public void setAuthor(String author) { this.author = author; }
public int getYear() { return this.year; } public void setTitle(String title) {
public void setYear(int year) { this.year = year; } 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 @Override
public String toString() { public String toString() {

View File

@ -15,6 +15,16 @@ public class FlightManager {
private String delaysTable; private String delaysTable;
private String flightsNTable; private String flightsNTable;
private static Map<String, Integer> sortByValue(Map<String, Integer> unsortMap) {
List<Map.Entry<String, Integer>> 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) { public void loadCompanies(String filename) {
Scanner input; Scanner input;
try { try {
@ -127,14 +137,4 @@ public class FlightManager {
} }
} }
} }
private static Map<String, Integer> sortByValue(Map<String, Integer> unsortMap) {
List<Map.Entry<String, Integer>> 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));
}
} }

View File

@ -11,6 +11,14 @@ public class Time {
this.minute = minute; 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) { public Time addTime(Time time) {
int newHour = hour + time.hour(); int newHour = hour + time.hour();
int newMinute = minute + time.minute(); int newMinute = minute + time.minute();
@ -34,14 +42,6 @@ public class Time {
return String.format("%02d:%02d", hour, minute); 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() { public int hour() {
return hour; return hour;
} }

View File

@ -26,11 +26,16 @@ public class Animal {
return id; return id;
} }
public String getName() {
return name;
}
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
public String getName() {
return name; public int getWeight() {
return weight;
} }
public void setWeight(int weight) { public void setWeight(int weight) {
@ -38,8 +43,9 @@ public class Animal {
throw new IllegalArgumentException("Weight must be positive!"); throw new IllegalArgumentException("Weight must be positive!");
this.weight = weight; this.weight = weight;
} }
public int getWeight() {
return weight; public int getAge() {
return age;
} }
public void setAge(int age) { public void setAge(int age) {
@ -47,21 +53,20 @@ public class Animal {
throw new IllegalArgumentException("Age must be positive!"); throw new IllegalArgumentException("Age must be positive!");
this.age = age; this.age = age;
} }
public int getAge() {
return age; public String getSponsor() {
return sponsor;
} }
public void setSponsor(String sponsor) { public void setSponsor(String sponsor) {
this.sponsor = sponsor; this.sponsor = sponsor;
} }
public String getSponsor() {
return sponsor;
}
@Override @Override
public String toString() { 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); 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 @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) return true;
@ -69,6 +74,7 @@ public class Animal {
Animal animal = (Animal) o; Animal animal = (Animal) o;
return id == animal.id && weight == animal.weight && age == animal.age && Objects.equals(name, animal.name) && Objects.equals(sponsor, animal.sponsor); return id == animal.id && weight == animal.weight && age == animal.age && Objects.equals(name, animal.name) && Objects.equals(sponsor, animal.sponsor);
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(id, name, weight, age, sponsor); return Objects.hash(id, name, weight, age, sponsor);

View File

@ -1,9 +1,13 @@
package aval.aa1; package aval.aa1;
public interface IPetShelter { public interface IPetShelter {
public void addAnimal(Animal animal); void addAnimal(Animal animal);
public void removeAnimal(Animal animal);
public Animal searchForAnimal(String name); void removeAnimal(Animal animal);
public boolean sponsorAnimal(int animalId);
public void listAllAnimals(); Animal searchForAnimal(String name);
boolean sponsorAnimal(int animalId);
void listAllAnimals();
} }

View File

@ -3,7 +3,7 @@ package aval.aa1;
import java.util.Scanner; import java.util.Scanner;
public class PetShelter implements IPetShelter { public class PetShelter implements IPetShelter {
private String shelterName; private final String shelterName;
private Animal[] animals; private Animal[] animals;
public PetShelter(String shelterName) { public PetShelter(String shelterName) {
@ -17,9 +17,7 @@ public class PetShelter implements IPetShelter {
animals[0] = animal; animals[0] = animal;
} else { } else {
Animal[] newAnimals = new Animal[animals.length + 1]; Animal[] newAnimals = new Animal[animals.length + 1];
for (int i = 0; i < animals.length; i++) { System.arraycopy(animals, 0, newAnimals, 0, animals.length);
newAnimals[i] = animals[i];
}
newAnimals[newAnimals.length - 1] = animal; newAnimals[newAnimals.length - 1] = animal;
animals = newAnimals; animals = newAnimals;
} }

View File

@ -1,6 +1,5 @@
package aval.aa2.Classes; package aval.aa2.Classes;
import java.time.LocalDate;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;

View File

@ -9,7 +9,6 @@ import java.io.FileReader;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.time.LocalDate;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;

View File

@ -4,14 +4,16 @@ import java.time.LocalDate;
// YOU MAY ADD IMPORTS HERE // YOU MAY ADD IMPORTS HERE
public class RainfallInfo { public class RainfallInfo {
private LocalDate date; private final LocalDate date;
private String location; private final String location;
private double rainfall; private final double rainfall;
public RainfallInfo(LocalDate date, String location, double rainfall) { public RainfallInfo(LocalDate date, String location, double rainfall) {
this.date = date; this.date = date;
this.location = location; this.location = location;
this.rainfall = rainfall; this.rainfall = rainfall;
} }
public LocalDate date() { public LocalDate date() {
return date; return date;
} }
@ -34,5 +36,6 @@ public class RainfallInfo {
@Override @Override
public int hashCode() { public int hashCode() {
return date.hashCode() | location.hashCode() | Double.hashCode(rainfall); return date.hashCode() | location.hashCode() | Double.hashCode(rainfall);
}; }
} }

View File

@ -39,6 +39,7 @@ public class RainfallTest {
} }
return data; return data;
} }
public static String printLocationData(List<RainfallInfo> data, String loc) { public static String printLocationData(List<RainfallInfo> data, String loc) {
System.out.printf("Rainfall for location %s:\n", loc); System.out.printf("Rainfall for location %s:\n", loc);
// 2) Print rainfall values for the given location // 2) Print rainfall values for the given location
@ -68,7 +69,8 @@ public class RainfallTest {
// YOU MAY ADD METHODS HERE // YOU MAY ADD METHODS HERE
public static String main() { public static String main() {
Test.lst = null; Test.map = null; Test.lst = null;
Test.map = null;
// Load the file data to the list // Load the file data to the list
List<RainfallInfo> rainfallData = loadData("rainfall_data.csv"); List<RainfallInfo> rainfallData = loadData("rainfall_data.csv");
System.out.printf("Data size: %d\n", rainfallData.size()); System.out.printf("Data size: %d\n", rainfallData.size());
@ -93,14 +95,14 @@ public class RainfallTest {
} }
class Test { class Test {
static List<RainfallInfo> lst = new ArrayList<>();
static Map<Month, Double> map = new HashMap<>();
// Variables used in unit tests (DON'T USE IN YOUR IMPLEMENTATION!): // Variables used in unit tests (DON'T USE IN YOUR IMPLEMENTATION!):
private static LocalDate[] dates = { private static final LocalDate[] dates = {
LocalDate.parse("2023-03-02"), LocalDate.parse("2023-03-02"),
LocalDate.parse("2023-04-17"), LocalDate.parse("2023-04-17"),
LocalDate.parse("2023-05-27"), LocalDate.parse("2023-05-27"),
}; };
static List<RainfallInfo> lst = new ArrayList<>();
static Map<Month, Double> map = new HashMap<>();
static { static {
lst.add(new RainfallInfo(dates[2], "Aveiro", 2.2)); lst.add(new RainfallInfo(dates[2], "Aveiro", 2.2));

View File

@ -13,6 +13,27 @@ public class DateYMD {
this.year = year; 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) { public void set(int day, int month, int year) {
if (!validDate(day, month, year)) if (!validDate(day, month, year))
throw new IllegalArgumentException("Invalid date"); throw new IllegalArgumentException("Invalid date");
@ -71,24 +92,4 @@ public class DateYMD {
public String toString() { public String toString() {
return String.format("%04d-%02d-%02d", this.year, this.month, this.day); 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);
}
} }