From 0bd35d5c5a11f1259fa9467a114e48ff20c54cfd Mon Sep 17 00:00:00 2001 From: rr1583 Date: Thu, 20 Jun 2024 01:50:13 -0400 Subject: [PATCH] Exceptions Rene The lab involves creating and handling exceptions in a Java project by defining a Person class with various properties and methods, a PersonsList class to manage multiple Person objects, and implementing test cases to validate the functionality. --- .DS_Store | Bin 0 -> 6148 bytes .idea/.gitignore | 3 + .idea/lab-java-exceptions.iml | 12 + .idea/misc.xml | 6 + .idea/modules.xml | 8 + .idea/vcs.xml | 6 + out/.DS_Store | Bin 0 -> 6148 bytes out/production/.DS_Store | Bin 0 -> 6148 bytes .../lab-java-exceptions/.idea/.gitignore | 3 + .../.idea/lab-java-exceptions.iml | 12 + .../lab-java-exceptions/.idea/misc.xml | 6 + .../lab-java-exceptions/.idea/modules.xml | 8 + .../lab-java-exceptions/.idea/vcs.xml | 6 + out/production/lab-java-exceptions/README.md | 309 ++++++++++++++++++ .../labjavaexceptions/Main.class | Bin 0 -> 2398 bytes .../labjavaexceptions/Person.class | Bin 0 -> 2030 bytes .../labjavaexceptions/PersonsList.class | Bin 0 -> 2417 bytes .../lab-java-exceptions/src/README.md | 309 ++++++++++++++++++ person.txt | 1 + src/.DS_Store | Bin 0 -> 6148 bytes src/README.md | 309 ++++++++++++++++++ src/labjavaexceptions/.DS_Store | Bin 0 -> 6148 bytes src/labjavaexceptions/Main.java | 38 +++ src/labjavaexceptions/Person.java | 63 ++++ src/labjavaexceptions/PersonsList.java | 51 +++ 25 files changed, 1150 insertions(+) create mode 100644 .DS_Store create mode 100644 .idea/.gitignore create mode 100644 .idea/lab-java-exceptions.iml create mode 100644 .idea/misc.xml create mode 100644 .idea/modules.xml create mode 100644 .idea/vcs.xml create mode 100644 out/.DS_Store create mode 100644 out/production/.DS_Store create mode 100644 out/production/lab-java-exceptions/.idea/.gitignore create mode 100644 out/production/lab-java-exceptions/.idea/lab-java-exceptions.iml create mode 100644 out/production/lab-java-exceptions/.idea/misc.xml create mode 100644 out/production/lab-java-exceptions/.idea/modules.xml create mode 100644 out/production/lab-java-exceptions/.idea/vcs.xml create mode 100644 out/production/lab-java-exceptions/README.md create mode 100644 out/production/lab-java-exceptions/labjavaexceptions/Main.class create mode 100644 out/production/lab-java-exceptions/labjavaexceptions/Person.class create mode 100644 out/production/lab-java-exceptions/labjavaexceptions/PersonsList.class create mode 100644 out/production/lab-java-exceptions/src/README.md create mode 100644 person.txt create mode 100644 src/.DS_Store create mode 100644 src/README.md create mode 100644 src/labjavaexceptions/.DS_Store create mode 100644 src/labjavaexceptions/Main.java create mode 100644 src/labjavaexceptions/Person.java create mode 100644 src/labjavaexceptions/PersonsList.java diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..68073ddf50872ef34cc40cb5ec5f847441556bc0 GIT binary patch literal 6148 zcmeHK&2AGh5FR%vb*PYn1X3k9ti&}c>0c_uWgE5!4qUp39sq@GHfmShtfTCP973c$ z!-Y5D$`kMiybIz0Gxh|r{o%j?p=w4Nf3|1F)_jTW9RN_>X}kr{1OSanSigzQB|>)6 z3$ns9>xhchFoP&H5sqj%5n(_W_}>|zvs(iLQz)LMmGk=vEt@~A*d*91n&o3Y<)5Q* zn&d^h{Z*~h>Z>=_^qOARuftO_3yXd+&Aa`{OBy{lCXJT;e)J+4&U(!|PfS+ylWaJ# z0ZBYWmsiJ07MoeuOtUz*v7s~QhHmtl8}s?j?sm)D>Fh6B-u%&ayXAE{dy7Rw-+l1# z@lo$A9cAXdBVFO0WaSp)5E$Zo&xSDl6(6dR1A; zVFH75UiUBex;EU|oYRx7a9~Db%ylU>u$GYt0{)NakMEA}eZT$X09}4r<3Cu(r&q0d z?zdX*DfqVx@cGbm2Z#s*!hkUFI|Fn-c&LOvW9iUd9oX0s0I`nKRZ?i`4F%)NFxmVQwDwl3T(eK literal 0 HcmV?d00001 diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/.idea/lab-java-exceptions.iml b/.idea/lab-java-exceptions.iml new file mode 100644 index 0000000..7d82878 --- /dev/null +++ b/.idea/lab-java-exceptions.iml @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..e6be3f1 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..a23e12e --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/out/.DS_Store b/out/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..d7e67b3fb31dabe906dd695c72bd4429ccb33de7 GIT binary patch literal 6148 zcmeHKO-sW-5S^`66N}J;g2x4~MeA2Zyu_*puSWEsQX5k=7_+5G?V%KM)<5Jg@$cx& z?nadAQL!=uvv0CHFWI~eyBPow&3?EBPz3-7ov`F$^M%nk`Iwb#&lIB2_vphlWDtRZ zWGtII{-Of3c5~2$9JEyA?rQ)E7+reqn8MLYk`zp!WQPSyYLKJo|<>D+# zLN#creiEjd>ze_`b=+2UX*k^2T(8NE#`dTthdb-_nrt+-MkCi*TwdKhZr#QAiF(wt z2Z7(Kwt0&MJYn#q9uIymiB)og;{~_iFtP%y04p$Q3fO(jsZ83$dA_UwEAZnA(EcFN z2|bIsLA`Zgqe}q9GIndjn0^dz7DH!OZ7<1_;UP9M~{gMJi&th&6d(iktK+C`lEAXodyaBXqToC{O literal 0 HcmV?d00001 diff --git a/out/production/.DS_Store b/out/production/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..b76b3bdf9086c1ca2896929febbf04c2306b5e5e GIT binary patch literal 6148 zcmeHKQA-;^5T1>(UXVhd6?|OqHEODDiuiI(^}*L((Fa@7I}_}+*V~Z0m_i8LbNxg9 z690~Vv%4vkRPd=vnSt4FGCMPy`}WwqAtKcs_g@h;i70?F)*2Z8B0SH!AT{q<0xDbM z8^v@1-K4=nv^bt31H5-HD8rs5*tI|R?0`vZi0I!W`snRLxK?-w>VauY!#X!M%v)9LQ(otED1yq&f5bZ@8K z(w)wm*{l()ZEWv<=zY(A&{(`J53oTEL49xI2Kfhd;> zbg9a>7|Nx?uYFwTv2y6rN%`hO`IVLLP?TLA^|cKr6*`nr7!U^TGQhnbq{;XH;r;!; z4U$0^5C;BF22}kZI_Tor{N1|nlzi7}=ocsp$5jr0r@*jRF=F{DUWZzNU$X%WJys6k Qfyjq|r9lQ^;GZ&Z3ka`eKmY&$ literal 0 HcmV?d00001 diff --git a/out/production/lab-java-exceptions/.idea/.gitignore b/out/production/lab-java-exceptions/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/out/production/lab-java-exceptions/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/out/production/lab-java-exceptions/.idea/lab-java-exceptions.iml b/out/production/lab-java-exceptions/.idea/lab-java-exceptions.iml new file mode 100644 index 0000000..7d82878 --- /dev/null +++ b/out/production/lab-java-exceptions/.idea/lab-java-exceptions.iml @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/out/production/lab-java-exceptions/.idea/misc.xml b/out/production/lab-java-exceptions/.idea/misc.xml new file mode 100644 index 0000000..e6be3f1 --- /dev/null +++ b/out/production/lab-java-exceptions/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/out/production/lab-java-exceptions/.idea/modules.xml b/out/production/lab-java-exceptions/.idea/modules.xml new file mode 100644 index 0000000..a23e12e --- /dev/null +++ b/out/production/lab-java-exceptions/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/out/production/lab-java-exceptions/.idea/vcs.xml b/out/production/lab-java-exceptions/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/out/production/lab-java-exceptions/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/out/production/lab-java-exceptions/README.md b/out/production/lab-java-exceptions/README.md new file mode 100644 index 0000000..d76a5ac --- /dev/null +++ b/out/production/lab-java-exceptions/README.md @@ -0,0 +1,309 @@ +![logo_ironhack_blue 7](https://user-images.githubusercontent.com/23629340/40541063-a07a0a8a-601a-11e8-91b5-2f13e4e6b441.png) + +# LAB Java | Exceptions + + + +## Introduction + +We have just learned how to throw, handle and test exceptions so let's practice a bit more. + +
+ +## Requirements + +1. Fork this repo. +2. Clone this repo. +3. Add your instructor and the class graders as collaborators to your repository. If you are unsure who your class graders are, ask your instructor or refer to the day 1 slide deck. +4. In the repository, create a Java project and add the code for the following prompts. + +## Submission + +Once you finish the assignment, submit a URL link to your repository or your pull request in the field below. + +
+ +## Instructions + +1. Create a `Person` class that has the following properties: + + - `id`: an integer + - `name`: a string formatted as "firstName lastName" + - `age`: an integer + - `occupation`: a string + + The `Person` class should have the following methods: + + - A constructor that takes in an integer `id`, a string `name`, an integer `age` and a string `occupation` as arguments and sets their respective properties. + - A `setAge` method that takes in an integer `age` and sets the `age` property, but throws an error if `age` is less than 0. + - An `equals` method that takes in a `Person` object and returns `true` if their properties are the same, excluding the `id` property. + +2. Create a `PersonsList` class that holds a list of `Person` objects. + - Create a `findByName` method that takes in a string `name` and returns the `Person` object with a name that matches exactly. The `name` parameter should be formatted as "firstName lastName". This method should throw an exception if the `name` parameter is not properly formatted. + - Create a `clone` method that takes in a `Person` object and returns a new `Person` object with the same properties, except with a new `id`. + - Create a method that takes in a `Person` object as a parameter and uses the `toString` method to write the `Person` information to a file. This method should handle any errors as necessary. + +
+ +## Test Cases + +1. Test the `setAge` method to ensure that it throws an error if the age is less than 0. +2. Test the `findByName` method to ensure that it properly finds and returns the correct `Person` object when given a properly formatted name. +3. Test the `findByName` method to ensure that it throws an exception if the `name` parameter is not properly formatted. +4. Test the `clone` method to ensure that it creates a new `Person` object with the same properties as the original, except with a new `id`. + +
+ +## FAQs + +
+ +
+ I am stuck and don't know how to solve the problem or where to start. What should I do? + +
+ + If you are stuck in your code and don't know how to solve the problem or where to start, you should take a step back and try to form a clear, straight forward question about the specific issue you are facing. The process you will go through while trying to define this question, will help you narrow down the problem and come up with potential solutions. + + For example, are you facing a problem because you don't understand the concept or are you receiving an error message that you don't know how to fix? It is usually helpful to try to state the problem as clearly as possible, including any error messages you are receiving. This can help you communicate the issue to others and potentially get help from classmates or online resources. + + Once you have a clear understanding of the problem, you should be able to start working toward the solution. + +
+ +
+ +
+ How do I create a Maven project in IntelliJ? + +
+ + To create a Maven project in IntelliJ, you can follow these steps: + + 1. Open IntelliJ IDEA and click the "Create New Project" button. + 2. In the "New Project" dialog, select "Maven" as the build system. + 3. Specify the name of the project. + 4. In the "Project Location" section, specify a location where you want to save your project. + 5. Select the "Create Git repository" checkbox in order to initialize the git repository upon creation of the project. + 6. Click the "Create" button to create the Maven project. + +
+ + + +
+ +
+ +
+ What is the purpose of the "toString()" method and how can I override it in Java? + +
+ + The `toString()` method in Java is a method that is automatically called when an object is passed as a string. The purpose of this method is to return a string representation of an object. By default, the `toString()` method returns the name of the object's class and its memory address. + + It is a good practice to override the `toString()` method in your own classes to provide a meaningful string representation of your objects. This can be useful for debugging and logging purposes. + + Here is an example of how to override the `toString()` method in Java: + + ```java + class Circle { + int x, y; + int radius; + + public String toString() { + return "Circle [x=" + x + ", y=" + y + ", radius=" + radius + "]"; + } + } + ``` + + In this example, the `Circle` class overrides the `toString()` method to return a string representation of the `Circle` object. When an object of the `Circle` class is passed as a string, this custom implementation of `toString()` will be called and will return the desired string representation. + + It is important to note that the `toString()` method should return a concise, human-readable string representation of the object, as it is commonly used for debugging and logging purposes. + +
+ + + +
+ +
+ +
+ What is the purpose of using the "throws" keyword in Java and when should I use it? + +
+ + The `throws` keyword in Java is used to declare that a method may throw an exception. The purpose of using the `throws` keyword is to indicate that an exception may be thrown and it requires the calling method to handle the exception. If a method declares that it throws an exception, the calling method must either handle the exception using a try-catch block or declare that it also throws the same exception. + + Here's an example of how you can use the `throws` keyword in a method: + + ```java + public void readFile(String fileName) throws FileNotFoundException { + File file = new File(fileName); + Scanner scanner = new Scanner(file); + // code to read the file + scanner.close(); + } + ``` + + In this example, the `readFile()` method declares that it throws a `FileNotFoundException`. If the file specified in the `fileName` argument does not exist, a `FileNotFoundException` will be thrown and the calling method must handle it. + + You should use the `throws` keyword when a method can potentially throw an exception that it cannot handle itself. In such cases, it is the responsibility of the calling method to handle the exception. The use of the `throws` keyword allows for proper error handling and prevents the code from crashing due to unhandled exceptions. + +
+ + + +
+ +
+ +
+ What is the purpose of using "throw new" in Java and when should it be used? + +
+ + The `throw new` keyword in Java is used to throw a custom exception. The purpose of using the `throw new` keyword is to raise an exception in the code and halt the execution of the program. This is useful in cases where the code encounters an exceptional condition that cannot be handled within the method and requires the calling method to handle the exception. + + Here's an example of how you can use the `throw new` keyword in a method: + + ```java + public void divide(int a, int b) throws ArithmeticException { + if (b == 0) { + throw new ArithmeticException("Cannot divide by zero"); + } + int result = a / b; + System.out.println("Result: " + result); + } + ``` + + In this example, the `divide()` method checks if the denominator `b` is equal to zero. If it is, the method throws a custom `ArithmeticException` with a message indicating that dividing by zero is not allowed. The calling method must handle the exception or declare that it also throws the same exception. + + You should use the `throw new` keyword when you encounter an exceptional condition in your code that cannot be handled within the method. This allows the calling method to handle the exception and prevent the program from crashing due to unhandled exceptions. + +
+ + + +
+ +
+ +
+ How can I use the "File" and "FileWriter" classes in Java to write to a file? + +
+ + To write to a file in Java, you can use the `File` and `FileWriter` classes. The `File` class is used to create a file or directory in the file system, while the `FileWriter` class is used to write characters to the file. + + Here's an example of how you can use these classes to write to a file: + + ```java + import java.io.File; + import java.io.FileWriter; + import java.io.IOException; + + public class FileExample { + public static void main(String[] args) { + try { + // Create a new file object + File file = new File("example.txt"); + + // Create a new FileWriter object to write to the file + FileWriter writer = new FileWriter(file); + + // Write some text to the file + writer.write("This is an example of writing to a file in Java."); + + // Close the writer to save the changes + writer.close(); + + System.out.println("File written successfully"); + } catch (IOException e) { + System.out.println("An error occurred while writing to the file: " + e.getMessage()); + } + } + } + ``` + + In this example, a new `File` object is created with the name `example.txt`. A `FileWriter` object is then created, passing the `File` object as a parameter. The `write()` method is used to write the text to the file and the `close()` method is called to save the changes. + + Note that when using `FileWriter`, the file is created if it doesn't already exist and any existing content in the file is overwritten. If you want to append to an existing file instead of overwriting it, you can use the `FileWriter` constructor that takes two parameters, the second being a `boolean` that indicates whether to append to the file or not. + + ```java + FileWriter writer = new FileWriter(file, true); + ``` + + It's important to catch any `IOException` that may be thrown when writing to a file, as this indicates that an error occurred while performing the operation. In this example, the error message is printed to the console. + +
+ + + +
+ +
+ +
+ What is the use of "assertThrows" in JUnit and how can I use it to test exceptions in Java? + +
+ + The `assertThrows` method in JUnit is used to test if a certain exception is thrown by a specific piece of code. It allows you to ensure that your code behaves correctly when an exception occurs. + + Here's an example of how you can use `assertThrows` in JUnit: + + ```java + @Test + public void testException() { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { + // Code that should throw the exception + }); + assertEquals("Exception message", exception.getMessage()); + } + ``` + + In the example above, we are testing if the code inside the lambda expression throws an `IllegalArgumentException`. If the code does throw the exception, it will be caught and stored in the `exception` variable. Then, we can use `assertEquals` to check that the exception message is correct. + + **Note**: The `assertThrows` method is available in JUnit 5 and later versions. + +
+ + + +
+ +
+ +
+ I am unable to push changes to my repository. What should I do? + +
+ + If you are unable to push changes to your repository, here are a few steps that you can follow: + + 1. Check your internet connection: Ensure that your internet connection is stable and working. + 1. Verify your repository URL: Make sure that you are using the correct repository URL to push your changes. + 2. Check Git credentials: Ensure that your Git credentials are up-to-date and correct. You can check your credentials using the following command: + + ```bash + git config --list + ``` + + 4. Update your local repository: Before pushing changes, make sure that your local repository is up-to-date with the remote repository. You can update your local repository using the following command: + + ```bash + git fetch origin + ``` + + 5. Check for conflicts: If there are any conflicts between your local repository and the remote repository, resolve them before pushing changes. + 6. Push changes: Once you have resolved any conflicts and updated your local repository, you can try pushing changes again using the following command: + + ```bash + git push origin + ``` + +
+ + diff --git a/out/production/lab-java-exceptions/labjavaexceptions/Main.class b/out/production/lab-java-exceptions/labjavaexceptions/Main.class new file mode 100644 index 0000000000000000000000000000000000000000..4849ccdeb23c7ce699a11d45abf1398156b926e8 GIT binary patch literal 2398 zcmaJ@T~`xV6y28q6Jih?@BiOgeL;^3tdN zfWEa)wr_p554aYt)gREm)V12~nE`<&z*^j4&fRC9bM`&=41fKz`zL^Vc%DEDVg_21 zXhXX|_fz>yW^L(|vky0(s-hNXziT;`o)n0sGiwIo0vBw#5#ZE|qN-`jb^PqI@_g5c zBOwr9aJQV)jH}{E@@>{BTaHp*0tQY8QMv>&>G}LYpn~=+r<`kI3gVp+xN?AjIZg!bLHA5>|%_Y!{z9cT< zl0c%Y^rG^8SylqQ=}cpyCY9??VgQ2z=c}@!rd_8f^}40E_?NGxqkVyqbfaezvIO42 z6$4k37{ahXPgv^F^aPArkgV-6|7NUI>0N>T<4(oTTfRS?nRH{&Ax^Z0N z`OdgS?ecs^FrGvf?+J9sQYku7(x&sr5$7^%f!EC>-p4HxZ(2_2{`QirQn~SFi5|~n zLg03w>4%}~@evzEHQB-aaol0rL1kfKCSvFha=VwrBt8~sE84EZv~HhN%}MFC;&vSO zS!6Bj^l|+nlyoMESc-lbQZKMRu*L~RKvhJPrTsPy`qZFv?I`9Jh-GB zGWT6q``VMWMWwgglHb*ijRcA)8BjqlZ&HVY(PcT$+=|LZ(=Hkrb27Mj+XBBFzAbye zi1dMUO1AQc@~&H{*K&ts-5Z;SEJqwyw`-~i{IGn{gwGwGN_!O3(zXk1=v*9I96G+z zQ)P9u5k(wN1^N!|e8aZgWP4MxUD?L;W@oZ__a{bb)Ag!SH;~jggu^5H-wsc1-f@&S zZ3h>_H^AN)ZVh7hi(Hct084ntw+<}h5iN8UFNtfV?YB2D9=Dnu-G7^>UZXSrJ9_eez#QAbg{-mI9ZZwa{FK38u@ayQCclr9%zl;65-M=`j3KCZ4QII;#3YD{^DEqe zE9k^1PGf@BNm^%VeZ=qbDthrb@g?+;<1$$;!o?;0fI<9-6n?^0{LIhbuNV&XTM7BP zuz~`0o28zs^pEj3vc>4V{};7nF6+!?6wmMl9@Aq2Wqe6=3)wH@N$C3(5h=8<80hZ$ z7dL``eZDp@Vz2}e*ye+UF}@+L1>fSk5Z?w#zH+!);aUmTYPh=io~Q&79yFu({Rfl% Bd}sgw literal 0 HcmV?d00001 diff --git a/out/production/lab-java-exceptions/labjavaexceptions/Person.class b/out/production/lab-java-exceptions/labjavaexceptions/Person.class new file mode 100644 index 0000000000000000000000000000000000000000..f67af66d5692dff8eab355e72c9d2d1452855a54 GIT binary patch literal 2030 zcma)7TW=dh6#gc@tmCYmHnpADA&CiT<6G)-FL6_vnwq*eNg-7bARfl{$k}AGYrNx% z3L)_`5JKV!9#9@YYEr34z!MMrCWJV%yK$VvARcz-vgbSJJLh~e`{&=!e+96H526@D zKtoVR2w{dxd;Bpko80P@x0-vRB^koE49k$W83MWd&Nw0%*AUe)0i9vSABvu1TMT1Hn}O98Ag*H)ml%Q;KM)L4jng38vS(PGN|daobX-A#;yFUDcgQZ7 zt9t=cI;IsqYPVYbE?03hq!|`Z{nSlUbhx?R>+}zVCGVZ^iC~r?P42QSZdta>HbvGH zj+2$U+{)gFVg_?6^?8P5?jkQQepbheD%$|>2vx6_bS&X2L!={Q)#Q%Da3z-?Lc5!k z)G~4!@;VAAo++)DHKi&(>vNOfXJUJWujD_Tq86>_xQ;Tz^a0-&RoiND`Jo|qY34|7 zNy4t?>O-OZf{xf4Cg@u+thx$>q+tilHhGB`#{y|gp9`UB>Hq>r$bBFf~we~lI za@Qbsna00Kq{0x}mb|sU!Mi>tLqEi=FrX= z;G-v9F~a#Vg`;7U;p&AljLJ^KLx%bPHl;3krJ!RMq4Nd==}i|7&BoMK;*NAA-I1;a z8Y5tIjBn8UWm zh|xt9N17tNN?%^{Jkj_%t(3iD!rYnSqWERh1%ZG&Q+$H-oh~z<&8PH5StVw_MeG;M zd^DALh8KQQycQIX02GfYLV-|0!o`uI*|Zx!~3aUe;)Uc?~mavtd0Q3emV!99|^9EjJ$9@^5RJFt&x$F=ObSm38p*M zr~M-(sY+if6n{V{cv$=c@xn0{i}ZYtP~fomJ0crYkXVVHV_f@2ZPI#y)(hYHizF?Q z^ifgw8sZ6~1Pv?nn1cXtzm7KUN-?zueYoadbP?4SSs_B(*{_#uf1T2v?+ zqKFB!-_sxJIZLmUbJL6WjFKl1J7-o*?}9)}rhiUFT%gl8s(GfBn{*s~t!TPl5-M5} zXoaStO~W4S73j6}MQLh0E*VwNv@34zy5YF|l^z0WHF#s#;u}b*n`p&8bg1amupb8m z_H0)(7kz0-;6NtuYsz<`e<6;8%<;;ff5_M$vSsRIBQ8=%nToN#~~m{h313#Du~BN7V0A{F#Q& zWeCMJpBO5x)wwh6+*Q*uZa9+qB#JmDV_etpg^V8e>;PD5W;D#oK1Lr&V=0-_a6{g- zXvwl&qR!XvlTYmIieo?07cH9J#4Qb9<2LKzu+P-0RmX5$gA}Bi$G+h)A#dk5bu{K! zm~PBt5_h0$Sd@YHRyph5jHj3G&pLX^AiXnYxuSbDhv%WD36eMQTydxNPF$EEHJ9uq zdhIQm6=SNlx@b7FGJ7&rv`e}*r#q&64~2@iV)AbF?TG0w2Ery-aj+`5MKU{@vt$lH zutfxVcD55pE}NC5{F=OJ0>jM&)-U&N-b%&y>v(r~*d3qBYkD;-QZ}~2AY;4by<4z- z{;UM$&)Ra*1aiB8y_=Lzi;u#sus_gm8(LB!#gl$@NgYfi}svS<&I z^1C!F*9eaAmPYs`5qxsz^S8ve2$m4znV%Fs4NCH8;R$FT*nk+=f;zu}#IH!c@U55m z+(QcxO@T(7HkA3M1wL4T$v1&}xF6zOW(*lu8~6pu!A-PBaN`Y@{HTFDvK1XZPFG+X z;z(Qzt3(p0zzz|AVtj>O`N58^b)Oqo;^wpFey3mv~N;7RZ_o^P>oKA%TPF)a}j7;bv|1WLe zs!S*1rz4vI9BZN^)d-dfDT&C98zPVSkwTI;QQ&pI`}139nWjc*jYie*FvNJpqGI$J z+d^@EXaiGIS>`ppjxWjESI>|dSAv5!9_?1Tqw84cR$e|sT=IJN1-%n&WQyCchlCyB zFZdZ7;XVr}K8m<6Nnn_EIa+4-M|e!nlWg@Gp76xX8XSy; z97x%>q(0(PKaSXI!YV3SRg9|WR=LH6ikq()I@&Cy%vZ$!MkKG|jzSK;V}uC4{}0Sh BFAx9# literal 0 HcmV?d00001 diff --git a/out/production/lab-java-exceptions/src/README.md b/out/production/lab-java-exceptions/src/README.md new file mode 100644 index 0000000..d76a5ac --- /dev/null +++ b/out/production/lab-java-exceptions/src/README.md @@ -0,0 +1,309 @@ +![logo_ironhack_blue 7](https://user-images.githubusercontent.com/23629340/40541063-a07a0a8a-601a-11e8-91b5-2f13e4e6b441.png) + +# LAB Java | Exceptions + + + +## Introduction + +We have just learned how to throw, handle and test exceptions so let's practice a bit more. + +
+ +## Requirements + +1. Fork this repo. +2. Clone this repo. +3. Add your instructor and the class graders as collaborators to your repository. If you are unsure who your class graders are, ask your instructor or refer to the day 1 slide deck. +4. In the repository, create a Java project and add the code for the following prompts. + +## Submission + +Once you finish the assignment, submit a URL link to your repository or your pull request in the field below. + +
+ +## Instructions + +1. Create a `Person` class that has the following properties: + + - `id`: an integer + - `name`: a string formatted as "firstName lastName" + - `age`: an integer + - `occupation`: a string + + The `Person` class should have the following methods: + + - A constructor that takes in an integer `id`, a string `name`, an integer `age` and a string `occupation` as arguments and sets their respective properties. + - A `setAge` method that takes in an integer `age` and sets the `age` property, but throws an error if `age` is less than 0. + - An `equals` method that takes in a `Person` object and returns `true` if their properties are the same, excluding the `id` property. + +2. Create a `PersonsList` class that holds a list of `Person` objects. + - Create a `findByName` method that takes in a string `name` and returns the `Person` object with a name that matches exactly. The `name` parameter should be formatted as "firstName lastName". This method should throw an exception if the `name` parameter is not properly formatted. + - Create a `clone` method that takes in a `Person` object and returns a new `Person` object with the same properties, except with a new `id`. + - Create a method that takes in a `Person` object as a parameter and uses the `toString` method to write the `Person` information to a file. This method should handle any errors as necessary. + +
+ +## Test Cases + +1. Test the `setAge` method to ensure that it throws an error if the age is less than 0. +2. Test the `findByName` method to ensure that it properly finds and returns the correct `Person` object when given a properly formatted name. +3. Test the `findByName` method to ensure that it throws an exception if the `name` parameter is not properly formatted. +4. Test the `clone` method to ensure that it creates a new `Person` object with the same properties as the original, except with a new `id`. + +
+ +## FAQs + +
+ +
+ I am stuck and don't know how to solve the problem or where to start. What should I do? + +
+ + If you are stuck in your code and don't know how to solve the problem or where to start, you should take a step back and try to form a clear, straight forward question about the specific issue you are facing. The process you will go through while trying to define this question, will help you narrow down the problem and come up with potential solutions. + + For example, are you facing a problem because you don't understand the concept or are you receiving an error message that you don't know how to fix? It is usually helpful to try to state the problem as clearly as possible, including any error messages you are receiving. This can help you communicate the issue to others and potentially get help from classmates or online resources. + + Once you have a clear understanding of the problem, you should be able to start working toward the solution. + +
+ +
+ +
+ How do I create a Maven project in IntelliJ? + +
+ + To create a Maven project in IntelliJ, you can follow these steps: + + 1. Open IntelliJ IDEA and click the "Create New Project" button. + 2. In the "New Project" dialog, select "Maven" as the build system. + 3. Specify the name of the project. + 4. In the "Project Location" section, specify a location where you want to save your project. + 5. Select the "Create Git repository" checkbox in order to initialize the git repository upon creation of the project. + 6. Click the "Create" button to create the Maven project. + +
+ + + +
+ +
+ +
+ What is the purpose of the "toString()" method and how can I override it in Java? + +
+ + The `toString()` method in Java is a method that is automatically called when an object is passed as a string. The purpose of this method is to return a string representation of an object. By default, the `toString()` method returns the name of the object's class and its memory address. + + It is a good practice to override the `toString()` method in your own classes to provide a meaningful string representation of your objects. This can be useful for debugging and logging purposes. + + Here is an example of how to override the `toString()` method in Java: + + ```java + class Circle { + int x, y; + int radius; + + public String toString() { + return "Circle [x=" + x + ", y=" + y + ", radius=" + radius + "]"; + } + } + ``` + + In this example, the `Circle` class overrides the `toString()` method to return a string representation of the `Circle` object. When an object of the `Circle` class is passed as a string, this custom implementation of `toString()` will be called and will return the desired string representation. + + It is important to note that the `toString()` method should return a concise, human-readable string representation of the object, as it is commonly used for debugging and logging purposes. + +
+ + + +
+ +
+ +
+ What is the purpose of using the "throws" keyword in Java and when should I use it? + +
+ + The `throws` keyword in Java is used to declare that a method may throw an exception. The purpose of using the `throws` keyword is to indicate that an exception may be thrown and it requires the calling method to handle the exception. If a method declares that it throws an exception, the calling method must either handle the exception using a try-catch block or declare that it also throws the same exception. + + Here's an example of how you can use the `throws` keyword in a method: + + ```java + public void readFile(String fileName) throws FileNotFoundException { + File file = new File(fileName); + Scanner scanner = new Scanner(file); + // code to read the file + scanner.close(); + } + ``` + + In this example, the `readFile()` method declares that it throws a `FileNotFoundException`. If the file specified in the `fileName` argument does not exist, a `FileNotFoundException` will be thrown and the calling method must handle it. + + You should use the `throws` keyword when a method can potentially throw an exception that it cannot handle itself. In such cases, it is the responsibility of the calling method to handle the exception. The use of the `throws` keyword allows for proper error handling and prevents the code from crashing due to unhandled exceptions. + +
+ + + +
+ +
+ +
+ What is the purpose of using "throw new" in Java and when should it be used? + +
+ + The `throw new` keyword in Java is used to throw a custom exception. The purpose of using the `throw new` keyword is to raise an exception in the code and halt the execution of the program. This is useful in cases where the code encounters an exceptional condition that cannot be handled within the method and requires the calling method to handle the exception. + + Here's an example of how you can use the `throw new` keyword in a method: + + ```java + public void divide(int a, int b) throws ArithmeticException { + if (b == 0) { + throw new ArithmeticException("Cannot divide by zero"); + } + int result = a / b; + System.out.println("Result: " + result); + } + ``` + + In this example, the `divide()` method checks if the denominator `b` is equal to zero. If it is, the method throws a custom `ArithmeticException` with a message indicating that dividing by zero is not allowed. The calling method must handle the exception or declare that it also throws the same exception. + + You should use the `throw new` keyword when you encounter an exceptional condition in your code that cannot be handled within the method. This allows the calling method to handle the exception and prevent the program from crashing due to unhandled exceptions. + +
+ + + +
+ +
+ +
+ How can I use the "File" and "FileWriter" classes in Java to write to a file? + +
+ + To write to a file in Java, you can use the `File` and `FileWriter` classes. The `File` class is used to create a file or directory in the file system, while the `FileWriter` class is used to write characters to the file. + + Here's an example of how you can use these classes to write to a file: + + ```java + import java.io.File; + import java.io.FileWriter; + import java.io.IOException; + + public class FileExample { + public static void main(String[] args) { + try { + // Create a new file object + File file = new File("example.txt"); + + // Create a new FileWriter object to write to the file + FileWriter writer = new FileWriter(file); + + // Write some text to the file + writer.write("This is an example of writing to a file in Java."); + + // Close the writer to save the changes + writer.close(); + + System.out.println("File written successfully"); + } catch (IOException e) { + System.out.println("An error occurred while writing to the file: " + e.getMessage()); + } + } + } + ``` + + In this example, a new `File` object is created with the name `example.txt`. A `FileWriter` object is then created, passing the `File` object as a parameter. The `write()` method is used to write the text to the file and the `close()` method is called to save the changes. + + Note that when using `FileWriter`, the file is created if it doesn't already exist and any existing content in the file is overwritten. If you want to append to an existing file instead of overwriting it, you can use the `FileWriter` constructor that takes two parameters, the second being a `boolean` that indicates whether to append to the file or not. + + ```java + FileWriter writer = new FileWriter(file, true); + ``` + + It's important to catch any `IOException` that may be thrown when writing to a file, as this indicates that an error occurred while performing the operation. In this example, the error message is printed to the console. + +
+ + + +
+ +
+ +
+ What is the use of "assertThrows" in JUnit and how can I use it to test exceptions in Java? + +
+ + The `assertThrows` method in JUnit is used to test if a certain exception is thrown by a specific piece of code. It allows you to ensure that your code behaves correctly when an exception occurs. + + Here's an example of how you can use `assertThrows` in JUnit: + + ```java + @Test + public void testException() { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { + // Code that should throw the exception + }); + assertEquals("Exception message", exception.getMessage()); + } + ``` + + In the example above, we are testing if the code inside the lambda expression throws an `IllegalArgumentException`. If the code does throw the exception, it will be caught and stored in the `exception` variable. Then, we can use `assertEquals` to check that the exception message is correct. + + **Note**: The `assertThrows` method is available in JUnit 5 and later versions. + +
+ + + +
+ +
+ +
+ I am unable to push changes to my repository. What should I do? + +
+ + If you are unable to push changes to your repository, here are a few steps that you can follow: + + 1. Check your internet connection: Ensure that your internet connection is stable and working. + 1. Verify your repository URL: Make sure that you are using the correct repository URL to push your changes. + 2. Check Git credentials: Ensure that your Git credentials are up-to-date and correct. You can check your credentials using the following command: + + ```bash + git config --list + ``` + + 4. Update your local repository: Before pushing changes, make sure that your local repository is up-to-date with the remote repository. You can update your local repository using the following command: + + ```bash + git fetch origin + ``` + + 5. Check for conflicts: If there are any conflicts between your local repository and the remote repository, resolve them before pushing changes. + 6. Push changes: Once you have resolved any conflicts and updated your local repository, you can try pushing changes again using the following command: + + ```bash + git push origin + ``` + +
+ + diff --git a/person.txt b/person.txt new file mode 100644 index 0000000..1cc5e8e --- /dev/null +++ b/person.txt @@ -0,0 +1 @@ +Person{id=2, name='Jane Smith', age=30, occupation='Doctor'} \ No newline at end of file diff --git a/src/.DS_Store b/src/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..085921badd374677555b0328b687271ceb219728 GIT binary patch literal 6148 zcmeHKO>Yx15FMw1?y5ox5=cE-;=&<7Xdwu3Swec?z@>}e04VHsSFo^MN7+q-6h+!I z{2_h`e})6Rv0b19q+W^u%}C=nwr9rjv*iyWQloixlc+~T0hF;5qWFbyKkJ%wd`lOo zY>tGED50F*(ZQOxH2jSW@Y-FZ604Td8W8H{NK2E#o43j#^y(KY zuuhdBUDQ*b;bS^2i@F&MKB>+|_uTo-U^CbXUc|4>B5smqUXPO5Gp;>0rc96RBz;ok zi%IX&15-6gQROomP-Hn=ompL4<1nT{gKg#lsUUu1yK2MuM6Jhl$)(SgE# z0f79Bv;vzSh#aFmMjl&-=z%B~3Ur~$e=(E`N4xfZk;m4d3n%42AIguc{0~Lh(UD(U zcT$l + +## Requirements + +1. Fork this repo. +2. Clone this repo. +3. Add your instructor and the class graders as collaborators to your repository. If you are unsure who your class graders are, ask your instructor or refer to the day 1 slide deck. +4. In the repository, create a Java project and add the code for the following prompts. + +## Submission + +Once you finish the assignment, submit a URL link to your repository or your pull request in the field below. + +
+ +## Instructions + +1. Create a `Person` class that has the following properties: + + - `id`: an integer + - `name`: a string formatted as "firstName lastName" + - `age`: an integer + - `occupation`: a string + + The `Person` class should have the following methods: + + - A constructor that takes in an integer `id`, a string `name`, an integer `age` and a string `occupation` as arguments and sets their respective properties. + - A `setAge` method that takes in an integer `age` and sets the `age` property, but throws an error if `age` is less than 0. + - An `equals` method that takes in a `Person` object and returns `true` if their properties are the same, excluding the `id` property. + +2. Create a `PersonsList` class that holds a list of `Person` objects. + - Create a `findByName` method that takes in a string `name` and returns the `Person` object with a name that matches exactly. The `name` parameter should be formatted as "firstName lastName". This method should throw an exception if the `name` parameter is not properly formatted. + - Create a `clone` method that takes in a `Person` object and returns a new `Person` object with the same properties, except with a new `id`. + - Create a method that takes in a `Person` object as a parameter and uses the `toString` method to write the `Person` information to a file. This method should handle any errors as necessary. + +
+ +## Test Cases + +1. Test the `setAge` method to ensure that it throws an error if the age is less than 0. +2. Test the `findByName` method to ensure that it properly finds and returns the correct `Person` object when given a properly formatted name. +3. Test the `findByName` method to ensure that it throws an exception if the `name` parameter is not properly formatted. +4. Test the `clone` method to ensure that it creates a new `Person` object with the same properties as the original, except with a new `id`. + +
+ +## FAQs + +
+ +
+ I am stuck and don't know how to solve the problem or where to start. What should I do? + +
+ + If you are stuck in your code and don't know how to solve the problem or where to start, you should take a step back and try to form a clear, straight forward question about the specific issue you are facing. The process you will go through while trying to define this question, will help you narrow down the problem and come up with potential solutions. + + For example, are you facing a problem because you don't understand the concept or are you receiving an error message that you don't know how to fix? It is usually helpful to try to state the problem as clearly as possible, including any error messages you are receiving. This can help you communicate the issue to others and potentially get help from classmates or online resources. + + Once you have a clear understanding of the problem, you should be able to start working toward the solution. + +
+ +
+ +
+ How do I create a Maven project in IntelliJ? + +
+ + To create a Maven project in IntelliJ, you can follow these steps: + + 1. Open IntelliJ IDEA and click the "Create New Project" button. + 2. In the "New Project" dialog, select "Maven" as the build system. + 3. Specify the name of the project. + 4. In the "Project Location" section, specify a location where you want to save your project. + 5. Select the "Create Git repository" checkbox in order to initialize the git repository upon creation of the project. + 6. Click the "Create" button to create the Maven project. + +
+ + + +
+ +
+ +
+ What is the purpose of the "toString()" method and how can I override it in Java? + +
+ + The `toString()` method in Java is a method that is automatically called when an object is passed as a string. The purpose of this method is to return a string representation of an object. By default, the `toString()` method returns the name of the object's class and its memory address. + + It is a good practice to override the `toString()` method in your own classes to provide a meaningful string representation of your objects. This can be useful for debugging and logging purposes. + + Here is an example of how to override the `toString()` method in Java: + + ```java + class Circle { + int x, y; + int radius; + + public String toString() { + return "Circle [x=" + x + ", y=" + y + ", radius=" + radius + "]"; + } + } + ``` + + In this example, the `Circle` class overrides the `toString()` method to return a string representation of the `Circle` object. When an object of the `Circle` class is passed as a string, this custom implementation of `toString()` will be called and will return the desired string representation. + + It is important to note that the `toString()` method should return a concise, human-readable string representation of the object, as it is commonly used for debugging and logging purposes. + +
+ + + +
+ +
+ +
+ What is the purpose of using the "throws" keyword in Java and when should I use it? + +
+ + The `throws` keyword in Java is used to declare that a method may throw an exception. The purpose of using the `throws` keyword is to indicate that an exception may be thrown and it requires the calling method to handle the exception. If a method declares that it throws an exception, the calling method must either handle the exception using a try-catch block or declare that it also throws the same exception. + + Here's an example of how you can use the `throws` keyword in a method: + + ```java + public void readFile(String fileName) throws FileNotFoundException { + File file = new File(fileName); + Scanner scanner = new Scanner(file); + // code to read the file + scanner.close(); + } + ``` + + In this example, the `readFile()` method declares that it throws a `FileNotFoundException`. If the file specified in the `fileName` argument does not exist, a `FileNotFoundException` will be thrown and the calling method must handle it. + + You should use the `throws` keyword when a method can potentially throw an exception that it cannot handle itself. In such cases, it is the responsibility of the calling method to handle the exception. The use of the `throws` keyword allows for proper error handling and prevents the code from crashing due to unhandled exceptions. + +
+ + + +
+ +
+ +
+ What is the purpose of using "throw new" in Java and when should it be used? + +
+ + The `throw new` keyword in Java is used to throw a custom exception. The purpose of using the `throw new` keyword is to raise an exception in the code and halt the execution of the program. This is useful in cases where the code encounters an exceptional condition that cannot be handled within the method and requires the calling method to handle the exception. + + Here's an example of how you can use the `throw new` keyword in a method: + + ```java + public void divide(int a, int b) throws ArithmeticException { + if (b == 0) { + throw new ArithmeticException("Cannot divide by zero"); + } + int result = a / b; + System.out.println("Result: " + result); + } + ``` + + In this example, the `divide()` method checks if the denominator `b` is equal to zero. If it is, the method throws a custom `ArithmeticException` with a message indicating that dividing by zero is not allowed. The calling method must handle the exception or declare that it also throws the same exception. + + You should use the `throw new` keyword when you encounter an exceptional condition in your code that cannot be handled within the method. This allows the calling method to handle the exception and prevent the program from crashing due to unhandled exceptions. + +
+ + + +
+ +
+ +
+ How can I use the "File" and "FileWriter" classes in Java to write to a file? + +
+ + To write to a file in Java, you can use the `File` and `FileWriter` classes. The `File` class is used to create a file or directory in the file system, while the `FileWriter` class is used to write characters to the file. + + Here's an example of how you can use these classes to write to a file: + + ```java + import java.io.File; + import java.io.FileWriter; + import java.io.IOException; + + public class FileExample { + public static void main(String[] args) { + try { + // Create a new file object + File file = new File("example.txt"); + + // Create a new FileWriter object to write to the file + FileWriter writer = new FileWriter(file); + + // Write some text to the file + writer.write("This is an example of writing to a file in Java."); + + // Close the writer to save the changes + writer.close(); + + System.out.println("File written successfully"); + } catch (IOException e) { + System.out.println("An error occurred while writing to the file: " + e.getMessage()); + } + } + } + ``` + + In this example, a new `File` object is created with the name `example.txt`. A `FileWriter` object is then created, passing the `File` object as a parameter. The `write()` method is used to write the text to the file and the `close()` method is called to save the changes. + + Note that when using `FileWriter`, the file is created if it doesn't already exist and any existing content in the file is overwritten. If you want to append to an existing file instead of overwriting it, you can use the `FileWriter` constructor that takes two parameters, the second being a `boolean` that indicates whether to append to the file or not. + + ```java + FileWriter writer = new FileWriter(file, true); + ``` + + It's important to catch any `IOException` that may be thrown when writing to a file, as this indicates that an error occurred while performing the operation. In this example, the error message is printed to the console. + +
+ + + +
+ +
+ +
+ What is the use of "assertThrows" in JUnit and how can I use it to test exceptions in Java? + +
+ + The `assertThrows` method in JUnit is used to test if a certain exception is thrown by a specific piece of code. It allows you to ensure that your code behaves correctly when an exception occurs. + + Here's an example of how you can use `assertThrows` in JUnit: + + ```java + @Test + public void testException() { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { + // Code that should throw the exception + }); + assertEquals("Exception message", exception.getMessage()); + } + ``` + + In the example above, we are testing if the code inside the lambda expression throws an `IllegalArgumentException`. If the code does throw the exception, it will be caught and stored in the `exception` variable. Then, we can use `assertEquals` to check that the exception message is correct. + + **Note**: The `assertThrows` method is available in JUnit 5 and later versions. + +
+ + + +
+ +
+ +
+ I am unable to push changes to my repository. What should I do? + +
+ + If you are unable to push changes to your repository, here are a few steps that you can follow: + + 1. Check your internet connection: Ensure that your internet connection is stable and working. + 1. Verify your repository URL: Make sure that you are using the correct repository URL to push your changes. + 2. Check Git credentials: Ensure that your Git credentials are up-to-date and correct. You can check your credentials using the following command: + + ```bash + git config --list + ``` + + 4. Update your local repository: Before pushing changes, make sure that your local repository is up-to-date with the remote repository. You can update your local repository using the following command: + + ```bash + git fetch origin + ``` + + 5. Check for conflicts: If there are any conflicts between your local repository and the remote repository, resolve them before pushing changes. + 6. Push changes: Once you have resolved any conflicts and updated your local repository, you can try pushing changes again using the following command: + + ```bash + git push origin + ``` + +
+ + diff --git a/src/labjavaexceptions/.DS_Store b/src/labjavaexceptions/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..85ea1dd8a588072aef9a36d9ad1fd57d62322b14 GIT binary patch literal 6148 zcmeHK%}N774E|DksPwW&kMjft-(V^2K~NBU0b3POiVJS_ymueQN7OGrid(lQK|~VB zeCZ^a%zn_B2>_WtT^|D#fC*Jm)EE$*9(0W&_<$(3#tipZ;Tfxw&A>u`aZ2}oh%@f` z4iEUU|K@7FY1Z^AHLuj!n+YvoigVoH5iOeiS@N=zRrRu3oU&$%?Y^p`+ns!^oRSPA z1Ia)#kPQ5k0p8gvlc{5l$v`rY416-6=R=_?)`6X)9UUC31t5+&Z9-cg%$idI>%h*D z9*TG>(NiT_4Doc%mx!waJ4a84MDrn0`J;IetIqX{g+pq`9Fu`$pwEEzzLZMu|0Vx2 zgH67L3;=@7hAWq^f9Krv`;~?-9TsdX5~K)BQzl#?^tH VqpqU!mQKuvfDw{IGVluwyaVeQIIjQz literal 0 HcmV?d00001 diff --git a/src/labjavaexceptions/Main.java b/src/labjavaexceptions/Main.java new file mode 100644 index 0000000..a35935f --- /dev/null +++ b/src/labjavaexceptions/Main.java @@ -0,0 +1,38 @@ +package labjavaexceptions; + +public class Main { + public static void main(String[] args) { + // Test setAge method + try { + Person person1 = new Person(1, "John Doe", -5, "Engineer"); + } catch (IllegalArgumentException e) { + System.out.println("setAge test passed: " + e.getMessage()); + } + + // Test findByName method + PersonsList personsList = new PersonsList(); + Person person2 = new Person(2, "Jane Smith", 30, "Doctor"); + personsList.addPerson(person2); + + try { + Person foundPerson = personsList.findByName("Jane Smith"); + System.out.println("findByName test passed: " + foundPerson); + } catch (IllegalArgumentException e) { + System.out.println("findByName test failed: " + e.getMessage()); + } + + try { + personsList.findByName("JaneSmith"); // Incorrect format + } catch (IllegalArgumentException e) { + System.out.println("findByName format test passed: " + e.getMessage()); + } + + // Test clone method + Person clonedPerson = personsList.clone(person2); + System.out.println("clone test passed: " + clonedPerson); + + // Test writePersonToFile method + personsList.writePersonToFile(person2, "person.txt"); + System.out.println("writePersonToFile test passed: Check person.txt file"); + } +} diff --git a/src/labjavaexceptions/Person.java b/src/labjavaexceptions/Person.java new file mode 100644 index 0000000..aa4cba8 --- /dev/null +++ b/src/labjavaexceptions/Person.java @@ -0,0 +1,63 @@ +package labjavaexceptions; + +public class Person { + private int id; + private String name; + private int age; + private String occupation; + + // Constructor + public Person(int id, String name, int age, String occupation) { + this.id = id; + this.name = name; + setAge(age); // Use the setAge method to handle validation + this.occupation = occupation; + } + + // Setters and Getters + public void setAge(int age) { + if (age < 0) { + throw new IllegalArgumentException("Age cannot be less than 0"); + } + this.age = age; + } + + public int getId() { + return id; + } + + public String getName() { + return name; + } + + public int getAge() { + return age; + } + + public String getOccupation() { + return occupation; + } + + // equals method + @Override + public boolean equals(Object obj) { + if (this == obj) return true; + if (obj == null || getClass() != obj.getClass()) return false; + + Person person = (Person) obj; + + if (!name.equals(person.name)) return false; + if (age != person.age) return false; + return occupation.equals(person.occupation); + } + + @Override + public String toString() { + return "Person{" + + "id=" + id + + ", name='" + name + '\'' + + ", age=" + age + + ", occupation='" + occupation + '\'' + + '}'; + } +} diff --git a/src/labjavaexceptions/PersonsList.java b/src/labjavaexceptions/PersonsList.java new file mode 100644 index 0000000..f4a0c41 --- /dev/null +++ b/src/labjavaexceptions/PersonsList.java @@ -0,0 +1,51 @@ +package labjavaexceptions; + +import java.util.ArrayList; +import java.util.List; +import java.io.FileWriter; +import java.io.IOException; + +public class PersonsList { + private List persons; + + public PersonsList() { + this.persons = new ArrayList<>(); + } + + // Add a Person to the list + public void addPerson(Person person) { + persons.add(person); + } + + // Find a Person by name + public Person findByName(String name) { + if (!name.matches("[A-Za-z]+ [A-Za-z]+")) { + throw new IllegalArgumentException("Name must be properly formatted as 'firstName lastName'"); + } + for (Person person : persons) { + if (person.getName().equals(name)) { + return person; + } + } + return null; + } + + // Clone a Person + public Person clone(Person person) { + return new Person(getNextId(), person.getName(), person.getAge(), person.getOccupation()); + } + + // Get the next ID + private int getNextId() { + return persons.size() + 1; // Simple implementation for example purposes + } + + // Write Person information to a file + public void writePersonToFile(Person person, String filename) { + try (FileWriter writer = new FileWriter(filename)) { + writer.write(person.toString()); + } catch (IOException e) { + e.printStackTrace(); + } + } +}