Skip to content

Solucion Lab #60

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .idea/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 13 additions & 0 deletions .idea/compiler.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions .idea/encodings.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

20 changes: 20 additions & 0 deletions .idea/jarRepositories.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 9 additions & 0 deletions .idea/lab-java-exceptions.iml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 14 additions & 0 deletions .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions .idea/modules.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Maria_Lopez.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Person{id=2, name='Maria Lopez', age=25, occupation='Doctora'}
17 changes: 17 additions & 0 deletions SolLabExceptions/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>org.example</groupId>
<artifactId>SolLabExceptions</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

</project>
59 changes: 59 additions & 0 deletions SolLabExceptions/src/main/java/Person.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
public class Person {
private int id;
private String name;
private int age;
private String occupation;

public Person(int id, String name, int age, String occupation) {
this.id = id;
this.name = name;
setAge(age);
this.occupation = occupation;
}

public int getId() {
return id;
}

public String getName() {
return name;
}

public int getAge() {
return age;
}

public String getOccupation() {
return occupation;
}


public void setAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("La edad no puede ser menor que 0");
}
this.age = age;
}


@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Person person = (Person) obj;
return age == person.age &&
name.equals(person.name) &&
occupation.equals(person.occupation);
}


@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", occupation='" + occupation + '\'' +
'}';
}
}
54 changes: 54 additions & 0 deletions SolLabExceptions/src/main/java/PersonsList.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class PersonsList {
private List<Person> people;

public PersonsList() {
this.people = new ArrayList<>();
}

public void addPerson(Person person) {
people.add(person);
}

public Person findByName(String name) {
// Verificar formato del nombre
if (name == null || !name.matches("^[A-Za-z]+ [A-Za-z]+$")) {
throw new IllegalArgumentException("El nombre debe tener formato 'firstName lastName'");
}

// Buscar la persona por nombre
for (Person person : people) {
if (person.getName().equals(name)) {
return person;
}
}

// Si no se encuentra la persona
throw new RuntimeException("No se encontró a la persona con nombre: " + name);
}

public Person clone(Person person) {
// Generar un nuevo ID
int newId = (int) (Math.random() * 10000);
return new Person(newId, person.getName(), person.getAge(), person.getOccupation());
}

public void writeToFile(Person person) {
String fileName = person.getName().replace(" ", "_") + ".txt";

try (FileWriter writer = new FileWriter(fileName)) {
writer.write(person.toString());
System.out.println("Información escrita en el archivo: " + fileName);
} catch (IOException e) {
System.err.println("Error al escribir en el archivo: " + e.getMessage());
}
}

public List<Person> getPeople() {
return people;
}
}
83 changes: 83 additions & 0 deletions SolLabExceptions/src/test/java/PersonsTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
public class PersonsTest {
public static void main(String[] args) {
// Crear algunas personas para las pruebas
Person person1 = new Person(1, "Juan Perez", 30, "Ingeniero");
Person person2 = new Person(2, "Maria Lopez", 25, "Doctora");
Person person3 = new Person(3, "Carlos Rodriguez", 40, "Abogado");

// Crear la lista de personas
PersonsList list = new PersonsList();
list.addPerson(person1);
list.addPerson(person2);
list.addPerson(person3);

testSetAgeWithNegativeValue();

testFindByNameWithCorrectFormat(list);

testFindByNameWithIncorrectFormat(list);

testCloneMethod(list, person1);

System.out.println("Todas las pruebas completadas.");
}

// Test 1: Prueba que setAge lance una excepción si la edad es negativa
private static void testSetAgeWithNegativeValue() {
System.out.println("\n----- Test 1: setAge con valor negativo -----");
try {
Person person = new Person(1, "Test Person", 30, "Tester");
person.setAge(-5);
System.out.println("ERROR: No se lanzó excepción al establecer edad negativa");
} catch (IllegalArgumentException e) {
System.out.println("ÉXITO: Se lanzó la excepción esperada: " + e.getMessage());
}
}

// Test 2: Prueba que findByName encuentre correctamente una persona con formato correcto
private static void testFindByNameWithCorrectFormat(PersonsList list) {
System.out.println("\n----- Test 2: findByName con formato correcto -----");
try {
Person found = list.findByName("Maria Lopez");
System.out.println("ÉXITO: Se encontró a la persona: " + found);
} catch (Exception e) {
System.out.println("ERROR: No se pudo encontrar a la persona: " + e.getMessage());
}
}

// Test 3: Prueba que findByName lance excepción con formato incorrecto
private static void testFindByNameWithIncorrectFormat(PersonsList list) {
System.out.println("\n----- Test 3: findByName con formato incorrecto -----");
try {
// Formato incorrecto: sin apellido
Person found = list.findByName("Maria");
System.out.println("ERROR: No se lanzó excepción con formato incorrecto");
} catch (IllegalArgumentException e) {
System.out.println("ÉXITO: Se lanzó la excepción esperada: " + e.getMessage());
} catch (Exception e) {
System.out.println("ERROR: Se lanzó una excepción inesperada: " + e.getMessage());
}
}

// Test 4: Prueba que clone cree una nueva persona con los mismos datos excepto el ID
private static void testCloneMethod(PersonsList list, Person original) {
System.out.println("\n----- Test 4: método clone -----");
Person cloned = list.clone(original);

System.out.println("Original: " + original);
System.out.println("Clonado: " + cloned);

boolean sameId = original.getId() == cloned.getId();
boolean sameProperties = original.getName().equals(cloned.getName()) &&
original.getAge() == cloned.getAge() &&
original.getOccupation().equals(cloned.getOccupation());

if (!sameId && sameProperties) {
System.out.println("ÉXITO: El clon tiene los mismos datos pero diferente ID");
} else {
System.out.println("ERROR: El clon no se creó correctamente");
if (sameId) System.out.println(" - Los IDs son iguales cuando deberían ser diferentes");
if (!sameProperties) System.out.println(" - Las propiedades no son iguales cuando deberían serlo");
}
}
}
Binary file added SolLabExceptions/target/classes/Person.class
Binary file not shown.
Binary file added SolLabExceptions/target/classes/PersonsList.class
Binary file not shown.
Binary file not shown.