diff --git a/_config.yml b/_config.yml index 5815247..242a784 100644 --- a/_config.yml +++ b/_config.yml @@ -7,9 +7,7 @@ baseurl: "/JN-CSAblog" remote_theme: jekyll/minima minima: social_links: - - { platform: github, user_url: "https://github.com/nighthawkcoders"} - - { platform: github, user_url: "https://github.com/Tirth-Thakkar"} - - { platform: github, user_url: "https://github.com/h4seeb-cmd"} + - { platform: github, user_url: "https://github.com/Jyustin/JN-CSAblog"} # remote_theme: pages-themes/dinky@v0.2.0 # remote_theme: pages-themes/minimal@v0.2.0 # remote_theme: pages-themes/hacker@v0.2.0 diff --git a/_notebooks/2023-08-17-AP-pseudo-vs-python.ipynb b/_notebooks/2023-08-17-AP-pseudo-vs-python.ipynb deleted file mode 100644 index d6efdb7..0000000 --- a/_notebooks/2023-08-17-AP-pseudo-vs-python.ipynb +++ /dev/null @@ -1,127 +0,0 @@ -{ - "cells": [ - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "---\n", - "toc: true\n", - "comments: true\n", - "layout: notebook\n", - "title: College Board Pseudo Code \n", - "description: The College Board testing language is Pseudo Code. Pseudo mean kind-of language that we will compare to Python.\n", - "courses: { csp: {week: 1} }\n", - "type: hacks\n", - "---" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Learning College Board Pseudo Code\n", - "> College Board uses a kind-of programming language in its Multiple Choice exam. There are thousands of different programming languages have been created, and more are being created every year. College Board has designed a pseudo code, a non operational programming language, to highlight concepts that it wants every student to learn.\n", - "\n", - "College Board is trying to remain neutral and build Computer Science Principles off of any language, thus the Teacher is left to pick the language(s) according to application and curriculum. \n", - "\n", - "College Board Pseudo Code [Exam Reference Sheet](https://apcentral.collegeboard.org/media/pdf/ap-computer-science-principles-exam-reference-sheet.pdf)\n" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Comparison of CB Pseudo Code to Python with descriptions\n", - "\n", - "Command Vocabulary | Pseudo code | Python | Purpose\n", - "Output | DISPLAY(expression) | print(expression, end=\" \") | Displays the value of expression, followed by a space. Python defaults to newline, thus the end=\" \"\n", - "Input | a ← INPUT() | a = input(prompt) | Accepts a value from the user and returns it to the variable a.\n", - "Assignment |\ta ← expression\t | a = expression | Evaluates expression and assigns the result to the variable a.\n", - "Selection | IF (expression) | if expression: | Run commands in the code block associated with the selection\n", - "Iteration n times |\tREPEAT n TIMES | for i in range(n): | Repeat commands in the code block associated withe the iteration n times\n", - "Iteration expression | REPEAT UNTIL (expression) |\twhile expression: | Repeat commands in the code block associated withe the iteration while expression is true\n", - "List Assignment | list ← [expression1, expression2, expression3] | list = [expression1, expression2, expression3] | Assigns 3 values to list, value can be literal or expressions\n", - "First index in List |\tlist[1] | list[0] | Access the 1st element in the list[]. FYI, most programming languages start a zero.\n", - "Last index in List | list[LENGTH(list)] | list[len(list) - 1] | Access the last element in the list[]. If you start at zero, last element is length - 1.\n", - "Define Procedure | PROCEDURE name (parameter) | def name(parameter): | Create a procedure containing a sequence of programming instructions.\n", - "Expression equals |\ta = b\t| a == b | Evaluate if assigned value of a equals assigned value of b\n", - "Expression not equals |\ta ≠ b\t| a != b | Evaluate if assigned value of a is NOT equal to assigned value of b" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Pseudo code IF Code Block\n", - "```\n", - "a ← 1\n", - "b ← 1\n", - "\n", - "IF (a = b) {\n", - " DISPLAY(\"A equals B\")\n", - "}\n", - "```" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# Python code if block to match Pseudo Code\n", - "a = 1\n", - "b = 1\n", - "if (a == b):\n", - " # Python uses indent to establish code block, Teacher use tab key\n", - " print(\"A equals B\")" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Hacks\n", - "> Key Learnings. It is very important that you become fluent in \" Vocabulary\" and researching problems.\n", - "\n", - "- Code a JavaScript cell, this must start with %%js%% in first line of cell. Match the IF condition example in this blog.\n", - "\n", - "- Code a REPEAT n TIMES as described in comparison sheet in Pseudo code, Python, and JavaScript. Be sure to comment your code.\n", - " - REPEAT 100 TIMES\n", - " - Sum all the numpers\n", - " - PRINT the result\n", - "\n", - "- Reflect on our PSEUDO code and how it helped with your problem solving in these hacks. \n", - "\n", - "- Maked efinition for: code block, sequence, selections, iteration. Consider a strategy to remember Pseudo Code, Python and JavaScript for these definitions." - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "base", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.9.12" - }, - "orig_nbformat": 4 - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/_notebooks/2023-08-17-Markdown_Table_Code_Hack.ipynb b/_notebooks/2023-08-17-Markdown_Table_Code_Hack.ipynb deleted file mode 100644 index a1c0da6..0000000 --- a/_notebooks/2023-08-17-Markdown_Table_Code_Hack.ipynb +++ /dev/null @@ -1,141 +0,0 @@ -{ - "cells": [ - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "---\n", - "toc: true\n", - "comments: true\n", - "layout: notebook\n", - "title: IPYNB Table, Code\n", - "description: Example!!! This sample shows markdown cell, markdown table, markdown code fencing, and code cells.\n", - "courses: { compsci: {week: 1} }\n", - "type: hacks\n", - "---" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Learning College Board Pseudo Code\n", - "> College Board uses a kind-of programming language in its Multiple Choice exam. There are thousands of different programming languages have been created, and more are being created every year. College Board has designed a pseudo code, a non operational programming language, to highlight concepts that it wants every student to learn.\n", - "\n", - "College Board is trying to remain neutral and build Computer Science Principles off of any language, thus the Teacher is left to pick the language(s) according to application and curriculum. \n", - "\n", - "College Board Pseudo Code [Exam Reference Sheet](https://apcentral.collegeboard.org/media/pdf/ap-computer-science-principles-exam-reference-sheet.pdf)\n" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Comparison of CB Pseudo Code to Python with descriptions\n", - "\n", - "Command Vocabulary | Pseudo code | Python | Purpose\n", - "Output | DISPLAY(expression) | print(expression, end=\" \") | Displays the value of expression, followed by a space. Python defaults to newline, thus the end=\" \"\n", - "Input | a ← INPUT() | a = input(prompt) | Accepts a value from the user and returns it to the variable a.\n", - "Assignment |\ta ← expression\t | a = expression | Evaluates expression and assigns the result to the variable a.\n", - "Selection | IF (expression) | if expression: | Run commands in the code block associated with the selection\n", - "Iteration n times |\tREPEAT n TIMES | for i in range(n): | Repeat commands in the code block associated withe the iteration n times\n", - "Iteration expression | REPEAT UNTIL (expression) |\twhile expression: | Repeat commands in the code block associated withe the iteration while expression is true\n", - "List Assignment | list ← [expression1, expression2, expression3] | list = [expression1, expression2, expression3] | Assigns 3 values to list, value can be literal or expressions\n", - "First index in List |\tlist[1] | list[0] | Access the 1st element in the list[]. FYI, most programming languages start a zero.\n", - "Last index in List | list[LENGTH(list)] | list[len(list) - 1] | Access the last element in the list[]. If you start at zero, last element is length - 1.\n", - "Define Procedure | PROCEDURE name (parameter) | def name(parameter): | Create a procedure containing a sequence of programming instructions.\n", - "Expression equals |\ta = b\t| a == b | Evaluate if assigned value of a equals assigned value of b\n", - "Expression not equals |\ta ≠ b\t| a != b | Evaluate if assigned value of a is NOT equal to assigned value of b" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Pseudo code IF Code Block\n", - "```\n", - "a ← 1\n", - "b ← 1\n", - "\n", - "IF (a = b) {\n", - " DISPLAY(\"A equals B\")\n", - "}\n", - "```" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "A equals B\n" - ] - } - ], - "source": [ - "# Python code if block to match Pseudo Code\n", - "a = 1\n", - "b = 1\n", - "if (a == b):\n", - " # Python uses indent to establish code block, Teacher use tab key\n", - " print(\"A equals B\")" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Hacks\n", - "> Key Learnings. It is very important that you become fluent in \" Vocabulary\" and researching problems.\n", - "\n", - "- Code a JavaScript cell, this must start with %%js%% in first line of cell. Match the IF condition example in this blog.\n", - "\n", - "- Code a REPEAT n TIMES as described in comparison sheet in Pseudo code, Python, and JavaScript. Be sure to comment your code.\n", - " - REPEAT 100 TIMES\n", - " - Sum all the numpers\n", - " - PRINT the result\n", - "\n", - "- Reflect on our PSEUDO code and how it helped with your problem solving in these hacks. \n", - "\n", - "- Maked efinition for: code block, sequence, selections, iteration. Consider a strategy to remember Pseudo Code, Python and JavaScript for these definitions." - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [] - } - ], - "metadata": { - "kernelspec": { - "display_name": "base", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.9.12" - }, - "orig_nbformat": 4 - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/_notebooks/2023-08-21-HTML_Image_Hack.ipynb b/_notebooks/2023-08-21-HTML_Image_Hack.ipynb deleted file mode 100644 index ed105c7..0000000 --- a/_notebooks/2023-08-21-HTML_Image_Hack.ipynb +++ /dev/null @@ -1,209 +0,0 @@ -{ - "cells": [ - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "---\n", - "comments: true\n", - "layout: notebook\n", - "title: IPYNB HTML, img\n", - "description: A key to development in this class is the association VSCode to a GitHub pages project. This is where students update assignments and present work.\n", - "type: hacks\n", - "courses: { compsci: {week: 0} }\n", - "categories: [C4.1]\n", - "---" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Create your own GitHub Pages Project\n", - "> Make you own project from GitHub Pages Student Repo." - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Make a GitHub Pages Repository\n", - "> Goto GitHub [student](https://github.com/nighthawkcoders/student).\n", - "\n", - "- Reference: [Create from template](https://docs.github.com/en/repositories/creating-and-managing-repositories/creating-a-repository-from-a-template). Most student will pick this option.\n", - "\n", - "\n", - "- Reference: [Fork a repo](https://docs.github.com/en/get-started/quickstart/fork-a-repo). Student in CSA that teacher has asked to contribute to student example repo will pick this.\n" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Start the GitHub Pages Student Project\n", - "> Run the following commands using terminal on you machine. Be sure Repo has been forked.\n", - "\n", - "- Clone and Open project in VSCode\n", - "- Change \"forkme\" text with your \"ghid\" or selected location\n", - "\n", - "\n", - "```bash\n", - "(base) id:~$ mkdir vscode # make a vscode directory, if you don't have one\n", - "(base) id:~$ cd vscode # change to the directory\n", - "(base) id:~$ git clone https://github.com/forkme/student.git # change to your repo\n", - "(base) id:~$ cd student # change to the project directory\n", - "(base) id:~$ code . # open VSCode in project directory\n", - "```" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### VSCode for Python Extensions, adapt for your needs JavaScript, Python, Java\n", - "- VSCode [Language extensions](https://code.visualstudio.com/docs/languages/overview)\n", - " - Install Python, Python Environment Manager, Python Extension Pack, Pylance\n", - " - Install Jupyter, Jupyter Keymap\n", - " - Install IntelliCode, IntelliCode API Usage Examples\n", - " - Windows machines install WSL Remote Development" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": { - "vscode": { - "languageId": "html" - } - }, - "outputs": [ - { - "data": { - "text/html": [ - "\n", - "\n", - "\n", - "
\n", - "
\n", - " \n", - " \"Extensions\"\n", - " \n", - "
\n", - "
\n", - "
\n", - "

\n", - " Visual Studio Code claims to provide just the tools a developer needs for a quick code-build-debug and version control cycle. It provides a Market Place for enhancements and more complex workflows. Before adding extensions, clone projects and see what is requested or added. Here are some extension that were added through that process or that I have added...\n", - "

\n", - " \n", - "

\n", - " Review Details in Marketplace for better explanation of purpose of the things explained above. There is a lot more! As you need Git help look at things like Git History and GitLens. Or, perhaps you enjoy Vim and want Vim emulation for editing, their is an extension for that. Later, there may be interest in AWS Toolkit or Deploy extensions. We will learn more about Marketplace Extensions as we do more.\n", - "

\n", - "
\n", - "
\n", - "
\n" - ], - "text/plain": [ - "" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "%%HTML\n", - "\n", - "\n", - "\n", - "
\n", - "
\n", - " \n", - " \"Extensions\"\n", - " \n", - "
\n", - "
\n", - "
\n", - "

\n", - " Visual Studio Code claims to provide just the tools a developer needs for a quick code-build-debug and version control cycle. It provides a Market Place for enhancements and more complex workflows. Before adding extensions, clone projects and see what is requested or added. Here are some extension that were added through that process or that I have added...\n", - "

\n", - "
    \n", - "
  • \n", - " In marketplace there are several extensions for Python, Python Intellisense, Python Extension Pack\n", - "
  • \n", - "
  • \n", - " Jupyter: This supports build jupyter ipynb files from within VS Code\n", - "
  • \n", - "
  • \n", - " Code Spell Checker: Got to have it when building documents, particularly if you spell and typo like the Teacher\n", - "
  • \n", - "
  • \n", - " IntelliCode: Got to have it when creating a code file, it will sense type of code by extension. Also, it help with syntax as you are coding.\n", - "
  • \n", - "
\n", - "

\n", - " Review Details in Marketplace for better explanation of purpose of the things explained above. There is a lot more! As you need Git help look at things like Git History and GitLens. Or, perhaps you enjoy Vim and want Vim emulation for editing, their is an extension for that. Later, there may be interest in AWS Toolkit or Deploy extensions. We will learn more about Marketplace Extensions as we do more.\n", - "

\n", - "
\n", - "
\n", - "
" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Hacks\n", - "> Setup Tools and test GitHub connection. Tool and Equipment setup is like attendance, without Tools and Equipment you are effectually absent.\n", - "- Change index.md to show it is REALLY YOURS. Refer to [Markdown Cheet Sheet](https://www.markdownguide.org/cheat-sheet/).\n", - " - Push a minor \"index.md\" change and Verify on GitHub [https://code.visualstudio.com/docs/editor/versioncontrol#_git-support](https://code.visualstudio.com/docs/editor/versioncontrol#_git-support)\n", - " - Verify \"index.md\" change on deployed GitHub Pages" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3 (ipykernel)", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.9.12" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/_notebooks/2023-08-21-VSCode-GitHub_Pages.ipynb b/_notebooks/2023-08-21-VSCode-GitHub_Pages.ipynb deleted file mode 100644 index cd92a08..0000000 --- a/_notebooks/2023-08-21-VSCode-GitHub_Pages.ipynb +++ /dev/null @@ -1,210 +0,0 @@ -{ - "cells": [ - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "---\n", - "comments: true\n", - "layout: notebook\n", - "title: Student GitHub Pages\n", - "description: A key to development in this class is the association VSCode to a GitHub pages project. This is where students update assignments and present work.\n", - "type: hacks\n", - "toc: true\n", - "courses: { csse: {week: 0}, csp: {week: 0}, csa: {week: 0} }\n", - "categories: [C4.1]\n", - "---" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Create your own GitHub Pages Project\n", - "> Make you own project from GitHub Pages Student Repo." - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Make a GitHub Pages Repository\n", - "> Goto GitHub [student](https://github.com/nighthawkcoders/student).\n", - "\n", - "- Reference: [Create from template](https://docs.github.com/en/repositories/creating-and-managing-repositories/creating-a-repository-from-a-template). Most student will pick this option.\n", - "\n", - "\n", - "- Reference: [Fork a repo](https://docs.github.com/en/get-started/quickstart/fork-a-repo). Student in CSA that teacher has asked to contribute to student example repo will pick this.\n" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Start the GitHub Pages Student Project\n", - "> Run the following commands using terminal on you machine. Be sure Repo has been forked.\n", - "\n", - "- Clone and Open project in VSCode\n", - "- Change \"forkme\" text with your \"ghid\" or selected location\n", - "\n", - "\n", - "```bash\n", - "(base) id:~$ mkdir vscode # make a vscode directory, if you don't have one\n", - "(base) id:~$ cd vscode # change to the directory\n", - "(base) id:~$ git clone https://github.com/forkme/student.git # change to your repo\n", - "(base) id:~$ cd student # change to the project directory\n", - "(base) id:~$ code . # open VSCode in project directory\n", - "```" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### VSCode for Python Extensions, adapt for your needs JavaScript, Python, Java\n", - "- VSCode [Language extensions](https://code.visualstudio.com/docs/languages/overview)\n", - " - Install Python, Python Environment Manager, Python Extension Pack, Pylance\n", - " - Install Jupyter, Jupyter Keymap\n", - " - Install IntelliCode, IntelliCode API Usage Examples\n", - " - Windows machines install WSL Remote Development" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": { - "vscode": { - "languageId": "html" - } - }, - "outputs": [ - { - "data": { - "text/html": [ - "\n", - "\n", - "\n", - "
\n", - "
\n", - " \n", - " \"Extensions\"\n", - " \n", - "
\n", - "
\n", - "
\n", - "

\n", - " Visual Studio Code claims to provide just the tools a developer needs for a quick code-build-debug and version control cycle. It provides a Market Place for enhancements and more complex workflows. Before adding extensions, clone projects and see what is requested or added. Here are some extension that were added through that process or that I have added...\n", - "

\n", - "
    \n", - "
  • \n", - " In marketplace there are several extensions for Python, Python Intellisense, Python Extension Pack\n", - "
  • \n", - "
  • \n", - " Jupyter: This supports build jupyter ipynb files from within VS Code\n", - "
  • \n", - "
  • \n", - " Code Spell Checker: Got to have it when building documents, particularly if you spell and typo like the Teacher\n", - "
  • \n", - "
  • \n", - " IntelliCode: Got to have it when creating a code file, it will sense type of code by extension. Also, it help with syntax as you are coding.\n", - "
  • \n", - "
\n", - "

\n", - " Review Details in Marketplace for better explanation of purpose of the things explained above. There is a lot more! As you need Git help look at things like Git History and GitLens. Or, perhaps you enjoy Vim and want Vim emulation for editing, their is an extension for that. Later, there may be interest in AWS Toolkit or Deploy extensions. We will learn more about Marketplace Extensions as we do more.\n", - "

\n", - "
\n", - "
\n", - "
\n" - ], - "text/plain": [ - "" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "%%HTML\n", - "\n", - "\n", - "\n", - "
\n", - "
\n", - " \n", - " \"Extensions\"\n", - " \n", - "
\n", - "
\n", - "
\n", - "

\n", - " Visual Studio Code claims to provide just the tools a developer needs for a quick code-build-debug and version control cycle. It provides a Market Place for enhancements and more complex workflows. Before adding extensions, clone projects and see what is requested or added. Here are some extension that were added through that process or that I have added...\n", - "

\n", - "
    \n", - "
  • \n", - " In marketplace there are several extensions for Python, Python Intellisense, Python Extension Pack\n", - "
  • \n", - "
  • \n", - " Jupyter: This supports build jupyter ipynb files from within VS Code\n", - "
  • \n", - "
  • \n", - " Code Spell Checker: Got to have it when building documents, particularly if you spell and typo like the Teacher\n", - "
  • \n", - "
  • \n", - " IntelliCode: Got to have it when creating a code file, it will sense type of code by extension. Also, it help with syntax as you are coding.\n", - "
  • \n", - "
\n", - "

\n", - " Review Details in Marketplace for better explanation of purpose of the things explained above. There is a lot more! As you need Git help look at things like Git History and GitLens. Or, perhaps you enjoy Vim and want Vim emulation for editing, their is an extension for that. Later, there may be interest in AWS Toolkit or Deploy extensions. We will learn more about Marketplace Extensions as we do more.\n", - "

\n", - "
\n", - "
\n", - "
" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Hacks\n", - "> Setup Tools and test GitHub connection. Tool and Equipment setup is like attendance, without Tools and Equipment you are effectually absent.\n", - "- Change index.md to show it is REALLY YOURS. Refer to [Markdown Cheet Sheet](https://www.markdownguide.org/cheat-sheet/).\n", - " - Push a minor \"index.md\" change and Verify on GitHub [https://code.visualstudio.com/docs/editor/versioncontrol#_git-support](https://code.visualstudio.com/docs/editor/versioncontrol#_git-support)\n", - " - Verify \"index.md\" change on deployed GitHub Pages" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3 (ipykernel)", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.9.12" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/_notebooks/2023-09-23-unit2hacks.ipynb b/_notebooks/2023-09-23-unit2hacks.ipynb new file mode 100755 index 0000000..4079dfb --- /dev/null +++ b/_notebooks/2023-09-23-unit2hacks.ipynb @@ -0,0 +1,605 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "layout: post\n", + "title: Unit 2 Hacks\n", + "description: hacks and tricks learned in Unit 2 of Computer Science A\n", + "type: tangibles\n", + "courses: { compsci: {week: 0} }\n", + "categories: [C4.1]\n", + "---" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# note: the following hacks were done with chatgpt assist. I don't claim to have written every line of code here\n", + "\n", + "# Hack 1: \n", + "\n", + "Create a void method that takes an integer input and adds it to an ArrayList. Then, add a non-void method that is able to call a certain index from the ArrayList." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Enter an integer: " + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "ArrayList contents: [5, 3]\n", + "Element at index 1: 3\n" + ] + } + ], + "source": [ + "import java.util.ArrayList;\n", + "import java.util.Scanner;\n", + "\n", + "public class ArrayListTest {\n", + "\n", + " // Declare ArrayList as a static field to make it accessible across methods\n", + " private static ArrayList numbers = new ArrayList();\n", + "\n", + " public static void inputArrlist() {\n", + " Scanner sc = new Scanner(System.in);\n", + " System.out.print(\"Enter an integer: \");\n", + " int n = sc.nextInt(); // take input from user\n", + " numbers.add(n); // add input to ArrayList\n", + " }\n", + "\n", + " // A non-void method to get an element from ArrayList by index\n", + " public static int getElementAtIndex(int index) {\n", + " if (index >= 0 && index < numbers.size()) {\n", + " return numbers.get(index);\n", + " } else {\n", + " System.out.println(\"Index out of bounds.\");\n", + " return -1; // You can choose a different return value or throw an exception if needed\n", + " }\n", + " }\n", + "\n", + " // Java standard runtime entry point\n", + " public static void main(String[] args) {\n", + " inputArrlist(); // Call the method to add an integer to the ArrayList\n", + "\n", + " // Print the ArrayList\n", + " System.out.println(\"ArrayList contents: \" + numbers);\n", + "\n", + " // Example of calling the non-void method to get an element by index\n", + " int indexToAccess = 1; // Change this to the desired index\n", + " int elementAtIndex = getElementAtIndex(indexToAccess);\n", + "\n", + " if (elementAtIndex != -1) {\n", + " System.out.println(\"Element at index \" + indexToAccess + \": \" + elementAtIndex);\n", + " }\n", + " }\n", + "}\n", + "\n", + "ArrayListTest.main(null); // Class prefix allows reference of Static Method" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# HACK 2\n", + "Create a simple guessing game with random numbers in math, except the random number is taken to a random exponent (also includes roots), and the person has to find out what the root and exponent is (with hints!). Use at least one static and one non-static method in your class." + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Welcome to the Exponent Guessing Game!\n", + "I've generated a random number, raised it to an exponent,\n", + "and your task is to guess both the base and the exponent.\n", + "Let's get started!\n", + "Enter your guess for the base: " + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Enter your guess for the exponent: Hint: The base is less than 3.\n", + "Hint: The exponent is 0.5 (a square root).\n", + "Enter your guess for the base: Enter your guess for the exponent: Hint: The base is less than 3.\n", + "Hint: The exponent is 0.5 (a square root).\n", + "Enter your guess for the base: Enter your guess for the exponent: Congratulations! You've guessed it!\n", + "It took you 3 attempts.\n" + ] + } + ], + "source": [ + "import java.util.Random;\n", + "import java.util.Scanner;\n", + "\n", + "public class ExponentGuessingGame {\n", + "\n", + " // Static field\n", + " private static Random random = new Random();\n", + " private double base;\n", + " private double exponent;\n", + "\n", + " // Constructor (non-static)\n", + " public ExponentGuessingGame() {\n", + " generateRandomNumber(); // Initialize the game by generating a random base and exponent.\n", + " }\n", + "\n", + " // Non-static method\n", + " private void generateRandomNumber() {\n", + " base = random.nextInt(2); // Generate a random base between 1 and 2.\n", + " int exponentChoice = random.nextInt(3); // Choose a random exponent type (0: Square root, 1: Cube root, 2: Random exponent).\n", + " if (exponentChoice == 0) {\n", + " exponent = 0.5; // Set the exponent to 0.5 for a square root.\n", + " } else if (exponentChoice == 1) {\n", + " exponent = 1.0 / 3.0; // Set the exponent to 1/3 for a cube root.\n", + " } else {\n", + " exponent = 2; // Set the exponent to 2 for square.\n", + " }\n", + " }\n", + "\n", + " // Non-static method\n", + " public void play() {\n", + " Scanner scanner = new Scanner(System.in);\n", + " int attempts = 0;\n", + "\n", + " System.out.println(\"Welcome to the Exponent Guessing Game!\");\n", + " System.out.println(\"I've generated a random number, raised it to an exponent,\");\n", + " System.out.println(\"and your task is to guess both the base and the exponent.\");\n", + " System.out.println(\"Let's get started!\");\n", + "\n", + " while (true) {\n", + " attempts++;\n", + " System.out.print(\"Enter your guess for the base: \");\n", + " double guessedBase = scanner.nextDouble();\n", + " System.out.print(\"Enter your guess for the exponent: \");\n", + " double guessedExponent = scanner.nextDouble();\n", + "\n", + " if (guessedBase == base && guessedExponent == exponent) {\n", + " System.out.println(\"Congratulations! You've guessed it!\");\n", + " System.out.println(\"It took you \" + attempts + \" attempts.\");\n", + " break;\n", + " } else {\n", + " displayHint(base, exponent); // Non-static method call to provide hints.\n", + " }\n", + " }\n", + "\n", + " scanner.close();\n", + " }\n", + "\n", + " // Static method\n", + " private static void displayHint(double base, double exponent) {\n", + " if (base < 3) {\n", + " System.out.println(\"Hint: The base is less than 3.\");\n", + " } else {\n", + " System.out.println(\"Hint: The base is greater than or equal to 3.\");\n", + " }\n", + "\n", + " if (exponent == 0.5) {\n", + " System.out.println(\"Hint: The exponent is 0.5 (a square root).\");\n", + " } else if (exponent == 0.3) {\n", + " System.out.println(\"Hint: The exponent is 0.3 (a cube root).\");\n", + " } else {\n", + " System.out.println(\"Hint: The exponent is 2.\");\n", + " }\n", + " }\n", + "\n", + " // Static method (entry point of the program)\n", + " public static void main(String[] args) {\n", + " ExponentGuessingGame game = new ExponentGuessingGame();\n", + " game.play(); // Start the game by calling the play method (non-static).\n", + " }\n", + "}\n", + "\n", + "ExponentGuessingGame.main(null);\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# HACK 3\n", + "Create a class of your choosing that has multiple parameters of different types (int, boolean, String, double) and put 5 data values in that list. Show that you can access the information by givng some samples." + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Person 1 - Name: John, Age: 25, Student: false, Height: 5.9\n", + "Person 2 - Name: Alice, Age: 18, Student: true, Height: 5.5\n", + "Person 3 - Name: Bob, Age: 30, Student: false, Height: 6.0\n", + "Person 4 - Name: Eve, Age: 22, Student: true, Height: 5.7\n", + "Person 5 - Name: Charlie, Age: 28, Student: false, Height: 6.2\n" + ] + } + ], + "source": [ + "public class Person {\n", + " // Declare private instance variables for a Person\n", + " private int age;\n", + " private boolean isStudent;\n", + " private String name;\n", + " private double height;\n", + "\n", + " // Constructor to initialize a Person with provided data\n", + " public Person(int age, boolean isStudent, String name, double height) {\n", + " // Initialize the instance variables with the provided values\n", + " this.age = age;\n", + " this.isStudent = isStudent;\n", + " this.name = name;\n", + " this.height = height;\n", + " }\n", + "\n", + " // Getter method to retrieve the age of the Person\n", + " public int getAge() {\n", + " return age;\n", + " }\n", + "\n", + " // Getter method to check if the Person is a student\n", + " public boolean isStudent() {\n", + " return isStudent;\n", + " }\n", + "\n", + " // Getter method to retrieve the name of the Person\n", + " public String getName() {\n", + " return name;\n", + " }\n", + "\n", + " // Getter method to retrieve the height of the Person\n", + " public double getHeight() {\n", + " return height;\n", + " }\n", + "\n", + " public static void main(String[] args) {\n", + " // Create five Person instances with sample data\n", + " Person person1 = new Person(25, false, \"John\", 5.9);\n", + " Person person2 = new Person(18, true, \"Alice\", 5.5);\n", + " Person person3 = new Person(30, false, \"Bob\", 6.0);\n", + " Person person4 = new Person(22, true, \"Eve\", 5.7);\n", + " Person person5 = new Person(28, false, \"Charlie\", 6.2);\n", + "\n", + " // Access and print information from the Person instances\n", + " System.out.println(\"Person 1 - Name: \" + person1.getName() + \", Age: \" + person1.getAge() + \", Student: \" + person1.isStudent() + \", Height: \" + person1.getHeight());\n", + " System.out.println(\"Person 2 - Name: \" + person2.getName() + \", Age: \" + person2.getAge() + \", Student: \" + person2.isStudent() + \", Height: \" + person2.getHeight());\n", + " System.out.println(\"Person 3 - Name: \" + person3.getName() + \", Age: \" + person3.getAge() + \", Student: \" + person3.isStudent() + \", Height: \" + person3.getHeight());\n", + " System.out.println(\"Person 4 - Name: \" + person4.getName() + \", Age: \" + person4.getAge() + \", Student: \" + person4.isStudent() + \", Height: \" + person4.getHeight());\n", + " System.out.println(\"Person 5 - Name: \" + person5.getName() + \", Age: \" + person5.getAge() + \", Student: \" + person5.isStudent() + \", Height: \" + person5.getHeight());\n", + " }\n", + "}\n", + "\n", + "Person.main(null);" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# HACK 4\n", + "Using your preliminary knowlege of loops, use a for loop to iterate through a person’s first and last name, seperated by a space, and create methods to call a person’s first name and a person’s last name by iterating through the string." + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "First Name: John\n", + "Last Name: Doe\n" + ] + } + ], + "source": [ + "public class PersonName {\n", + " private String fullName;\n", + "\n", + " public PersonName(String fullName) {\n", + " this.fullName = fullName;\n", + " }\n", + "\n", + " // Method to get the first name\n", + " public String getFirstName() {\n", + " StringBuilder firstName = new StringBuilder();\n", + "\n", + " // Iterate through each character in the full name\n", + " for (int i = 0; i < fullName.length(); i++) {\n", + " char c = fullName.charAt(i);\n", + "\n", + " // Check if the current character is not a space\n", + " if (c != ' ') {\n", + " // Append the character to the first name\n", + " firstName.append(c);\n", + " } else {\n", + " // If a space is encountered, stop iterating (we've found the first name)\n", + " break;\n", + " }\n", + " }\n", + "\n", + " // Convert the StringBuilder to a String and return the first name\n", + " return firstName.toString();\n", + " }\n", + "\n", + " // Method to get the last name\n", + " public String getLastName() {\n", + " StringBuilder lastName = new StringBuilder();\n", + " boolean foundSpace = false;\n", + "\n", + " // Iterate through each character in the full name in reverse order\n", + " for (int i = fullName.length() - 1; i >= 0; i--) {\n", + " char c = fullName.charAt(i);\n", + "\n", + " // Check if the current character is not a space and we haven't found a space yet\n", + " if (c != ' ' && !foundSpace) {\n", + " // Insert the character at the beginning of the last name (to reverse the order)\n", + " lastName.insert(0, c);\n", + " } else {\n", + " // If a space is encountered or we've already found a space, set the flag to true\n", + " foundSpace = true;\n", + " }\n", + " }\n", + "\n", + " // Convert the StringBuilder to a String and return the last name\n", + " return lastName.toString();\n", + " }\n", + "\n", + " public static void main(String[] args) {\n", + " PersonName person = new PersonName(\"John Doe\");\n", + " \n", + " // Get and print the first name\n", + " String firstName = person.getFirstName();\n", + " System.out.println(\"First Name: \" + firstName);\n", + " \n", + " // Get and print the last name\n", + " String lastName = person.getLastName();\n", + " System.out.println(\"Last Name: \" + lastName);\n", + " }\n", + "}\n", + "\n", + "\n", + "PersonName.main(null);" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# HACK 4 BUT WITH USER INPUT FOR NAME" + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Enter your full name: First Name: engineer\n", + "Last Name: gaming\n" + ] + } + ], + "source": [ + "import java.util.Scanner;\n", + "\n", + "public class PersonName {\n", + " private String fullName;\n", + "\n", + " public PersonName(String fullName) {\n", + " this.fullName = fullName;\n", + " }\n", + "\n", + " // Method to get the first name\n", + " public String getFirstName() {\n", + " StringBuilder firstName = new StringBuilder();\n", + "\n", + " // Iterate through each character in the full name\n", + " for (int i = 0; i < fullName.length(); i++) {\n", + " char c = fullName.charAt(i);\n", + "\n", + " // Check if the current character is not a space\n", + " if (c != ' ') {\n", + " // Append the character to the first name\n", + " firstName.append(c);\n", + " } else {\n", + " // If a space is encountered, stop iterating (we've found the first name)\n", + " break;\n", + " }\n", + " }\n", + "\n", + " // Convert the StringBuilder to a String and return the first name\n", + " return firstName.toString();\n", + " }\n", + "\n", + " // Method to get the last name\n", + " public String getLastName() {\n", + " StringBuilder lastName = new StringBuilder();\n", + " boolean foundSpace = false;\n", + "\n", + " // Iterate through each character in the full name in reverse order\n", + " for (int i = fullName.length() - 1; i >= 0; i--) {\n", + " char c = fullName.charAt(i);\n", + "\n", + " // Check if the current character is not a space and we haven't found a space yet\n", + " if (c != ' ' && !foundSpace) {\n", + " // Insert the character at the beginning of the last name (to reverse the order)\n", + " lastName.insert(0, c);\n", + " } else {\n", + " // If a space is encountered or we've already found a space, set the flag to true\n", + " foundSpace = true;\n", + " }\n", + " }\n", + "\n", + " // Convert the StringBuilder to a String and return the last name\n", + " return lastName.toString();\n", + " }\n", + "\n", + " public static void main(String[] args) {\n", + " Scanner scanner = new Scanner(System.in);\n", + "\n", + " // Prompt the user for their full name\n", + " System.out.print(\"Enter your full name: \");\n", + " String fullName = scanner.nextLine();\n", + "\n", + " // Create a PersonName object with the user's input\n", + " PersonName person = new PersonName(fullName);\n", + "\n", + " // Get and print the first name\n", + " String firstName = person.getFirstName();\n", + " System.out.println(\"First Name: \" + firstName);\n", + "\n", + " // Get and print the last name\n", + " String lastName = person.getLastName();\n", + " System.out.println(\"Last Name: \" + lastName);\n", + "\n", + " // Close the scanner\n", + " scanner.close();\n", + " }\n", + "}\n", + "\n", + "PersonName.main(null);" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [], + "source": [ + "%maven org.knowm.xchart:xchart:3.5.2\n", + "\n", + "import org.knowm.xchart.*;\n", + "\n", + "public class HeartShapeGraph {\n", + "\n", + " public static void main(String[] args) throws Exception {\n", + " int numPoints = 100;\n", + " double[] xData = new double[numPoints];\n", + " double[] yData = new double[numPoints];\n", + "\n", + " plotHeartShape(xData, yData, 0, 0, numPoints - 1);\n", + "\n", + " // Create Chart\n", + " XYChart chart = QuickChart.getChart(\"Heart Shape\", \"X\", \"Y\", \"y(x)\", xData, yData);\n", + "\n", + " // Show it\n", + " new SwingWrapper(chart).displayChart();\n", + " }\n", + "\n", + " private static void plotHeartShape(double[] xData, double[] yData, int index, double t, int maxIndex) {\n", + " if (index > maxIndex) {\n", + " return;\n", + " }\n", + "\n", + " //Chat GPT Math\n", + " xData[index] = 16 * Math.pow(Math.sin(t), 3);\n", + " yData[index] = 13 * Math.cos(t) - 5 * Math.cos(2 * t) - 2 * Math.cos(3 * t) - Math.cos(4 * t);\n", + "\n", + " plotHeartShape(xData, yData, index + 1, t + (2 * Math.PI) / maxIndex, maxIndex);\n", + " }\n", + "}\n", + "\n", + "HeartShapeGraph.main(null);" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "ename": "", + "evalue": "", + "output_type": "error", + "traceback": [ + "\u001b[1;31mThe Kernel crashed while executing code in the the current cell or a previous cell. Please review the code in the cell(s) to identify a possible cause of the failure. Click here for more info. View Jupyter log for further details." + ] + } + ], + "source": [ + "%maven org.knowm.xchart:xchart:3.5.2\n", + "\n", + "import org.knowm.xchart.*;\n", + "\n", + "public class CoolGraph {\n", + "\n", + " public static void main(String[] args) throws Exception {\n", + " int numPoints = 100;\n", + " double[] xData = new double[numPoints];\n", + " double[] yData = new double[numPoints];\n", + "\n", + " plotHeartShape(xData, yData, 0, 0, numPoints - 1);\n", + "\n", + " // Create Chart\n", + " XYChart chart = QuickChart.getChart(\"Heart Shape\", \"X\", \"Y\", \"y(x)\", xData, yData);\n", + "\n", + " // Show it\n", + " new SwingWrapper(chart).displayChart();\n", + " }\n", + "\n", + " private static void plotHeartShape(double[] xData, double[] yData, int index, double t, int maxIndex) {\n", + " if (index > maxIndex) {\n", + " return;\n", + " }\n", + "\n", + " //Chat GPT Math\n", + " xData[index] = 16 * Math.pow(Math.cos(t), 3);\n", + " yData[index] = 13 * Math.sin(t) - 5 * Math.sin(2 * t) - 2 * Math.sin(3 * t) - Math.sin(4 * t);\n", + "\n", + " plotHeartShape(xData, yData, index + 1, t + (2 * Math.PI) / maxIndex, maxIndex);\n", + " }\n", + "}\n", + "\n", + "HeartShapeGraph.main(null);" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Java", + "language": "java", + "name": "java" + }, + "language_info": { + "codemirror_mode": "java", + "file_extension": ".jshell", + "mimetype": "text/x-java-source", + "name": "java", + "pygments_lexer": "java", + "version": "20.0.2+9" + }, + "orig_nbformat": 4 + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/_notebooks/2023-10-08-Unit_3_Booleans.ipynb b/_notebooks/2023-10-08-Unit_3_Booleans.ipynb new file mode 100755 index 0000000..42263ec --- /dev/null +++ b/_notebooks/2023-10-08-Unit_3_Booleans.ipynb @@ -0,0 +1,870 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "toc: true\n", + "comments: true\n", + "layout: post\n", + "title: Unit 3 Lesson\n", + "type: tangibles\n", + "courses: { compsci: {week: 0} }\n", + "---" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Lessons\n", + "\n", + "## 3.1\n", + "\n", + "### Learning Objective\n", + "- Evaluate Boolean expressions that use relational operators in program code\n", + "\n", + "Types of Rational Operators\n", + "- Operators\n", + " - Primitives\n", + " - Equal to: ==\n", + " - Not Equal to: !=\n", + "- Arithmetic\n", + " - Greater than: >\n", + " - Less than: >\n", + " - Greater than or equal to: >=\n", + " - Less than or equal to: <=\n", + "\n", + "All operators give a `true` or `False` value\n", + "\n", + " Operators SHOULD NOT be used on String . String comparisons should be done using .equal or .compareTo\n", + "\n", + "- This is because\n", + " - In Java, strings should not be compared using the == operator because it checks for ______reference______ equality, not _______content_____ equality.\n", + " - When you use == with objects (including strings), it checks if the references to the objects are the same. In other words, it checks if they point to the same _______memory location_____ in the memory.\n", + " - String literals in Java are stored in a special memory area called the \"String Pool\". When you create a string literal, Java checks if a string with the same content already exists in the pool. If it does, it returns a reference to that existing string; if not, it creates a new string.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Comparing Numbers\n", + "\n", + "\n", + " \n", + "\n", + "\n", + "

Select two numbers and check their relation:

\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "

\n", + " \n", + "\n", + "" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "false\n" + ] + } + ], + "source": [ + "public class Test {\n", + " public static void main(){\n", + " String a = \"Hello\";\n", + " String b = new String(\"Hello\");\n", + "\n", + " System.out.println( a == b);\n", + " }\n", + "}\n", + "Test.main()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 3.2 3.3 and 3.4\n", + "\n", + "\n", + "### Learning Objective\n", + "- Represent branching logical processes by using conditional statements\n", + "\n", + "We all know how if and else statements work\n", + "\n", + "We all know how if and else statements work\n", + "\n", + "#### Syntax" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "\n", + "Interactive Flip Cards\n", + "\n", + "\n", + "\n", + "\n", + "
\n", + "
\n", + "
\n", + "

if-else Syntax

\n", + "
\n", + "
\n", + "
\n",
+    "        if (condition) {\n",
+    "            // Code to execute if the condition is true\n",
+    "        } else {\n",
+    "            // Code to execute if the condition is false\n",
+    "        }\n",
+    "      
\n", + "
\n", + "
\n", + "
\n", + "\n", + "
\n", + "
\n", + "
\n", + "

else-if Syntax

\n", + "
\n", + "
\n", + "
\n",
+    "        if (condition1) {\n",
+    "            // Code to be executed if condition1 is true\n",
+    "        } else if (condition2) {\n",
+    "            // Code to be executed if condition2 is true\n",
+    "        } else if (condition3) {\n",
+    "            // Code to be executed if condition3 is true\n",
+    "        } else {\n",
+    "            // Code to be executed if none of the conditions are true\n",
+    "        }\n",
+    "      
\n", + "
\n", + "
\n", + "
\n", + "\n", + "\n", + "" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 3.5\n", + "\n", + "### Learning Objectives:\n", + "\n", + "- Understand nested if-else statements and their role in representing branching logical processes.\n", + "- Evaluate compound boolean expressions using logical operators like ``&&`` and ``||``.\n", + "- Introduce short-circuited evaluation in compound boolean expressions.\n", + "\n", + "#### Nested if-else statements\n", + "Nested if-else statements allow for ____________MUTLIPLE_ levels of decision-making within a program.\n" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "x is positive, but y is not.\n" + ] + } + ], + "source": [ + "public class Nested {\n", + " public static void main() {\n", + " int x = 5;\n", + " int y = -10;\n", + "\n", + " if (x > 0) {\n", + " if (y > 0) {\n", + " System.out.println(\"Both x and y are positive.\");\n", + " } else {\n", + " System.out.println(\"x is positive, but y is not.\");\n", + " }\n", + " } else {\n", + " System.out.println(\"x is not positive.\");\n", + " }\n", + " }\n", + "}\n", + "Nested.main()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Compound Boolean Expressions:\n", + "\n", + "Compound boolean expressions involve using _______LOGICAL_____ operators like ``&& (and)`` and ``|| (or)`` to combine multiple conditions." + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "You are an adult student.\n" + ] + } + ], + "source": [ + "public class Compound {\n", + " public static void main(){\n", + " int age = 25;\n", + " boolean isStudent = true;\n", + "\n", + " if (age >= 18 && isStudent) {\n", + " System.out.println(\"You are an adult student.\");\n", + " } else if (age >= 18 || isStudent) {\n", + " System.out.println(\"You are either an adult or a student.\");\n", + " } else {\n", + " System.out.println(\"You are neither an adult nor a student.\");\n", + " }\n", + " }\n", + "}\n", + "Compound.main()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Short-Circuited Evaluation:\n", + "Short-circuited evaluation is an _______OPTIMIZATION_____ technique where the second condition in a ``compound expression is only evaluated if the first condition is true (for &&) or false (for ||).``" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "This will be printed.\n" + ] + } + ], + "source": [ + "public class Short {\n", + " public static void main() {\n", + " boolean condition1 = true;\n", + " boolean condition2 = false;\n", + "\n", + " if (condition1 || condition2) {\n", + " System.out.println(\"This will be printed.\");\n", + " }\n", + " }\n", + "}\n", + "\n", + "Short.main()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Coding Practice\n", + "Calculate the final grade based on the following criteria:\n", + "- If the student didn't complete homework, the grade is automatically \"F.\"\n", + "- If the student completed homework and the average of midterm and final exam scores is >= 70, the grade is \"Pass.\"\n", + "- Otherwise, the grade is \"Fail.\"" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Enter your midterm score (0-100): \n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Enter your final exam score (0-100): \n", + "Did you complete the homework (yes/no): \n", + "\n", + "Your final grade is: Pass\n" + ] + } + ], + "source": [ + "import java.util.Scanner;\n", + "\n", + "public class GradeCalculator {\n", + " public static void main(String[] args) {\n", + " Scanner scanner = new Scanner(System.in);\n", + "\n", + " System.out.print(\"Enter your midterm score (0-100): \\n\");\n", + " int midtermScore = scanner.nextInt();\n", + "\n", + " System.out.print(\"Enter your final exam score (0-100): \\n\");\n", + " int finalExamScore = scanner.nextInt();\n", + "\n", + " System.out.print(\"Did you complete the homework (yes/no): \\n\");\n", + " String homeworkComplete = scanner.next().toLowerCase();\n", + "\n", + " String grade; // Declare the 'grade' variable outside of if-else block\n", + "\n", + " if (homeworkComplete.equals(\"yes\") && (midtermScore + finalExamScore) / 2 >= 60) {\n", + " grade = \"Pass\";\n", + " } else {\n", + " grade = \"Fail\";\n", + " }\n", + "\n", + " System.out.println(\"\\nYour final grade is: \" + grade);\n", + "\n", + " scanner.close();\n", + " }\n", + "}\n", + "GradeCalculator.main(null)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 3.6\n", + "\n", + "### Learning Objective\n", + "- Compare and contrast equivalent Boolean expressions\n", + "\n", + "De Morgan’s Law\n", + "- Augustus De Morgan was a 19th century mathematician whose laws or rules about _______boolean_____ logic allow us to simplify expressions when they are negated\n", + "Given two Boolean variables a and b:\n", + "\n", + "``De Morgan's Law provides a set of rules for negating complex boolean expressions. ``\n", + "\n", + "Example:\n", + "\n", + "Using ``&&`` operators:\n", + "\n", + "![image](https://github.com/Firestorm0986/frontend-proj/assets/108041389/e02209c1-c2f5-4dab-8106-6f97824d5322)\n", + "\n", + "Using ``||`` operator:\n", + "\n", + "![image](https://github.com/Firestorm0986/frontend-proj/assets/108041389/beb4e917-03c2-4709-96f9-88981ee69812)\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### More:\n", + "\n", + "- !(x > 0) → (x <= 0)\n", + "- Distributing a “not” with a boolean expression “flips” the relational operator to the opposite relational operator\n", + " - !(x < 0) → (x >= 0)\n", + " - !(x >= 0) → (x < 0)\n", + " - !(x == 0) → (x != 0)\n", + " - ! (x != 0) → ( x == 0) \n", + "\n", + "\n", + "#### A bit more complex:\n", + "![image](https://github.com/Firestorm0986/frontend-proj/assets/108041389/1fa9c9c3-db17-443c-94cc-0be8e6e62436)\n", + "\n", + "#### Proving the law using tables\n", + "![image](https://github.com/Firestorm0986/frontend-proj/assets/108041389/cd135d80-df08-442b-aa73-35e8afbef96b)" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Are the expressions equivalent? true\n" + ] + } + ], + "source": [ + "public class Example {\n", + " public static void main(){\n", + " boolean x = true;\n", + " boolean y = false;\n", + "\n", + " // Original expression\n", + " boolean originalExp = !(x && y);\n", + "\n", + " // Applying De Morgan's Law\n", + " boolean equivalentExp = !x || !y;\n", + "\n", + " // Checking if the results are equivalent\n", + " System.out.println(\"Are the expressions equivalent? \" + (originalExp == equivalentExp));\n", + "\n", + " }\n", + "}\n", + "Example.main()" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Are the expressions equivalent? true\n" + ] + } + ], + "source": [ + "public class Example2 {\n", + " public static void main(){\n", + " boolean p = true;\n", + " boolean q = true;\n", + "\n", + " // Original expression\n", + " boolean originalExp2 = !(p || q);\n", + "\n", + " // Applying De Morgan's Law\n", + " boolean equivalentExp2 = !p && !q;\n", + "\n", + " // Checking if the results are equivalent\n", + " System.out.println(\"Are the expressions equivalent? \" + (originalExp2 == equivalentExp2));\n", + " }\n", + "}\n", + "\n", + "Example2.main()" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Are the expressions equivalent? true\n" + ] + } + ], + "source": [ + "public class Example3 {\n", + " public static void main(){\n", + " boolean a = true;\n", + " boolean b = false;\n", + " boolean c = true;\n", + "\n", + " // Original expression\n", + " boolean originalExp3 = !(a && b) || (c || !b);\n", + "\n", + " // Applying De Morgan's Law\n", + " boolean equivalentExp3 = (!a || !b) || (c || b);\n", + "\n", + " // Checking if the results are equivalent\n", + " System.out.println(\"Are the expressions equivalent? \" + (originalExp3 == equivalentExp3));\n", + "\n", + " }\n", + "}\n", + "\n", + "Example3.main()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### De Morgan's Law Practice\n", + "\n", + "Negate the following expressions:\n", + "\n", + "``1. !(A || B)``\n", + "\n", + "ANSWER: ``(!A && !B)``\n", + "\n", + "``2. (!A || !B && !C)``\n", + "\n", + "ANSWER: ``(!A && !B) (!A || !C)``\n", + "\n", + "``3. (!A && (!B || !C))``\n", + "\n", + "ANSWER: ``(!A || !B) (!A && !C)``" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 3.7\n", + "\n", + "### Learning Objective\n", + "- Compare object reference using boolean expressions in program code\n", + "\n", + "![image](https://github.com/Ishi-Singh/Fastpages/assets/82348259/40517c16-2f13-460c-89ea-f8f53a0a7a34)\n", + "\n", + "An if statement using == to compare myHouse and momsHouse will be true but false for myHouse and annasHouse because the objects are not the same even though they have same parameters. This means that == will only return true if it is the same object, not a reference or copy of that object. " + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "true\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "false\n", + "true\n", + "false\n" + ] + } + ], + "source": [ + "String a = \"Hello\";\n", + "String b = \"Hello\";\n", + "String c = a;\n", + "String d = new String(\"Hello\");\n", + "\n", + "System.out.println(a == c);\n", + "System.out.println(d == b);\n", + "System.out.println(a == b);\n", + "System.out.println(a == d);" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "![image](https://github.com/Ishi-Singh/Fastpages/assets/82348259/998e721e-1c5e-41a7-9799-13cfdee14ee2)\n", + "\n", + "When you want to compare objects you can use the .equal() method, it will return true if the objects have the same attributes even if they aren't identical." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "true\n", + "true\n", + "true\n", + "true\n" + ] + } + ], + "source": [ + "String a = \"Hello\";\n", + "String b = \"Hello\";\n", + "String c = a;\n", + "String d = new String(\"Hello\");\n", + "\n", + "System.out.println(a.equals(c));\n", + "System.out.println(d.equals(b));\n", + "System.out.println(a.equals(b));\n", + "System.out.println(a.equals(d));" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Hacks \n", + "\n", + "- Complete popcorn hacks - 0.1 points\n", + "- Coding hacks - 0.8 points\n", + " - Complexity: 0.4 points\n", + " - Functionality: 0.4 points" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Coding Practice\n", + "\n", + "Create a program that validates a user's password based on the following criteria:\n", + "\n", + "1. The password must be at least 8 characters long.\n", + "2. The password must contain at least one uppercase letter.\n", + "3. The password must contain at least one lowercase letter.\n", + "4. The password must contain at least one digit (0-9).\n", + "5. The password must contain at least one special character (!, @, #, $, %, ^, &, *).\n", + "\n", + "Write a Java program that prompts the user to enter a password and then checks if it meets the above criteria. If the password meets all the criteria, print \"Password is valid.\" If not, print a message indicating which criteria the password fails to meet.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# USER PASSWORD VALIDATION PROGRAM (HACKS)" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Enter your password: Your password must be at least 8 characters long.\n", + "Your password must contain at least one uppercase letter.\n", + "Your password must contain at least one digit.\n", + "Your password must contain at least one special character (!, @, #, $, %, ^, &, *).\n", + "Password is invalid.\n" + ] + } + ], + "source": [ + "import java.util.Scanner;\n", + "\n", + "public class Verify {\n", + "\n", + " // This method retrieves the user's password input from the console.\n", + " public static String userPasswordinput() {\n", + " Scanner sc = new Scanner(System.in);\n", + " System.out.print(\"Enter your password: \");\n", + " String userPassword = sc.nextLine();\n", + " return userPassword;\n", + " }\n", + "\n", + " // This method checks if the provided password meets certain criteria.\n", + " public static boolean userPasswordcheck(String userPassword) {\n", + " // Initialize boolean variables to track different criteria.\n", + " boolean lengthValid = userPassword.length() >= 8;\n", + " boolean uppercaseValid = false;\n", + " boolean lowercaseValid = false;\n", + " boolean digitValid = false;\n", + " boolean specialCharValid = false;\n", + "\n", + " // Iterate through each character in the user's password.\n", + " for (int i = 0; i < userPassword.length(); i++) {\n", + " char c = userPassword.charAt(i);\n", + "\n", + " // Check if the character is an uppercase letter.\n", + " if (Character.isUpperCase(c)) {\n", + " uppercaseValid = true;\n", + " }\n", + " // Check if the character is a lowercase letter.\n", + " else if (Character.isLowerCase(c)) {\n", + " lowercaseValid = true;\n", + " }\n", + " // Check if the character is a digit.\n", + " else if (Character.isDigit(c)) {\n", + " digitValid = true;\n", + " }\n", + " // Check if the character is a special character.\n", + " else if (\"!@#$%^&*\".contains(String.valueOf(c))) {\n", + " specialCharValid = true;\n", + " }\n", + " }\n", + "\n", + " // Check if all criteria are met.\n", + " if (lengthValid && uppercaseValid && lowercaseValid && digitValid && specialCharValid) {\n", + " return true; // Password is valid.\n", + " } else {\n", + " // Print error messages for criteria that are not met.\n", + " if (!lengthValid) {\n", + " System.out.println(\"Your password must be at least 8 characters long.\");\n", + " }\n", + " if (!uppercaseValid) {\n", + " System.out.println(\"Your password must contain at least one uppercase letter.\");\n", + " }\n", + " if (!lowercaseValid) {\n", + " System.out.println(\"Your password must contain at least one lowercase letter.\");\n", + " }\n", + " if (!digitValid) {\n", + " System.out.println(\"Your password must contain at least one digit.\");\n", + " }\n", + " if (!specialCharValid) {\n", + " System.out.println(\"Your password must contain at least one special character (!, @, #, $, %, ^, &, *).\");\n", + " }\n", + " return false; // Password is invalid.\n", + " }\n", + " }\n", + "\n", + " public static void main(String[] args) {\n", + " // Get the user's password input.\n", + " String userPassword = userPasswordinput();\n", + "\n", + " // Check if the password is valid and provide feedback.\n", + " if (userPasswordcheck(userPassword)) {\n", + " System.out.println(\"Password is valid!\");\n", + " System.out.println(\"Your password is: \" + userPassword);\n", + " } else {\n", + " System.out.println(\"Password is invalid.\");\n", + " }\n", + " }\n", + "}\n", + "\n", + "\n", + "\n", + "Verify.main(null);" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Java", + "language": "java", + "name": "java" + }, + "language_info": { + "codemirror_mode": "java", + "file_extension": ".jshell", + "mimetype": "text/x-java-source", + "name": "java", + "pygments_lexer": "java", + "version": "20.0.2+9" + }, + "orig_nbformat": 4 + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/_notebooks/2023-10-12-Unit4Lesson.ipynb b/_notebooks/2023-10-12-Unit4Lesson.ipynb new file mode 100755 index 0000000..ba72527 --- /dev/null +++ b/_notebooks/2023-10-12-Unit4Lesson.ipynb @@ -0,0 +1,1134 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "layout: post\n", + "title: Unit 4 Lesson\n", + "toc: true\n", + "comments: true\n", + "description: Lesson for APCSA Unit 4\n", + "courses: { compsci: {week: 0} }\n", + "type: tangibles\n", + "---" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Iteration\n", + "According to CollegeBoard, **Iteration** is a way to simplify code that would otherwise be repeated many times in succession. Using loops, we can finally implement complex algorithms and solutions to common problems that we weren't able to before.\n", + "\n", + "Iteration is repeating sequences to simplify code of advanced algorithms\n", + "\n", + "Iteration accounts for **17.5%-22.5%** of the APCSA AP Exam" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# 4.1: WHILE LOOPS\n", + "**Learning Objective**: Represent Iterative Processes using a while loop\n", + "\n", + "Question: What is a loop and what are some real life examples of this (Setting a Song to repeat on your music player)\n", + "\n", + "You know the i variable that you use for while/for loops? It actually has a name, loop control variable" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "int i = 0; // initialize loop control variable\n", + "while (i < 10) // checks the loop control variable\n", + "{\n", + " System.out.println(\"Doing some code\");\n", + " i++; // update the loop control variable\n", + "}" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0\n", + "1\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "2\n", + "3\n", + "4\n", + "0\n", + "1\n", + "2\n", + "3\n", + "4\n" + ] + } + ], + "source": [ + "// Popcorn Hack: Simplify the code segment below\n", + "int i = 0;\n", + "System.out.println(i);\n", + "i++;\n", + "System.out.println(i);\n", + "i++;\n", + "System.out.println(i);\n", + "i++;\n", + "System.out.println(i);\n", + "i++;\n", + "System.out.println(i);\n", + "i++;\n", + "\n", + "while (i < 5) {\n", + " System.out.println(i);\n", + " i++; \n", + "}\n", + "\n", + "for (int j = 0; j < 5; j++) {\n", + " System.out.println(j);\n", + "}" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "int i = 0;\n", + "while (i < 5) { System.out.println(i);\n", + "i++;\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Infinite loop \n", + "An infinite loop is when a while loop always evaluates to true. avoid this when you can because it's probably not good for your computer. if this happens by accident, I recommend copying all code in the block and deleting the block. After you delete the code block, close and reopen the tab that the code block was in.\n", + "\n", + "**What's wrong with this code block?**" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "while (true)\n", + "{\n", + " System.out.print(\"CONTROL \");\n", + "}\n", + "// DO NOT RUN THE CODE" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Do While loop\n", + " \n", + "**What will this code block output?**" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Quite shrimple. " + ] + } + ], + "source": [ + "// Quite shrimple\n", + "int i = 0;\n", + "do \n", + "{\n", + " System.out.print(\"Quite shrimple. \");\n", + " i++;\n", + "}\n", + "while (i < -5);" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In a do while loop, it will run the \"do\" once before it reaches the \"while\", and at that point it will start to act like a while loop." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## For loop\n", + "this is the standard structure of a for loop" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "ename": "CompilationException", + "evalue": "", + "output_type": "error", + "traceback": [ + "\u001b[1m\u001b[30m| \u001b[1m\u001b[30mfor (\u001b[0m\u001b[1m\u001b[30m\u001b[41minitialization\u001b[0m\u001b[1m\u001b[30m; Boolean expression; update)\u001b[0m", + "\u001b[1m\u001b[31mnot a statement\u001b[0m", + "", + "\u001b[1m\u001b[30m| \u001b[1m\u001b[30mfor (initialization; Boolean\u001b[0m\u001b[1m\u001b[30m\u001b[41m\u001b[0m\u001b[1m\u001b[30m expression; update)\u001b[0m", + "\u001b[1m\u001b[31m';' expected\u001b[0m", + "", + "\u001b[1m\u001b[30m| \u001b[1m\u001b[30mfor (initialization; Boolean \u001b[0m\u001b[1m\u001b[30m\u001b[41mexpression\u001b[0m\u001b[1m\u001b[30m; update)\u001b[0m", + "\u001b[1m\u001b[31mnot a statement\u001b[0m", + "", + "\u001b[1m\u001b[30m| \u001b[1m\u001b[30mfor (initialization; Boolean expression\u001b[0m\u001b[1m\u001b[30m\u001b[41m\u001b[0m\u001b[1m\u001b[30m; update)\u001b[0m", + "\u001b[1m\u001b[31m')' expected\u001b[0m", + "" + ] + } + ], + "source": [ + "for (initialization; Boolean expression; update)\n", + "{\n", + " System.out.println(\"Doing some code\");\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Initialization will run at the start of the loop, boolean expression will get checked with every loop, and update runs after every loop.\n", + "\n", + "**How many times will this code print \"Doing some code?\"**" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Doing some code\n", + "Doing some code\n", + "Doing some code\n", + "Doing some code\n", + "Doing some code\n" + ] + } + ], + "source": [ + "for (int num = 1; num <= 5; num++)\n", + "{\n", + " System.out.println(\"Doing some code\");\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In this code, it creates the variable *num* at the start of the loop, it checks if *num* is less than or equal to 5 after each loop, and it adds 1 to *num* after each loop." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Enhanced for loop \n", + "this is essentially a javascript for loop, as it will iterate through a list and run code in the loop to each variable inside the list" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1 4 6 2 " + ] + } + ], + "source": [ + "int[] list = {1, 4, 6, 2};\n", + "for (int j : list)\n", + "{\n", + " System.out.print(j);\n", + " System.out.print(\" \");\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Break and Continue\n", + "In java there are breaks, but there are also continues.\n", + "\n", + "### Break \n", + "Breaks, as you likely already know, end a loop. They tend to be used with an *if* statement\n", + "\n", + "**How many times will this code print \"Big guy?\"**" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Big guy\n", + "Big guy\n", + "Big guy\n", + "Big guy\n", + "Big guy\n" + ] + } + ], + "source": [ + "int i = 0; \n", + "while (i < 10) \n", + "{\n", + " System.out.println(\"Big guy\");\n", + " i++; \n", + " if (i == 5) {\n", + " break;\n", + " }\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Continue \n", + "Continue will skip code for an iteration, but will still keep the loop running" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0\n", + "1\n", + "2\n", + "3\n", + "4\n", + "\n", + "6\n", + "7\n", + "8\n", + "9\n" + ] + } + ], + "source": [ + "int i = 0; \n", + "while (i < 10) \n", + "{\n", + " if (i == 5) {\n", + " i++; // don't forget this, it creates an error similar to an infinite loop\n", + " System.out.println(\"\");\n", + " continue;\n", + " }\n", + " System.out.println(i);\n", + " i++; \n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# 4.3: Developing Algorithms Using Strings\n", + "**Learning Objective**: For algorithms in the context of a particular specification that involves String objects:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Methods in Java that help to MANIPULATE STRINGS\n", + "- String.substring - Retrieves a particular portion of a String\n", + "- String.equals - Comparees the content of two strings\n", + "- String.length - Returns the length of a String" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Common Prefix: C\n", + "Common Prefix: Co\n", + "Common Prefix: Cod\n", + "Common Prefix: Codi\n", + "Common Prefix: Codin\n", + "Common Prefix: Coding\n", + "Common Prefix: Coding \n", + "Common Prefix: Coding i\n", + "Common Prefix: Coding is\n", + "Common Prefix: Coding is \n", + "Common Prefix: Coding is c\n", + "Common Prefix: Coding is co\n" + ] + } + ], + "source": [ + "public class Compare {\n", + " public static void main(String[] args) {\n", + " String string1 = \"Coding is cool!\";\n", + " String string2 = \"Coding is coding!\";\n", + "\n", + " int minLength = Math.min(string1.length(), string2.length());\n", + "\n", + " for (int i = 0; i < minLength; i++) {\n", + " String subString1 = string1.substring(0, i + 1);\n", + " String subString2 = string2.substring(0, i + 1);\n", + "\n", + " if (subString1.equals(subString2)) {\n", + " System.out.println(\"Common Prefix: \" + subString2);\n", + " }\n", + " }\n", + " }\n", + "}\n", + "Compare.main(null)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Where are the 3 methods in the above Java Cell and how do they contribute to the program's functionality?**\n", + "\n", + "# answer\n", + "string.length() is used to determine the length of the string, for use with the math.min\n", + "\n", + "string.substring is used to return a substring of the string, here its used for the common prefix\n", + "\n", + "math.min is used to return the smaller of two numbers, here its used to determine the length of the 2 strings and then determine the common prefix" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "The Number of vowels in \"supercalifragilisticexpialidocious\" is 16\n" + ] + } + ], + "source": [ + "String word = \"supercalifragilisticexpialidocious\";\n", + "int count = 0;\n", + "\n", + "for (int i = 0; i < word.length(); i++) {\n", + " char letter = word.charAt(i);\n", + " if (letter == 'a' || letter == 'e' || letter == 'i' || letter == 'o' || letter == 'u') {\n", + " count++;\n", + " }\n", + "}\n", + "\n", + "System.out.println(\"The Number of vowels in \\\"\" + word + \"\\\" is \" + count);\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**What does word.length() do and how do we use it above?** \n", + "\n", + "### Answer:\n", + "\n", + "word.length() returns the length of the word. its 1 based counting.\n", + "\n", + "**What Boolean Operator is used?**\n", + "\n", + "### Answer:\n", + "\n", + "we use && for and and || for or." + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "We found the Smaller String!\n" + ] + } + ], + "source": [ + "public class Main {\n", + " public static void main(String[] args) {\n", + " String word = \"Scooby Doo\";\n", + " String sub = \"Doo\";\n", + " boolean found = false;\n", + "\n", + " for (int i = 0; i <= word.length() - sub.length(); i++) {\n", + " String portion = word.substring(i, i + sub.length());\n", + " if (portion.equals(sub)) {\n", + " found = true;\n", + " }\n", + " }\n", + " if (found) {\n", + " System.out.println(\"We found the Smaller String!\");\n", + " } else {\n", + " System.out.println(\"We did not find the Smaller String! \\t Ruh Roh!\");\n", + " }\n", + " }\n", + "}\n", + "Main.main(null)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### String concatenation\n", + "String concatenation is when you want to add to strings together" + ] + }, + { + "cell_type": "code", + "execution_count": 47, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Original String: String\n", + "Reversed String: gnirtS\n" + ] + } + ], + "source": [ + "String original = \"String\";\n", + "String reversed = \"\";\n", + "for (int i = 0; i < original.length(); i++)\n", + "{\n", + " String single = original.substring(i,i+1);\n", + " reversed = single + reversed;\n", + "}\n", + "System.out.println(\"Original String: \" + original);\n", + "System.out.println(\"Reversed String: \" + reversed);\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# 4.4: Nested Iteration\n", + "**Learning Objective**: Represent nested iteration processes\n", + "\n", + "Essential Knowledge:\n", + "- Nested iteration is when an iteration statement appears inside the body of another iteration statement\n", + "- The inner loop must complete all of its iterations before the outer loop can continue. \n", + "\n", + "**Before uncommenting the code, guess what the output will look like:**\n", + "\n", + "\n", + "we print 1 and 2, 4 times " + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1 2 \n", + "1 2 \n", + "1 2 \n", + "1 2 \n" + ] + } + ], + "source": [ + "public class NestedLoops{\n", + "\n", + " public static void main(String[] args){\n", + "\n", + " for (int outer = 1; outer < 5; outer++){\n", + "\n", + " for (int inner = 1; inner < 3; inner++){\n", + " \n", + " System.out.print(inner + \" \");\n", + " }\n", + "\n", + " System.out.println();\n", + "\n", + " } \n", + "\n", + " }\n", + "}\n", + "\n", + "NestedLoops.main(null)" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1 1 1 1 \n", + "2 2 2 2 \n" + ] + } + ], + "source": [ + "public class NestedLoops{\n", + "\n", + " public static void main(String[] args){\n", + " for ( int inner = 1; inner < 3; inner++){\n", + "\n", + " for (int outer = 1; outer < 5; outer++){\n", + " \n", + " System.out.print(inner + \" \");\n", + " }\n", + "\n", + " System.out.println();\n", + "\n", + " } \n", + "\n", + " }\n", + "}\n", + "\n", + "NestedLoops.main(null)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**What will the output of the code above be if we switch the loop headers (the stuff inside of the for loop)?**\n", + "\n", + "we print 4, 5 instead, 4 times \n", + "\n", + "**After making a prediction actually switch the loop headers for yourself. What do you notice about the output compared to the output before the change?**\n", + "\n", + "I was wrong, its instead printing it 1 4 times then 2 4 times, instead of 1 and 2 4 times." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# 4.5: Informal Code Analysis\n", + "\n", + "Essential Knowledge:\n", + "- A statement exectution count indicates the number of times a statement is executed by the program\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": {}, + "outputs": [], + "source": [ + "for (int outer = 0; outer < 3; outer++){\n", + " for (int inner = 0; inner < 4; inner++){\n", + " // statement #1\n", + " }\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**In the code above, how many times will the inner loop execute when outer = 0?** __3__\n", + "\n", + "**In the code above, how many times will the inner loop execute when outer = 1?** __2__ \n", + "\n", + "**In the code above, how many times will the inner loop execute when outer = 2?** __1__ \n", + "\n", + "**In the code above, how many times will the inner loop execute in total?** __4___\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "for (int outer = 5; outer > 0; outer--){\n", + " for (int inner = 0; inner < outer; inner++){\n", + " // statement #1\n", + " }\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**In the code above, how many times will the inner loop execute when outer = 5?** __5__ \n", + "\n", + "**In the code above, how many times will the inner loop execute when outer = 4?** __4__ \n", + "\n", + "**In the code above, how many times will the inner loop execute when outer = 3?** __3__ \n", + "\n", + "**In the code above, how many times will the inner loop execute in total?** __15__" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": {}, + "outputs": [], + "source": [ + "int k = 0;\n", + "while (k < 5){\n", + " int x = (int)(Math.random()*6) + 1;\n", + " while (x != 6){\n", + " //statement #1\n", + " x = (int)(Math.random()*6) + 1;\n", + " }\n", + " k++;\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**In the code above, how many times will the statement #1 execute?** __random b/c math.random__" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "05101520253035404550556065707580859095100105110115120125130" + ] + } + ], + "source": [ + "for (int k = 0; k < 135; k++){\n", + " if (k % 5 == 0){ // Statement #1\n", + " System.out.print(k); // Statement #2\n", + " }\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**In the code above, how many times will the statement #1 execute?** __135__ \n", + "\n", + "**In the code above, how many times will the statement #2 execute?** __27__\n", + "\n", + "Rewrite the code above to be more effecient based on execution count. \n" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0055101015152020252530303535404045455050555560606565707075758080858590909595100100105105110110115115120120125125130130" + ] + } + ], + "source": [ + "for (int k = 0; k < 135; k+= 5){ //+= 5 optimizes code \n", + " if (k % 5 == 0){ // Statement #1\n", + " System.out.print(k); // Statement #2\n", + " }\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# HACKS\n", + "These hacks will be due on Monday (October 16th) before class" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Hacks\n", + "- Finish the popcorn hacks (0.2)\n", + "- Rewrite the for loop (0.25)\n", + "- Complete the Ceaser Cipher Code (0.45)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "for (int k = 0; k < 40; k++){\n", + " if (k % 4 == 0){\n", + " System.out.println(k); \n", + " }\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Rewrite the code above 3 different times\n", + "- Your code should be more efficient based execution count\n", + "- Your code should use 3 different types of loops that you learned above (Hint: You may need to use a list)\n", + "\n", + "\n", + "\n", + "# TOP CODE REWRITE 1\n" + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0\n", + "4\n", + "8\n", + "12\n", + "16\n", + "20\n", + "24\n", + "28\n", + "32\n", + "36\n" + ] + } + ], + "source": [ + "\n", + "for (int k = 0; k < 40; k+= 4){ // adding += 4 instead of k++ to reduce the number of times the loop runs\n", + " if (k % 4 == 0){\n", + " System.out.println(k); \n", + " }\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# TOP CODE REWRITE 2" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0\n", + "4\n", + "8\n", + "12\n", + "16\n", + "20\n", + "24\n", + "28\n", + "32\n", + "36\n" + ] + } + ], + "source": [ + "int k = 0;\n", + "\n", + "// this time we use a while loop instead of a for loop\n", + "while (k < 40) {\n", + " if (k % 4 == 0){\n", + " System.out.println(k);\n", + " }\n", + " k+= 4;\n", + "}\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# TOP CODE REWRITE 3" + ] + }, + { + "cell_type": "code", + "execution_count": 43, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0 4 8 12 16 20 24 28 32 36 " + ] + } + ], + "source": [ + "int[] multiplesOfFour = new int[10]; // Array size is adjusted to fit multiples of 4 up to 36.\n", + "\n", + "int value = 0;\n", + "for (int i = 0; i < multiplesOfFour.length; i++) {\n", + " multiplesOfFour[i] = value;\n", + " value += 4;\n", + "}\n", + "\n", + "for (int multiple : multiplesOfFour) {\n", + " System.out.print(multiple + \" \");\n", + "}\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# TOP CODE REWRITE 4" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0\n", + "4\n", + "8\n", + "12\n", + "16\n", + "20\n", + "24\n", + "28\n", + "32\n", + "36\n" + ] + } + ], + "source": [ + "int k = 0; // this time we use a do while loop instead of a while loop or a for loop\n", + "do {\n", + " if (k % 4 == 0) {\n", + " System.out.println(k);\n", + " }\n", + " k += 4;\n", + "} while (k < 40);\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Ceaser Cipher Hacks\n", + "Try to write a cipher program that shifts each letter in a message 3 letters forward. Use any of the methods you learned today. Use it to decode the 3 messages we've given you!" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [], + "source": [ + "public class CaesarCipher {\n", + "\n", + " public static void main(String[] args) {\n", + "\n", + " String[] letters = {\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\"};\n", + " String message1 = \"Kfzb gly!\";\n", + " String message2 = \"zlab zlab zlab\";\n", + " String message3 = \"prmbozxifcoxdfifpqfzbumfxifalzflrp\";\n", + "\n", + " String msg1mod =\"\";\n", + "\n", + "}\n", + "}\n", + "\n", + "\n", + "\n", + "CaesarCipher.main(null);" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# ANSWER" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Nice job!\n", + "code code code\n", + "supercalifragilisticexpialidocious\n" + ] + } + ], + "source": [ + "public class CaesarCipher {\n", + "\n", + " public static void main(String[] args) {\n", + "\n", + " String message1 = \"Kfzb gly!\";\n", + " String msg1mod = \"\";\n", + " String message2 = \"zlab zlab zlab\";\n", + " String msg2mod = \"\";\n", + " String message3 = \"prmbozxifcoxdfifpqfzbumfxifalzflrp\";\n", + " String msg3mod = \"\";\n", + "\n", + " for (int i = 0; i < message1.length(); i++) {\n", + " char letter = message1.charAt(i);\n", + "\n", + " if (Character.isLetter(letter)) {\n", + " char baseChar = Character.isUpperCase(letter) ? 'A' : 'a'; // Determine the base character ('A' for uppercase, 'a' for lowercase)\n", + " char shiftedLetter = (char) (((letter - baseChar + 3) % 26) + baseChar); // Shift the letter by 3 positions\n", + " msg1mod += shiftedLetter;\n", + " } else {\n", + " msg1mod += letter; // Keep non-letter characters as they are\n", + " }\n", + " }\n", + "\n", + " for (int i = 0; i < message2.length(); i++) {\n", + " char letter2 = message2.charAt(i);\n", + "\n", + " if (Character.isLetter(letter2)) {\n", + " char baseChar = Character.isUpperCase(letter2) ? 'A' : 'a'; // Determine the base character ('A' for uppercase, 'a' for lowercase)\n", + " char shiftedLetter = (char) (((letter2 - baseChar + 3) % 26) + baseChar); // Shift the letter by 3 positions\n", + " msg2mod += shiftedLetter;\n", + " } else {\n", + " msg2mod += letter2; // Keep non-letter characters as they are\n", + " }\n", + " }\n", + "\n", + " \n", + " for (int i = 0; i < message3.length(); i++) {\n", + " char letter = message3.charAt(i);\n", + "\n", + " if (Character.isLetter(letter)) {\n", + " char baseChar = Character.isUpperCase(letter) ? 'A' : 'a'; // Determine the base character ('A' for uppercase, 'a' for lowercase)\n", + " char shiftedLetter = (char) (((letter - baseChar + 3) % 26) + baseChar); // Shift the letter by 3 positions\n", + " msg3mod += shiftedLetter;\n", + " } else {\n", + " msg3mod += letter; // Keep non-letter characters as they are\n", + " }\n", + " }\n", + "\n", + " System.out.println(msg1mod);\n", + " System.out.println(msg2mod);\n", + " System.out.println(msg3mod);\n", + "\n", + " }\n", + "}\n", + "\n", + "CaesarCipher.main(null);" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Java", + "language": "java", + "name": "java" + }, + "language_info": { + "codemirror_mode": "java", + "file_extension": ".jshell", + "mimetype": "text/x-java-source", + "name": "java", + "pygments_lexer": "java", + "version": "20.0.2+9" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/_notebooks/2023-10-14-unit5lastpart.ipynb b/_notebooks/2023-10-14-unit5lastpart.ipynb new file mode 100755 index 0000000..47927b7 --- /dev/null +++ b/_notebooks/2023-10-14-unit5lastpart.ipynb @@ -0,0 +1,164 @@ +{ + "cells": [ + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "toc: true\n", + "comments: true\n", + "layout: post\n", + "title: Topics 5.9-5.10\n", + "courses: { compsci: {week: 0} }\n", + "type: tangibles\n", + "---" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 5.9 this Keyword" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## KEY LEARNING OBJECTIVE" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Evaluate object reference expressions that use the keyword **this**." + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The keyword \"this\" is utilized in Java to refer to the current instance of a class. In other words, it helps to clarify what variable you're referring to within the instance." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "public class MyClass {\n", + " private int value;\n", + "\n", + " public void setValue(int value) {\n", + " this.value = value; // 'this' refers to the instance variable\n", + " }\n", + "}\n" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "QUESTION: **How can you use 'this' to call a constructor?**\n", + "\n", + "ANSWER: using this allows us to create objects of a class, then we can call the constructor to initialize/change those objects. " + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 5.10 Ethical and Social Implications of Computing Systems" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# KEY LEARNING OBJECTIVE" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Explain the ethical and social implications of computing systems." + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Components of Ethical Implications**:\n", + "\n", + "1. Legal issues and intellectual __property___ are big concerns in program creation. Licensing open source software is a big issue, as it dictates how programmers need to comply with terms and how software can be distributed and used.\n", + "\n", + "\n", + "2. Data privacy is also a big issue. There are many data protection laws that programmers need to ensure that their code complies with, especially if their program works with data collection and processing." + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Components of Social Implications**:\n", + "\n", + "1. There can be harmful impacts from software - malicious software can pose significant ___security____ ____risks_____.\n", + "\n", + "\n", + "2. Software has transformed how people communicate, access information, and interact with each other. Social media platforms, for example, have changed the way society discusses issues, while algorithms can create filter bubbles that limit exposure to diverse opinions." + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**POPCORN HACKS: (0.2)**" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Write a two sentence reflection on the social and ethical implications of programming. (0.8)**\n", + "\n", + "# reflection \n", + "Programming is pretty damn powerful, and people have made lots of good and bad programs. Its pretty important that programming remains ethical and safe, to \n", + "ensure that people don't get scammed or the tech-illiterate are not taken advantage of when they dive into the world of tech and programming. " + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Java", + "language": "java", + "name": "java" + }, + "language_info": { + "codemirror_mode": "java", + "file_extension": ".jshell", + "mimetype": "text/x-java-source", + "name": "java", + "pygments_lexer": "java", + "version": "20.0.2+9" + }, + "orig_nbformat": 4 + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/_notebooks/2023-10-14-unit5secondpart.ipynb b/_notebooks/2023-10-14-unit5secondpart.ipynb new file mode 100755 index 0000000..e7c6956 --- /dev/null +++ b/_notebooks/2023-10-14-unit5secondpart.ipynb @@ -0,0 +1,907 @@ +{ + "cells": [ + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "toc: true\n", + "comments: true\n", + "layout: post\n", + "title: Topics 5.4-5.8\n", + "courses: { compsci: {week: 0} }\n", + "type: tangibles\n", + "---" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Topic 5.4: Accessor Methods\n", + "\n", + "In Java, classes serve as blueprints for creating objects. These classes can encapsulate attributes (fields) and behaviors (methods). One of the cornerstones of Object-Oriented Programming is **data encapsulation**. This principle restricts direct access to some of an object's components, ensuring data integrity and security. Accessor methods, colloquially known as \"getters\", offer a controlled means to access these attributes.\n", + "\n", + "## Accessor Methods\n", + "\n", + "An **Accessor Method** permits other objects to retrieve the value of instance or static variables. They are typically non-void methods without parameters that return a value.\n", + "\n", + "For instance, consider a class `Circle`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "public class Circle {\n", + " private double radius;\n", + "\n", + " public Circle(double r) {\n", + " this.radius = r;\n", + " }\n", + "\n", + " // Accessor method for radius\n", + " public double getRadius() {\n", + " return radius;\n", + " }\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In the code above, the method `getRadius` is an accessor method. It allows external code to retrieve the value of the `radius` attribute without directly accessing the private field. This is a fundamental aspect of data encapsulation, ensuring that the internal state of an object is protected and can only be accessed or modified in controlled ways." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Return by Value\n", + "\n", + "Java employs the \"return by value\" approach for its methods. This implies that when a method returns a value, it's essentially returning a copy of that value. This is especially true for primitive data types." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "public int getIntegerValue() {\n", + " int value = 5;\n", + " return value;\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In the method above, the value `5` is returned, not the variable `value` itself." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Reference Return\n", + "\n", + "For objects, when a method returns an object, it's essentially returning a reference to that object, not a fresh copy. This becomes pivotal when dealing with mutable objects." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [], + "source": [ + "public class Box {\n", + " private ArrayList items;\n", + "\n", + " public Box() {\n", + " items = new ArrayList<>();\n", + " }\n", + "\n", + " public ArrayList getItems() {\n", + " return items;\n", + " }\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "If you append an item to the ArrayList returned by `getItems`, will it modify the original `items` in the `Box` object?\n", + "\n", + "Answer: no, because we only return a reference of the arraylist, not the original arraylist, plus appending items to arraylist needs us to create a new arraylist, so it will not modify the original arraylist." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## `toString` Method\n", + "\n", + "The `toString` method offers a string representation of an object. By default, it returns the class name followed by its memory address. However, it's a common practice to override this method to provide a more descriptive representation." + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Circle with radius: 5.0\n" + ] + } + ], + "source": [ + "public class Circle {\n", + " private double radius;\n", + "\n", + " public Circle(double r) {\n", + " this.radius = r;\n", + " }\n", + "\n", + " @Override\n", + " public String toString() {\n", + " return \"Circle with radius: \" + radius;\n", + " }\n", + "\n", + " public static void main(String[] args) {\n", + " Circle circle = new Circle(5.0);\n", + " System.out.println(circle); // This will implicitly call the toString() method\n", + " }\n", + "}\n", + "\n", + "Circle.main(null);" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Without overriding, what would the default `toString` method return?\n", + "\n", + "Answer: we would still get 5.0 as the result." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Topic 5.5: Mutator Methods\n", + "\n", + "Mutator methods, often referred to as \"setters\", play a crucial role in object-oriented programming. They allow controlled modification of an object's state. While accessor methods (\"getters\") retrieve the state of an object, mutator methods modify it.\n", + "\n", + "## Void Methods\n", + "\n", + "A **void method** does not return any value. Instead, its primary purpose is to perform an action. The keyword `void` in the method's header signifies that the method won't return any value." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Hello, World!\n" + ] + } + ], + "source": [ + "public class exampleVoid {\n", + " public void displayMessage() {\n", + " System.out.println(\"Hello, World!\");\n", + " }\n", + "\n", + " public static void main(String[] args) {\n", + " exampleVoid example = new exampleVoid();\n", + " example.displayMessage();\n", + " }\n", + "}\n", + "\n", + "exampleVoid.main(null);" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In the example above, the `displayMessage` method doesn't return any value; it simply prints a message to the console.\n", + "\n", + "## Mutator (Modifier) Methods\n", + "\n", + "A **mutator method** is typically a void method that alters the values of instance or static variables. These methods ensure that the internal state of an object can be changed in a controlled manner, adhering to the principles of data encapsulation and data integrity.\n", + "\n", + "Consider a class `Rectangle`:" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [], + "source": [ + "public class Rectangle {\n", + " private double length;\n", + " private double width;\n", + "\n", + " // Mutator method for length\n", + " public void setLength(double length) {\n", + " if (length > 0) {\n", + " this.length = length;\n", + " } else {\n", + " System.out.println(\"Invalid length provided.\");\n", + " }\n", + " }\n", + "\n", + " // Mutator method for width\n", + " public void setWidth(double width) {\n", + " if (width > 0) {\n", + " this.width = width;\n", + " } else {\n", + " System.out.println(\"Invalid width provided.\");\n", + " }\n", + " }\n", + "\n", + "\n", + "\n", + " \n", + " public static void main(String[] args) {\n", + " Rectangle rect = new Rectangle();\n", + " rect.setLength(5);\n", + " rect.setWidth(-3);\n", + " }\n", + "}\n", + "\n", + "Rectangle.main(null);" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In the `Rectangle` class, the methods `setLength` and `setWidth` are mutator methods. They allow the modification of the `length` and `width` attributes, respectively, while ensuring that only valid values are set.\n", + "\n", + "Suppose you add another method to the `Rectangle` class called `setDimensions` which takes a single string parameter in the format \"length,width\" (e.g., \"10,5\"). This method should parse the string, validate the values, and then set the `length` and `width` accordingly. If the string is in an invalid format or contains negative values, it should print an error message. Can you draft this method?" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Length: 5.5\n", + "Width: 4.2\n" + ] + } + ], + "source": [ + "public class Dimensions {\n", + " public String dimensions_str = \"10,10\";\n", + " public float length;\n", + " public float width;\n", + "\n", + " public void setDimensions(String dimensions) {\n", + " String[] dimensionParts = dimensions.split(\",\");\n", + "\n", + " if (dimensionParts.length == 2) { // Check if there are two parts\n", + " try {\n", + " float length = Float.parseFloat(dimensionParts[0]);\n", + " float width = Float.parseFloat(dimensionParts[1]);\n", + "\n", + " if (length > 0 && width > 0) {\n", + " this.length = length;\n", + " this.width = width;\n", + " } else {\n", + " System.out.println(\"Invalid dimensions provided.\");\n", + " }\n", + " } catch (NumberFormatException e) {\n", + " System.out.println(\"Invalid dimension format: \" + e.getMessage());\n", + " }\n", + " } else {\n", + " System.out.println(\"Invalid dimension format. Please provide two comma-separated values.\");\n", + " }\n", + " }\n", + "\n", + " public static void main(String[] args) {\n", + " Dimensions dimensions = new Dimensions();\n", + " dimensions.setDimensions(\"5.5,4.2\"); // Replace with the desired dimensions\n", + " System.out.println(\"Length: \" + dimensions.length);\n", + " System.out.println(\"Width: \" + dimensions.width);\n", + " }\n", + "}\n", + "\n", + "Dimensions.main(null);" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Topic 5.6: Writing Methods\n", + "\n", + "Methods in Java allow us to define behaviors for objects. When these methods are non-void and have parameters, they can return a value based on the provided arguments.\n", + "\n", + "## Accessing Private Data\n", + "\n", + "Methods can only access the private data and methods of a parameter that is a reference to an object when the parameter is of the same type as the method's enclosing class. This ensures data encapsulation and integrity." + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "10\n" + ] + } + ], + "source": [ + "public class MyClass {\n", + " private int privateData = 10;\n", + "\n", + " public int getPrivateData() {\n", + " return privateData;\n", + " }\n", + "\n", + " public static void main (String[] args) {\n", + " MyClass example = new MyClass();\n", + " int integer = example.getPrivateData();\n", + " System.out.println(integer);\n", + " }\n", + "}\n", + "\n", + "MyClass.main(null);" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Non-Void Methods with Parameters\n", + "\n", + "These methods are designed to receive values, process them, and return a computed result." + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Area: 50.0\n" + ] + } + ], + "source": [ + "public class AreaCalculator {\n", + " public double calculateArea(double length, double width) {\n", + " return length * width;\n", + " }\n", + "\n", + " public static void main(String[] args) {\n", + " AreaCalculator calculator = new AreaCalculator();\n", + " double area = calculator.calculateArea(5, 10);\n", + " System.out.println(\"Area: \" + area);\n", + " }\n", + "}\n", + "\n", + "AreaCalculator.main(null);" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Handling Mutable Objects\n", + "\n", + "It's a good programming practice not to modify mutable objects passed as parameters unless it's explicitly required.\n", + "\n", + "**Why?** Modifying mutable objects that are passed as parameters can lead to unintended side effects in the calling code. The calling code might not expect the object to be modified, and this can introduce bugs that are hard to trace. By avoiding the modification of passed objects, you ensure that the function or method is \"pure\" and doesn't produce unexpected side effects." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import java.util.ArrayList;\n", + "\n", + "public class ListModifier {\n", + " public void modifyList(ArrayList list) {\n", + " // Not recommended unless explicitly required\n", + " list.add(\"New Item\");\n", + " }\n", + "\n", + " public static void main(String[] args) {\n", + " ArrayList items = new ArrayList<>();\n", + " items.add(\"Original Item\");\n", + " \n", + " ListModifier modifier = new ListModifier();\n", + " modifier.modifyList(items);\n", + " \n", + " System.out.println(items);\n", + " }\n", + "}\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Question: What will be the output of the above code?\n", + "\n", + "Answer: [Original Item, New Item]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Primitive vs. Reference Parameters\n", + "\n", + "When a method's parameter is a primitive type, changes to it inside the method won't affect the original value. However, for reference types, changes inside the method will reflect on the original object." + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Number: 10\n", + "List: [Modified]\n" + ] + } + ], + "source": [ + "import java.util.ArrayList;\n", + "\n", + "public class ValueModifier {\n", + " public void modifyValues(int num, ArrayList list) {\n", + " num = 20;\n", + " list.add(\"Modified\");\n", + " }\n", + "\n", + " public static void main(String[] args) {\n", + " int number = 10;\n", + " ArrayList items = new ArrayList<>();\n", + " \n", + " ValueModifier modifier = new ValueModifier();\n", + " modifier.modifyValues(number, items);\n", + " \n", + " System.out.println(\"Number: \" + number);\n", + " System.out.println(\"List: \" + items);\n", + " }\n", + "}\n", + "\n", + "ValueModifier.main(null);" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "When a reference is passed to a method, both the original and the parameter inside the method point to the same memory location. This is termed as aliasing." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "public class AliasingExample {\n", + " public void addToList(ArrayList list) {\n", + " list.add(\"Aliased Item\");\n", + " }\n", + "\n", + " public static void main(String[] args) {\n", + " ArrayList items = new ArrayList<>();\n", + " \n", + " AliasingExample example = new AliasingExample();\n", + " example.addToList(items);\n", + " \n", + " System.out.println(items);\n", + " }\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Given the `AliasingExample` class, add a method named `removeFromList` that removes an item from the list based on its index. After adding the item \"Aliased Item\" using the `addToList` method, use the `removeFromList` method to remove it.\n", + "\n", + "**Note**: Due to aliasing, changes made to the list inside the method will reflect on the original list." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Topic 5.7: Static Variables and Methods\n", + "\n", + "In Java, the `static` keyword plays a pivotal role in the realm of Object-Oriented Programming. It allows variables and methods to be associated with the class itself rather than instances of the class. Let's delve deeper into the world of static components.\n", + "\n", + "## Static Variables\n", + "\n", + "Static variables, unlike instance variables, are associated with the class itself and not with any specific instance. This means there's only one copy of a static variable, which is shared among all instances of the class.\n", + "\n", + "### Key Points:\n", + "\n", + "- **Single Copy**: All instances of the class share the same copy of the static variable. This means if one object modifies a static variable, it reflects in all other instances.\n", + "- **Access Modifiers**: Static variables can be either `public` or `private`, determining their visibility.\n", + "- **Usage**: They are accessed using the class name, not through an instance." + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [], + "source": [ + "public class Student {\n", + " private static int studentCount = 0;\n", + " private String name;\n", + "\n", + " public Student(String name) {\n", + " this.name = name;\n", + " studentCount++;\n", + " }\n", + "\n", + " public static int getStudentCount() {\n", + " return studentCount;\n", + " }\n", + "\n", + " public static void main(String[] args) {\n", + " Student alice = new Student(\"Alice\");\n", + " Student bob = new Student(\"Bob\");\n", + " System.out.println(\"Total Students: \" + Student.getStudentCount());\n", + " }\n", + "}\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Question: If another student, Vardaan, enrolls, what will be the output of `Student.getStudentCount()`?\n", + "\n", + "Answer: Vardaan will be added to the count, and total students will be 3." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Static Methods\n", + "\n", + "Static methods are methods that belong to the class, not any specific instance. This means you can call a static method without creating an object of the class.\n", + "\n", + "### Key Points:\n", + "- **Association with Class**: Static methods are not tied to an instance of the class. This means they can't access instance variables or methods directly.\n", + "- **Access Restrictions**: Static methods cannot access instance variables or call non-static methods directly. They can only access static variables or call other static methods.\n", + "- **Usage**: They are called using the class name." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "public class MathUtility {\n", + " public int num;\n", + " \n", + " public static int square(int number) {\n", + " return number * number;\n", + " }\n", + "\n", + " public static void main(String[] args) {\n", + " int result = MathUtility.square(num);\n", + " System.out.println(\"Square: \" + result);\n", + " }\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Question: What is the problem with the above code (do not run the cell)?\n", + "\n", + "Answer: The static method is attempting to call an instance variable" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Aliasing in Static Components\n", + "\n", + "Given that static variables are shared among all instances, changes in one instance reflect in others. This is a form of aliasing, where multiple references point to the same memory location." + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Shared count after incrementing in obj1: 1\n", + "Shared count after incrementing in obj2: 2\n" + ] + } + ], + "source": [ + "public class SharedResource {\n", + " // Static variable shared among all instances\n", + " public static int sharedCount = 0;\n", + "\n", + " public void incrementCount() {\n", + " sharedCount++;\n", + " }\n", + "\n", + " public static void main(String[] args) {\n", + " SharedResource obj1 = new SharedResource();\n", + " SharedResource obj2 = new SharedResource();\n", + "\n", + " obj1.incrementCount();\n", + " System.out.println(\"Shared count after incrementing in obj1: \" + SharedResource.sharedCount);\n", + "\n", + " obj2.incrementCount();\n", + " System.out.println(\"Shared count after incrementing in obj2: \" + SharedResource.sharedCount);\n", + " }\n", + "}\n", + "\n", + "SharedResource.main(null);" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "When you run the above code, you'll notice that the `sharedCount` variable is incremented by both `obj1` and `obj2`, demonstrating that the static variable is indeed shared among all instances." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Topic 5.8: Scope and Access\n", + "\n", + "In Java, the scope of a variable determines where it can be accessed or modified. The scope is defined by where the variable is declared. Let's delve into the intricacies of variable scope and access in Java." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Local \n", + "\n", + "Local variables are declared within methods or constructors. Their scope is limited to the block in which they are declared, which means they can't be accessed outside of that block.\n", + "\n", + "**Key Points**:\n", + "\n", + "- **Declaration**: Local variables can be declared in methods or constructors.\n", + "- **Accessibility**: They can only be used within the method or constructor where they are declared.\n", + "- **Modifiers**: Local variables cannot have access modifiers like `public` or `private`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "public class LocalVariableExample {\n", + " public void displayMessage() {\n", + " String localVariable = \"Hello, World!\";\n", + " System.out.println(localVariable);\n", + " }\n", + "\n", + " public static void main(String[] args) {\n", + " LocalVariableExample example = new LocalVariableExample();\n", + " example.displayMessage();\n", + " }\n", + "}\n", + "\n", + "LocalVariableExample.main(null);" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In the above code, `localVariable` is a local variable that can only be accessed within the `displayMessage` method.\n", + "\n", + "## Shadowing\n", + "\n", + "When a local variable has the same name as an instance variable, the local variable shadows or hides the instance variable. In such cases, the local variable takes precedence." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "5\n", + "5\n" + ] + } + ], + "source": [ + "public class ShadowExample {\n", + " private int value = 10;\n", + "\n", + " public void printValue(int value) {\n", + " System.out.println(value); // Refers to the local variable\n", + " System.out.println(this.value); // Refers to the instance variable\n", + " }\n", + "\n", + " public static void main(String[] args) {\n", + " ShadowExample example = new ShadowExample();\n", + " example.printValue(5);\n", + " }\n", + "}\n", + "\n", + "ShadowExample.main(null);" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Question: In the `ShadowExample` class, if we didn't use the `this` keyword, which `value` would the method refer to?\n", + "\n", + "Answer: we would refer to the local variable again, which is 5" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Formal Parameters\n", + "\n", + "Formal parameters in methods or constructors are treated as local variables. Their scope is limited to the method or constructor in which they are defined." + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Name: John\n", + "Age: 25\n" + ] + } + ], + "source": [ + "public class DetailsDisplay {\n", + " public void displayDetails(String name, int age) {\n", + " System.out.println(\"Name: \" + name);\n", + " System.out.println(\"Age: \" + age);\n", + " }\n", + "\n", + " public static void main(String[] args) {\n", + " DetailsDisplay display = new DetailsDisplay();\n", + " display.displayDetails(\"John\", 25);\n", + " }\n", + "}\n", + "\n", + "DetailsDisplay.main(null);" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "In the above method, `name` and `age` are formal parameters and can only be accessed within the `displayDetails` method." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Method Decomposition\n", + "\n", + "Method decomposition is a programming technique where a complex problem is broken down into smaller, more manageable subproblems. Each subproblem is solved using a separate method. This approach promotes modularity and reusability.\n", + "\n", + "For instance, consider the following example for calculating the area and perimeter of a rectangle:" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Area: 50.0\n", + "Perimeter: 30.0\n" + ] + } + ], + "source": [ + "public class RectangleOperations {\n", + " public double calculateArea(double length, double width) {\n", + " return length * width;\n", + " }\n", + "\n", + " public double calculatePerimeter(double length, double width) {\n", + " return 2 * (length + width);\n", + " }\n", + "\n", + " public static void main(String[] args) {\n", + " RectangleOperations operations = new RectangleOperations();\n", + " System.out.println(\"Area: \" + operations.calculateArea(5, 10));\n", + " System.out.println(\"Perimeter: \" + operations.calculatePerimeter(5, 10));\n", + " }\n", + "}\n", + "\n", + "RectangleOperations.main(null);" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Java", + "language": "java", + "name": "java" + }, + "language_info": { + "codemirror_mode": "java", + "file_extension": ".jshell", + "mimetype": "text/x-java-source", + "name": "java", + "pygments_lexer": "java", + "version": "20.0.2+9" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/_notebooks/2023-10-14-unit5start.ipynb b/_notebooks/2023-10-14-unit5start.ipynb new file mode 100755 index 0000000..f7e04b0 --- /dev/null +++ b/_notebooks/2023-10-14-unit5start.ipynb @@ -0,0 +1,417 @@ +{ + "cells": [ + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "toc: true\n", + "comments: true\n", + "layout: post\n", + "title: Topics 5.1-5.3\n", + "courses: { compsci: {week: 0} }\n", + "type: tangibles\n", + "---" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# 5.1 Anatomy of a Class" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## KEY LEARNING OBJECTIVES:\n", + "\n", + "1. Designate access and visibility constraints to classes, data, constructors, and methods.\n", + "\n", + "2. Designate private visibility of instance variables to encapsulate the attributes of an object." + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## What is a class?" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "A **class** is a template for creating objects in Java. " + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Private vs Public Designation\n", + "\n", + "**Private**: A private access modifier means that the instance variables, constructors, and methods cannot be accessed outside of the class.\n", + "\n", + "**Public**: This allows access from classes outside the original class of declaration." + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Data Encapsulation\n", + "\n", + "This is one of the key components of object oriented programming. \n", + "\n", + "It ensures data ___encapsulation___ by controlling which parts of a class are accessible to other classes." + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In the following example, we look at encapsulation and demonstrate how to create a Student class with private instance variables for name and age, public methods for accessing and modifying these variables, and validation checks to ensure data integrity. " + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Meet our star student:\n", + "Name: Vishnu\n", + "Age: 17\n" + ] + } + ], + "source": [ + "public class Student {\n", + " // 1. Private variables to store student's name and age\n", + " private String name; // Stores the student's name\n", + " private int age; // Stores the student's age\n", + "\n", + " // 2. Public Class: Student\n", + "\n", + " // 3. Constructor Methods\n", + " // Constructor to create a Student object with a name and age\n", + " public Student(String name, int age) {\n", + " this.name = name;\n", + " this.age = age;\n", + " }\n", + "\n", + " public static void main(String[] args) {\n", + " // Let's create a new Student!\n", + " Student student = new Student(\"Vishnu\", 17);\n", + "\n", + " // Displaying the student's information\n", + " System.out.println(\"Meet our star student:\");\n", + " System.out.println(\"Name: \" + student.name); // Accessing the name directly\n", + " System.out.println(\"Age: \" + student.age); // Accessing the age directly\n", + " }\n", + "}\n", + "\n", + "Student.main(null);\n" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# 5.2 Constructors" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## KEY LEARNING OBJECTIVES" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Define instance variables for the attributes to be initialized through the constructors of a class." + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Constructors are used to set the __initial___ state of an object.\n" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Mutable Objects**: These are objects whose internal state can be changed after its creation. Lists are mutable objects, as are arrays.\n", + "\n", + "**Constructor Parameters**: These are values passed to a class's constructor when creating an instance. This initializes the new object's state.\n", + "\n", + "**Instance Variables**: These are object attributes that store the objects state. They are declared within the class and can be accessed by the object's methods.\n", + "\n", + "**Alias**: Two variables point to the __same__ object." + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "A good example of a Java alias:" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Value at index 0 through alias2: 100\n" + ] + } + ], + "source": [ + "public class AliasExample {\n", + " public static void main(String[] args) {\n", + " // Create an array and two references (aliases) to it\n", + " int[] array = new int[]{1, 2, 3};\n", + " int[] alias1 = array;\n", + " int[] alias2 = array;\n", + "\n", + " // Modify the array through one of the aliases\n", + " alias1[0] = 100;\n", + "\n", + " // Access the modified array through the other alias\n", + " System.out.println(\"Value at index 0 through alias2: \" + alias2[0]);\n", + " }\n", + "}\n", + "\n", + "AliasExample.main(null);" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In the below example, we explore encapsulation and demonstrate how to create a Person class to represent individuals with private attributes for name, age, and hobbies. The code showcases how to initialize and manipulate a Person object's state, including adding hobbies to the person's list, while ensuring the original data remains unchanged." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Person 1:\n", + "Name: Anna\n", + "Age: 17\n", + "Person 2:\n", + "Name: Rohin\n", + "Age: 13\n" + ] + } + ], + "source": [ + "public class Person {\n", + " private String name;\n", + " private int age;\n", + "\n", + " // Constructor to initialize a Person with a name and age\n", + " public Person(String name, int age) {\n", + " this.name = name; // Initialize the 'name' field with the provided name\n", + " this.age = age; // Initialize the 'age' field with the provided age\n", + " }\n", + "\n", + " // Method to display the person's information\n", + " public void displayInfo() {\n", + " System.out.println(\"Name: \" + name);\n", + " System.out.println(\"Age: \" + age);\n", + " }\n", + "}\n", + "\n", + "public class PersonConstructorDemo {\n", + " public static void main(String[] args) {\n", + " // Create two Person objects using the constructor\n", + " Person person1 = new Person(\"Anna\", 17);\n", + " Person person2 = new Person(\"Rohin\", 13);\n", + "\n", + " // Display information about the created persons\n", + " System.out.println(\"Person 1:\");\n", + " person1.displayInfo();\n", + " \n", + " System.out.println(\"Person 2:\");\n", + " person2.displayInfo();\n", + " }\n", + "}\n", + "\n", + "PersonConstructorDemo.main(null);\n" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In the Person class, the hobbies list is encapsulated to prevent unintended modifications. What is the importance of encapsulation and how does it improve the design of the class?" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# 5.3 Documentation with Comments" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## KEY LEARNING OBJECTIVE" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Describe the functionality and use of program code through comments." + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Precondition**: This is a condition that has to be met prior to an execution of a certain part of the code for the method to work.\n", + "\n", + "**Postcondition**: This is a condition that has to be met after the execution of a certain part of the code. " + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Constructor called with value: 42\n", + "Value: 42\n" + ] + } + ], + "source": [ + "public class Comments {\n", + " private int value;\n", + "\n", + " //constructor, build the value \n", + " public Comments(int value) {\n", + " this.value = value; //initialize value variable \n", + " System.out.println(\"Constructor called with value: \" + value); //print out message when constructor is called\n", + " }\n", + "// access encapsulated value\n", + " public int getValue() {\n", + " return value;\n", + " }\n", + "// access all the methods and print values \n", + " public static void main(String[] args) {\n", + " Comments myObject = new Comments(42); \n", + " int result = myObject.getValue(); \n", + " System.out.println(\"Value: \" + result); \n", + " }\n", + "}\n", + "\n", + "Comments.main(null);\n" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**ADD DESCRIPTIVE COMMENTS TO THE ABOVE CODE. Provide descriptions of functionality, identify methods used, and initialized variables if any.**" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Hacks" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**POPCORN HACKS: 0.2**" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Create a simple To-Do List that utilizes the following (0.8):**\n", + "\n", + "1. Private and Public Declaration\n", + "\n", + "2. Constructor\n", + "\n", + "3. Mutable Array containing To-Do List Items\n", + "\n", + "Make sure to add descriptive comments that are describing your code!" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Java", + "language": "java", + "name": "java" + }, + "language_info": { + "codemirror_mode": "java", + "file_extension": ".jshell", + "mimetype": "text/x-java-source", + "name": "java", + "pygments_lexer": "java", + "version": "20.0.2+9" + }, + "orig_nbformat": 4 + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/_notebooks/2023-10-18-Unit6Arrays.ipynb b/_notebooks/2023-10-18-Unit6Arrays.ipynb new file mode 100755 index 0000000..bc50c0b --- /dev/null +++ b/_notebooks/2023-10-18-Unit6Arrays.ipynb @@ -0,0 +1,1493 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "layout: post\n", + "title: Unit 6 Lesson\n", + "toc: true\n", + "comments: true\n", + "description: Lesson for APCSA Unit 6. Authors are Sreeja, Tanisha, Vivian, and Isabelle\n", + "courses: { compsci: {week: 0} }\n", + "type: tangibles\n", + "---" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Hello! wget this notebook `RIGHT NOW` \n", + "> (Find the link in 'coding' on SLACK)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Topic 6.1 - Array Creation and Access (Sreeja)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Vocabulary\n", + "- Array: a data strucutre used to implement a collection of object referance data\n", + "- Element: a single value within an array\n", + "- Index of an element: position of an element in the array\n", + "(In java, the first element of an array is at index 0)\n", + "- Length of an array: number of elements in the array" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Declaring an Array\n", + "Defines the array variable, specifying its data type and name." + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [], + "source": [ + "// Syntax: dataType[] arrayName;\n", + "int[] numbers; // Declare an integer array\n", + "String[] names; // Declare a string array" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Creating an Array\n", + "Gives memory for the array and specifies its size." + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [], + "source": [ + "// Syntax: arrayName = new dataType[size];\n", + "numbers = new int[5]; // Create an integer array with 5 elements\n", + "names = new String[3]; // Create a string array with 3 elements" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Initializing an Array\n", + "Populates the array with initial values." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [], + "source": [ + "// Syntax: arrayName = new dataType[size];\n", + "numbers = new int[5]; // Create an integer array with 5 elements\n", + "names = new String[3]; // Create a string array with 3 elements" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Accessing Array Elements\n", + "Retrieves a specific element's value from the array using its index." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "30\n" + ] + } + ], + "source": [ + "int[] numbers = {10, 20, 30, 40, 50};\n", + "int element = numbers[2]; // Access the third element (30) using index 2\n", + "System.out.println(element); // Output: 30\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Array Length\n", + "Obtains and displays the number of elements in the array." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Array length: 5\n" + ] + } + ], + "source": [ + "int[] numbers = {10, 20, 30, 40, 50};\n", + "int length = numbers.length; // Get the length of the array\n", + "System.out.println(\"Array length: \" + length); // Output: Array length: 5" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Modifying Array Elements\n", + "Updates the value of a specific element in the array." + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "35" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "int[] numbers = {10, 20, 30, 40, 50};\n", + "numbers[2] = 35; // Change the third element to 35" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Iterating Through an Array\n", + "Loops through the array, printing each element." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "int[] numbers = {10, 20, 30, 40, 50};\n", + "for (int i = 0; i < numbers.length; i++) {\n", + " System.out.println(numbers[i]);\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Enhanced For Loop (For-each)\n", + "Iterates through the array using a simplified loop structure, printing each element." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "int[] numbers = {10, 20, 30, 40, 50};\n", + "for (int number : numbers) {\n", + " System.out.println(number);\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Topic 6.2 - Traversing Array (1D) (Tanisha)\n", + "> Using iteration statements (standard for loops and while loops) to access each element in an array. \n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Standard For Loop\n", + "- An array in java is indexed from _0_ to the number of elements - 1_. " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Review on For Loops**\n", + "- init: The init expression is used for initializing a variable, and it is executed only once.\n", + "- condition: It executes the condition statement for every iteration\n", + "- incr/decr: It is the increment or decrement statement applied to the variable, updates the initial expression.\n", + "\n", + "![image](https://github.com/tanishapatil1234/student/assets/111611921/ec109b9d-f3be-451f-9d87-6488a1c96e2b)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import java.util.Random;\n", + "\n", + "/* public class RandomArray {\n", + " public static void main(String[] args){\n", + " int [] list = new int[6];\n", + " Random rand = new Random(); \n", + "*/\n", + " // FOR LOOP 1\n", + " for (int i = 0; i < list.length; i++){\n", + " list[i] = rand.nextInt(4);\n", + " }\n", + "\n", + " // FOR LOOP 2\n", + " for(int element: list){\n", + " System.out.println(element);\n", + " }\n", + "\n", + "/* }\n", + "\n", + " }\n", + "\n", + " RandomArray.main(null);\n", + "*/" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Class Discussion-Take Notes, these will count for points in your hacks!**\n", + "\n", + "1. What do the for loops accomplish? \n", + "the for loop 1 populates the array with random values. the for loop 2 prints the array using an enhanced for loop\n", + "________________________\n", + "2. What is the difference between how elements of the array list are accessed? \n", + "the enhanced for loop is used to access the array list. A normal for loop is only used for populate array.\n", + "________________________\n", + "3. BONUS: When the array list of ints was first created, what was each int in the list initialized to? \n", + "the array list was initialized to 0.\n", + "_________________________" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "![download](https://github.com/tanishapatil1234/student/assets/111611921/39e2f50d-6eca-4dcd-9d57-489662a26391)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# For loop : Accessing Some Elements of a List" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Class Discussion-Take Notes, these will count for points in your hacks!**\n", + "\n", + "4. If I only wanted to access the elements at even indices of the list (0, 2, 4), what could I change in the statement below to accomplish that? \n", + "\n", + "change the index to increase by 2\n", + "\n", + "5. What about odd? \n", + "\n", + "change the index inital value to 1, change to index += 2 in for loop" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Even Index\n", + "0\n", + "2\n", + "4\n", + "Odd Index\n", + "1\n", + "3\n", + "5\n" + ] + } + ], + "source": [ + "// EVEN\n", + "int[] list = {0, 1, 2, 3, 4, 5};\n", + "System.out.println(\"Even Index\");\n", + "for(int index = 0; index < list.length; index += 2){\n", + " System.out.println(list[index]);\n", + "}\n", + "\n", + "// ODD\n", + "int[] list = {0, 1, 2, 3, 4, 5};\n", + "System.out.println(\"Odd Index\");\n", + "for(int index = 1; index < list.length; index += 2){\n", + " System.out.println(list[index]);\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Note: These are NOT traversals, even though these are for loops. This is because not every element in the array is accessed.**" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Standard While Loop\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "6. Does the following loop accomplish traversing the array? \n", + "\n", + "since we go to each value, the loop accomplishes traversing the array.\n" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [], + "source": [ + "int [] list = new int[5];\n", + "int index = 0; \n", + "\n", + "while (index < list.length) \n", + "{\n", + " // Do something\n", + " index ++; \n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "7. This while loop and the for loop we used earlier accomplish the same task. The main difference is that after the loop is completed, the variable 'index' in the while loop will still exist. The variable 'i' in the for loop will not. Why? \n", + "\n", + "the i variable was defined inside loop, so it won't be used outside of the loop.\n", + "\n", + "__________________________________" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Bounds Errors" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "When traversing an array, we need to be careful with the indices to avoid an ArrayIndexOutOfBoundsException being thrown. " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**ATTENTION: MOST COMMON MISTAKE:**\n", + "8. What is wrong with the for loop and while loop below? Why does this produce an ArrayIndexOutOfBoundsException error? ____\n", + "\n", + "the loops are going out of bounds of our set arrays, the for loop is going 1 back the set limit of for loops. while loop is going 1 back the set limit of while loops." + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": {}, + "outputs": [ + { + "ename": "IncompleteSourceException", + "evalue": "for(int i = 0; i <= list.length; i ++)", + "output_type": "error", + "traceback": [ + "\u001b[1m\u001b[31mIncomplete input:\u001b[0m", + "\u001b[1m\u001b[30m| \u001b[1m\u001b[30mfor(int i = 0; i <= list.length; i ++)\u001b[0m" + ] + } + ], + "source": [ + "for(int i = 0; i <= list.length; i ++)" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": {}, + "outputs": [ + { + "ename": "IncompleteSourceException", + "evalue": "while (index <= list.length)", + "output_type": "error", + "traceback": [ + "\u001b[1m\u001b[31mIncomplete input:\u001b[0m", + "\u001b[1m\u001b[30m| \u001b[1m\u001b[30mwhile (index <= list.length)\u001b[0m" + ] + } + ], + "source": [ + "int index = 0; \n", + "while (index <= list.length)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Off by One Error** : missing the first or last element of an array when trying to traverse" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "[0, 1, 2, 3, 4]" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": {}, + "outputs": [ + { + "ename": "IncompleteSourceException", + "evalue": "// This won't access the last element in the list\nfor(int i = 0; i <= list.length - 1; i ++)", + "output_type": "error", + "traceback": [ + "\u001b[1m\u001b[31mIncomplete input:\u001b[0m", + "\u001b[1m\u001b[30m| \u001b[1m\u001b[30m// This won't access the last element in the list\u001b[0m", + "\u001b[1m\u001b[30m| \u001b[1m\u001b[30mfor(int i = 0; i <= list.length - 1; i ++)\u001b[0m" + ] + } + ], + "source": [ + "// This won't access the last element in the list\n", + "for(int i = 0; i < list.length - 1; i ++)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "// This won't access the first element in the list\n", + "int index = 1; \n", + "while (index <= list.length)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Developing Methods Using Arrays\n", + "Reviewing common methods asked on AP Exam FRQs" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Average Value" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Complete the popcorn hack below in order to return the average value of the elements in the list numbers. " + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "The average of the numbers is: 15.0\n" + ] + } + ], + "source": [ + "public class ArrayAverage {\n", + " public static void main(String[] args) {\n", + " int[] numbers = {5, 10, 15, 20, 25};\n", + " int sum = 0;\n", + " double average;\n", + " \n", + " for (int i = 0; i < numbers.length; i++) {\n", + " sum += numbers[i]; \n", + " }\n", + " \n", + " \n", + " average = (double) sum / numbers.length; /* missing code */\n", + " \n", + " System.out.println(\"The average of the numbers is: \" + average);\n", + " }\n", + "}\n", + "\n", + "ArrayAverage.main(null);" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# 6.3 Enhanced for loop for Arrays (Vivian)\n", + "- the enhanced for loop is also known as the “for each” loop\n", + "- provides a simplified way to loop through elements in an array, collection, or other iterable data structures." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "//syntax for enhanced for loop\n", + "for (dataType element : array) {\n", + " // code to process 'element'\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "- the data type in the loop must match the array’s element data type." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n", + "2\n", + "3\n", + "4\n", + "5\n" + ] + } + ], + "source": [ + "//array of int matches element int\n", + "int[] numbers = {1, 2, 3, 4, 5};\n", + "for (int num : numbers) {\n", + " System.out.println(num);\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Comparing a regular for loop with the enhanced for loop\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Popcorn Hack: Rewrite this code to use an enhanced for loop instead. make comments explaining what you added/changed" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Quote: \"Success is not final, failure is not fatal: It is the courage to continue that counts.\"\n", + "Emotion: Courageous\n", + "---------------------------\n", + "Quote: \"Success is not final, failure is not fatal: It is the courage to continue that counts.\"\n", + "Emotion: Passionate\n", + "---------------------------\n", + "Quote: \"Success is not final, failure is not fatal: It is the courage to continue that counts.\"\n", + "Emotion: Innovative\n", + "---------------------------\n" + ] + } + ], + "source": [ + "import java.util.List;\n", + "\n", + "class Quote {\n", + " private List quotes;\n", + " private List emotions;\n", + "\n", + " public Quote(List quotes, List emotions) {\n", + " this.quotes = quotes;\n", + " this.emotions = emotions;\n", + " }\n", + " int i = 0;\n", + " public void printQuotesWithEmotions() {\n", + " // Make a change in the code here! \n", + " \n", + " for (String emotion : emotions) {\n", + " String quote = quotes.get(i);\n", + " \n", + " System.out.println(\"Quote: \\\"\" + quote + \"\\\"\");\n", + " System.out.println(\"Emotion: \" + emotion);\n", + " System.out.println(\"---------------------------\");\n", + " }\n", + " }\n", + "\n", + " public static void main(String[] args) {\n", + " List quotes = List.of(\n", + " \"Success is not final, failure is not fatal: It is the courage to continue that counts.\",\n", + " \"The only way to do great work is to love what you do.\",\n", + " \"The best way to predict the future is to create it.\"\n", + " );\n", + "\n", + " List emotions = List.of(\n", + " \"Courageous\",\n", + " \"Passionate\",\n", + " \"Innovative\"\n", + " );\n", + "\n", + " Quote quotePrinter = new Quote(quotes, emotions);\n", + " quotePrinter.printQuotesWithEmotions();\n", + " }\n", + "}\n", + "\n", + "Quote.main(null);" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "What are some of the benefits of using an enhanced for loop in this case versus a regular for loop?\n", + "\n", + "a regular for loop allows you to access indices but an enchanced for loop cannot. Enchanced for loops are useful when you want to iterate through an array but not access the index. " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Limitations to enhanced for loop\n", + "- it does not provide access to the index of the current element.\n", + " - This means you cannot easily determine the position of the element in the array or collection.\n", + " - But when you want to search for a specific element in a collection and you don’t necessarily need to access the index\n", + " - If you need to work with indices, you should use a traditional for loop instead.\n", + "- read-only access to elements.\n", + " - You cannot modify the elements within the loop\n", + " - Thus, when you need to modify a collection based on a condition. You should use a regular for loop" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "For the next two code blocks, decide whether or not its better to use a regular for loop or an enhanced one, explain why. write the code for them" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "1. Searching for an Element in an ArrayList" + ] + }, + { + "cell_type": "code", + "execution_count": 44, + "metadata": {}, + "outputs": [], + "source": [ + "ArrayList names = new ArrayList<>();\n", + "String searchName = \"Vivian\";\n", + "\n", + "//code goes here\n", + "for (String name : names) {\n", + " if (name.equals(searchName)) {\n", + " System.out.println(\"Found \" + searchName);\n", + " break;\n", + " }\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "2. Removing Even Numbers from an ArrayList" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "ArrayList numbers = new ArrayList<>();\n", + "// use normal for loop\n", + "//code goes here\n", + "for (int i = 0; i < numbers.size(); i++) {\n", + " System.out.println(numbers.get(i));\n", + " \n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# 6.4: Developing Algorithms Using Arrays (Isabelle)\n", + "## How to identify the maximum or minimum value in an array" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "It is a common task to determine what the largest or smallest value stored is inside an array. In order to do this, we need a method that can take a parameter of an array of primitve values (`int` or `double`) and return the item that is at the appropriate extreme.\n", + "\n", + "Inside the method a local variable is needed to store the current max or min value that will be compared against all the values in the array. You can assign the current value to be either the opposite extreme or the first item you would be looking at.\n", + "\n", + "You can use either a standard `for` loop or an enhanced `for` loop to determine the max or min. Assign the temporary variable a starting value based on what extreme you are searching for.\n", + "\n", + "Inside the `for` loop, compare the current value against the local variable; if the current value is better, assign it to the temporary variable. When the loop is over, the local variable will contain the appropriate value and is still available and within scope and can be returned from the method." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Find max in an array of `double` values" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [], + "source": [ + "private double findMax(double [] values) {\n", + " double max = values[0];\n", + "\n", + " for (int index = 1; index < values.length; index++) {\n", + " if (values[index] > max) {\n", + " max = values[index];\n", + " }\n", + " }\n", + " return max;\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Find min in an array of `int` values" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "private int findMin(int [] values) {\n", + " int min = Integer.MAX_VALUE;\n", + "\n", + " for (int currentValue: values) {\n", + " if (currentValue < min) {\n", + " min = currentValue;\n", + " }\n", + " }\n", + " return min;\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Let's Practice!" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Popcorn hack #1**" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [], + "source": [ + "// What needs to be changed to find the index of the max value? (write correct code in cell below)\n", + "private int findMax(double [] values) {\n", + " double max = values[0];\n", + " int maxIndex = 0; \n", + "\n", + " for (int index = 1; index < values.length; index++) {\n", + " if (values[index] > max) { \n", + " max = values[index];\n", + " maxIndex = index;\n", + " }\n", + " }\n", + " return maxIndex;\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## How to calculate the average value from objects in an array" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "It is a common task to determine what is the average value returned from items stored inside an array. In order to do this, we need a method that can take a parameter of an array of Objects (DebugDuck) and calculate and return the average value that each instance of DebugDuck returns from the method.\n", + "\n", + "Inside the method; a local double variable is needed to store the accumulated values. Then we use a for loop to traverse the array and add the current total to the variable. After accumulating all the values we need to divide the total by the number of items stored in the array." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Using a standard `for` loop\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "private double calculateAverage(DebugDuck [] ducks) {\n", + " double average = 0.0;\n", + "\n", + " for (int index = 0; index < ducks.length; index++) {\n", + " average += ducks[index].getQuestionCount();\n", + " }\n", + " average = average / ducks.length;\n", + "\n", + " return average;\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Using a standard `enhanced` loop\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "private double calculateAverage(DebugDuck [] ducks) {\n", + " double average = 0.0;\n", + "\n", + " for (DebugDuck currentDuck: ducks) {\n", + " average += currentDuck.getQuestionCount();\n", + " }\n", + " average = average / ducks.length;\n", + "\n", + " return average;\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Does the order of accumulation matter?**\n", + "\n", + "no, because we accumulate all of the values at the end, regardless of change in order. we only need sum, not specific value, and changing order doesn't change sum.\n", + "\n", + "**Can you declare the variable inside the loop?**\n", + "\n", + "no, then we won't be able to access the variable outside the loop." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Shfiting Array contents to the right" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The contents of an array often need to be shifted as part of a solution to using the data inside.\n", + "\n", + "We need to know how much to shift the array by. This will need to be an int obviously.\n", + "\n", + "In order to move the contents we next need to make an empty array of the same size and then iterate over the original array and properly copy the values to the adjusted index in the new array.\n", + "\n", + "We then need to assign the new array back into the original variable.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**What kind of for loop should we use? Why?**\n", + "\n", + "use a normal for loop because we need to access specific indices." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "3 \n", + "4 \n", + "5 \n", + "1 \n", + "2 \n" + ] + } + ], + "source": [ + "int [] numbers = {1,2,3,4,5};\n", + "int [] shifted = new int [numbers.length];\n", + "int shift = 8;\n", + "for (int index = 0; index < numbers.length; index++) {\n", + " shifted [Math.abs((index + shift) % numbers.length)] = numbers[index];\n", + "}\n", + "numbers = shifted;\n", + "for (int num : numbers) {\n", + " System.out.println(num + \" \");\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Why are we using the % operator?**\n", + "\n", + "we use this to prevent our index going out of bounds, and it creates the shift " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Popcorn hack #2**" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "How would we code a left shift? Write a left shift using the variables below\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": 35, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "gamma\n", + "delta\n", + "alpha\n", + "beta\n" + ] + } + ], + "source": [ + "String[] words = {\"alpha\", \"beta\", \"gamma\", \"delta\"};\n", + "\n", + "String[] wordShift = new String[words.length];\n", + "int shiftWord = 2;\n", + "for (int index = 0; index < words.length; index++) {\n", + " wordShift[index] = words[((index + shiftWord) % words.length)];\n", + " System.out.println(wordShift[index]);\n", + "\n", + "}\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Why should the array index be wrapped in a call to Math.abs?**\n", + "\n", + "Math.abs returns absolute value, so we probably use this to make sure our array index doesn't go out of bounds." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Hacks" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Scoring Guidelines: \n", + "- 0.2 for completeing each of the sub-unit hacks mentioned below. \n", + " - FRQ/PopCorn hacks will be graded AP Style\n", + "- 0.1 for having organized notebook with note taking when appropriate. \n", + "- Extra 0.1 for going above expectations for the hacks (being creative!)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 6.1 HACK 1 FRQ (<5 min)\n", + "\n", + "Follow the steps in the lesson to just make an array that has some relation to your project. Feel free to use the code examples we provided in your hack if you would like." + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Type in your name:\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Type in your id:\n", + "User Information:\n", + "Name: ooo\n", + "ID: 88\n" + ] + } + ], + "source": [ + "// HACK 1 FRQ\n", + "import java.util.Scanner;\n", + "\n", + "String[] Users = {\"name\", \"id\", \"credit card\"};\n", + "Scanner scanner = new Scanner(System.in);\n", + "\n", + "while (true) {\n", + " System.out.println(\"type in your name\");\n", + " String name = scanner.nextLine();\n", + " Users[1] = (name);\n", + " System.out.println(\"name: \" + Users[1]);\n", + " String id = \"123456789\";\n", + " Users[2] = (id);\n", + " System.out.println(\"id: \" + (Users[2]));\n", + " break;\n", + "}" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "// Experiment with hashmaps to accomplish similar task " + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Type in your name:\n", + "Type in your id:\n", + "User Information:\n", + "Name: test\n", + "ID: 342342\n" + ] + } + ], + "source": [ + "import java.util.Scanner;\n", + "import java.util.HashMap;\n", + "\n", + "public class UserInformation {\n", + " public static void main(String[] args) {\n", + " Scanner scanner = new Scanner(System.in);\n", + " HashMap userMap = new HashMap<>();\n", + "\n", + " System.out.println(\"Type in your name:\");\n", + " String name = scanner.nextLine();\n", + " userMap.put(\"name\", name);\n", + "\n", + " System.out.println(\"Type in your id:\");\n", + " String id = scanner.nextLine();\n", + " userMap.put(\"id\", id);\n", + "\n", + " System.out.println(\"User Information:\");\n", + " System.out.println(\"Name: \" + userMap.get(\"name\"));\n", + " System.out.println(\"ID: \" + userMap.get(\"id\"));\n", + " }\n", + "}\n", + "UserInformation.main(null);\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 6.2 HACK 1 FRQ (<10 min)\n", + "\n", + "**Prime Numbers in an Array (5-10 min)**\n", + "\n", + "Create a loop to identify and print the prime numbers from an array of integers. Your loop MUST traverse through the given list. Some things to consider: \n", + "> BONUS: Do this with a for loop AND a while loop \n", + "\n", + "- Understand prime numbers and how to check for primality.\n", + "- Implement a loop and conditional statements to iterate through the array.\n", + "- Consider data storage (either displaying prime numbers immediately or storing them for later display)" + ] + }, + { + "cell_type": "code", + "execution_count": 50, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "17\n", + "23\n" + ] + } + ], + "source": [ + "int[] numbers = {1, 17, 4, 23};\n", + "\n", + "for (int i = 0; i < numbers.length; i++) {\n", + " int num = numbers[i];\n", + " boolean isPrime = true;\n", + " \n", + " if (num <= 1) {\n", + " isPrime = false;\n", + " } else {\n", + " for (int j = 2; j <= Math.sqrt(num); j++) {\n", + " if (num % j == 0) {\n", + " isPrime = false;\n", + " break;\n", + " }\n", + " }\n", + " }\n", + "\n", + " if (isPrime) {\n", + " System.out.println(num);\n", + " }\n", + "}\n" + ] + }, + { + "cell_type": "code", + "execution_count": 53, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "17\n", + "23\n" + ] + } + ], + "source": [ + "//rewrite with while loop \n", + "\n", + "int[] numbers = {1, 17, 4, 23};\n", + "\n", + "int i = 0;\n", + "\n", + "while (i < numbers.length) {\n", + " int num = numbers[i];\n", + " boolean isPrime = true;\n", + "\n", + " if (num <= 1) {\n", + " isPrime = false;\n", + " } else {\n", + " int j = 2;\n", + " while (j * j <= num) {\n", + " if (num % j == 0) {\n", + " isPrime = false;\n", + " break;\n", + " }\n", + " j++;\n", + " }\n", + " }\n", + "\n", + " if (isPrime) {\n", + " System.out.println(num);\n", + " }\n", + "\n", + " i++;\n", + "}\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 6.2 HACK 2 MCQ (<5 min)\n", + "\n", + "**Multiple Choice Questions**\n", + "\n", + "\n", + "Do NOT Run the code cells. Try to do this on your own." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "1. What will be displayed as the output? " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "String [] list = {\"red\", \"yellow\", \"blue\"}; \n", + "for (int i = 0; i <= list.length; i++)\n", + "{\n", + " System.out.print(list[i].length()+ \"-\" )\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "- A. red-yellow-blue\n", + "- B. 3-3-3-\n", + "- C. 3-6-4-\n", + "- D. 3-6-\n", + "- E. 3-6-4" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Write why you chose that answer! \n", + "\n", + "B because the print statement just prints out the length of the list, and the statement runs 3 times, also the array never changes.\n", + "______________________" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "2. The code below is meant to display every other number in the list numbers. Which of the following should replace the missing code in order to do this? " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "int [] numbers = {3, -4, 6, -7, 2}; \n", + "for(/*missing code*/)\n", + "{\n", + " System.out.println(numbers[i]);\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "- A. int i = 0; i < numbers.length/2; i++\n", + "- B. int i = 1; i < numbers.length; i++\n", + "- C. int i = 1; i < numbers.length; i+=2\n", + "- D. int i = 0; i < numbers.length; i++\n", + "- E. int i = 0; i < numbers.length; i+=2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Write why you chose that answer! \n", + "\n", + "E, because then we print out the 1st, 3rd, and 5th elements of the array, skipping 2nd and 4th since we go by 2 in the loop.\n", + "______________________" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "3. (This one is a little hard) Which of the following would fix the code so that the elements in arr are reversed. Hint: try creating a list in your head and trace the code to see if the code accomplishes its goal." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "public static void reverseArray(double [] arr)\n", + "{\n", + " for(int = 0; i< arr.length; i++)\n", + " {\n", + " double temp = arr[i];\n", + " arr[i] = arr[arr.length-1-i];\n", + " arr[arr.length-1-i] = temp; \n", + " }\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "- A. Change loop condition to: i < arr.length - 1\n", + "- B. Change loop condition to: i < arr.length/2\n", + "- C. Change loop condition to: i < arr.length/2 - 1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In case you are having trouble with question 3 the answer is B. Write about why! \n", + "\n", + "the Answer is B but I think its because dividing the array length my 2 would let us start somewhere else where the code would thus reverse the items for our goal.\n", + "\n", + "_______________________________" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 6.3 HACK \n", + "- Just finish the popcorn hacks throughout the lesson! " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 6.4 HACK \n", + "- Just finish the 2 popcorn hacks in the lesson! " + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Java", + "language": "java", + "name": "java" + }, + "language_info": { + "codemirror_mode": "java", + "file_extension": ".jshell", + "mimetype": "text/x-java-source", + "name": "java", + "pygments_lexer": "java", + "version": "20.0.2+9" + }, + "orig_nbformat": 4 + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/_notebooks/2023-10-20-unit-7.ipynb b/_notebooks/2023-10-20-unit-7.ipynb new file mode 100755 index 0000000..e610669 --- /dev/null +++ b/_notebooks/2023-10-20-unit-7.ipynb @@ -0,0 +1,1501 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "toc: true\n", + "comments: false\n", + "layout: post\n", + "title: Unit 7 ArrayLists\n", + "description: ArrayList Lesson\n", + "type: tangibles\n", + "courses: { compsci: {week: 0} }\n", + "---" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Unit 7: ArrayList\n", + "> Mastering the concept of Java's ArrayList. AP Exam weighting: 2.5-7.5%." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# 7.1: ArrayList Intro" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "- ArrayLists are dynamic, meaning their size can grow or shrink as needed, but arrays are static in size\n", + "- Instead of creating a new array of a different size and copying the data from the initial array to the new one, we can use ArrayLists\n", + "\n", + "|Arrays|ArrayLists|\n", + "|-------|---------|\n", + "|Fixed Length|Resizable Length|\n", + "|Fundamental Java feature|Part of a framework|\n", + "|An object with no methods|Class with many methods|\n", + "|Not as flexible|Designed to be very flexible|\n", + "|Can store primitive data|Not designed to store primitives|\n", + "||Slightly slower than arrays|\n", + "||Need an import statement|" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In order to use the ArrayList class, the ArrayList class needs to be imported from the java util package. This can be done by writing import java.util.ArrayList at the top of the class file." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import java.util.ArrayList; // Import the ArrayList class\n", + "\n", + "// Declare and initialize an ArrayList of integers\n", + "ArrayList numbersList = new ArrayList<>();" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "ArrayList objects are created in the same fashion as other object classes. The primary difference with ArrayLists is that the element type of the ArrayList must be specified using angled bracket <>. In this example, E represents the data type that will be used in the ArrayList. This can be replaced by an object data type:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "ArrayList list = new ArrayList();" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can actually declare ArrayLists without specifying the type that will be included in the ArrayList, but specifying the data type is smarter because it allows the compiler to find errors before run time, so its more efficient and easy to spot errors." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "ArrayList list = new ArrayList();" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Quick lil popcorn hack\n", + "\n", + "Create 2 ArrayLists, 1 called `studentName` and 1 called `studentAge`" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "public class Student\n", + "{\n", + " public static void main(String[] args)\n", + " {\n", + " ArrayList StudentAge = new ArrayList<>();\n", + " //Initialize your ArrayLists\n", + " ArrayList StudentName = new ArrayList<>();\n", + " }\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# 7.2: ArrayList Methods" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Learning Objectives\n", + "\n", + "Students will be able to represent collections of related object reference data using `ArrayList` objects.\n", + "\n", + "### Essential Knowledge\n", + "\n", + "- Iteration statements provide a means to access all the elements stored within an `ArrayList`. This process is referred to as \"traversing the `ArrayList`.\"\n", + "\n", + "- The following `ArrayList` methods, including what they do and when they are used, are part of the Java Quick Reference:\n", + "\n", + " * `int size()` - Returns the count of elements within the list.\n", + " * `boolean add(E obj)` - Appends the object `obj` to the end of the list and returns `true`.\n", + " * `void add(int index, E obj)` - Inserts `obj` at the specified `index`, shifting elements at and above that position to the right (incrementing their indices by 1) and increasing the list's size by 1.\n", + " * `E get(int index)` - Retrieves the element at the given `index` in the list.\n", + " * `E set(int index, E obj)` - Replaces the element at the specified `index` with `obj` and returns the previous element at that index.\n", + " * `E remove(int index)` - Deletes the element at the specified `index`, shifting all subsequent elements one index to the left, reducing the list's size by one, and returning the removed element.\n", + "\n", + "- Java allows the generic `ArrayList`, where the generic type `E` specifies the type of element.\n", + "\n", + "- When `ArrayList` is specified, the types of the reference parameters and return type when using the methods are type `E`.\n", + "\n", + "- `ArrayList` is preferred over `ArrayList` because it allows the compiler to find errors that would otherwise be found at runtime." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Size of the `ArrayList`\n", + "\n", + "* `int size();` : Returns the number of elements in the list.\n", + "\n", + "Consider the following code:" + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0\n" + ] + } + ], + "source": [ + "ArrayList a1 = new ArrayList<>();\n", + "System.out.println(a1.size());" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Adding Items to an `ArrayList`\n", + "\n", + "* `boolean add(E obj);` : Appends `obj` to the end of the list and returns true.\n", + "* `void add(int index, E obj)` : Inserts `obj` at position `index`, as long as `index` is within the list's length. It moves each element in the list 1 index higher and adds 1 to the list's size.\n", + "\n", + "Consider the following code:" + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[1.0, 4.0, 2.0, 3.0]\n" + ] + } + ], + "source": [ + "ArrayList a2 = new ArrayList<>();\n", + "a2.add(1.0);\n", + "a2.add(2.0);\n", + "a2.add(3.0);\n", + "a2.add(1, 4.0);\n", + "System.out.println(a2);" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Let's Look at an Example\n", + "\n", + "Consider the following code:" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "ename": "CompilationException", + "evalue": "", + "output_type": "error", + "traceback": [ + "\u001b[1m\u001b[30m| \u001b[1m\u001b[30mh.add(\u001b[0m\u001b[1m\u001b[30m\u001b[41m26.2\u001b[0m\u001b[1m\u001b[30m);\u001b[0m", + "\u001b[1m\u001b[31mincompatible types: double cannot be converted to java.lang.String\u001b[0m", + "" + ] + } + ], + "source": [ + "ArrayList h = new ArrayList<>();\n", + "\n", + "h.add(\"Hello\");\n", + "h.add(\"Hello\");\n", + "h.add(\"HeLLO\");\n", + "h.add(\"Hello\");\n", + "h.add(1, \"Hola\");\n", + "\n", + "h.add(26.2);\n", + "h.add(new String(\"Hello\"));\n", + "h.add(false);" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now, consider this code:" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[Hello, Hola, Hello, HeLLO, Hello, Hello]\n" + ] + } + ], + "source": [ + "ArrayList g = new ArrayList<>();\n", + "\n", + "g.add(\"Hello\");\n", + "g.add(\"Hello\");\n", + "g.add(\"HeLLO\");\n", + "g.add(\"Hello\");\n", + "g.add(1, \"Hola\");\n", + "\n", + "g.add(new String(\"Hello\"));\n", + "\n", + "System.out.println(g);" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Question:** Why does this code work?\n", + "\n", + "Block 1 might not work because we add false, but block 2 doesn't have it so it would work. Also block 1 \n", + "could fail because we can't add 26.2 due to it not being a string." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Deleting Items from an `ArrayList`\n", + "\n", + "`E remove(int index)` : Removes the element at position `index`, and moves the elements at position `index + 1` and higher to the left. It also subtracts one from the list's size. The return value is the element formerly at position `index`." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Hello\n" + ] + } + ], + "source": [ + "// If you are confused of what list g is, look back at the previous code.\n", + "g.remove(3);\n", + "String former = g.remove(0);\n", + "System.out.println(former);" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Updating Items in an `ArrayList`\n", + "\n", + "`E set(int index, E obj)` : Replaces the element at position `index` with `obj` and returns the element formerly at position `index`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Hello\n", + "[Hola, Bonjour, Hello, Hello]\n" + ] + } + ], + "source": [ + "String helloFormer = g.set(1, \"Bonjour\");\n", + "System.out.println(helloFormer);\n", + "System.out.println(g);" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Accessing Items in an `ArrayList`\n", + "\n", + "`E get(int index)` Returns the element at position `index` in the list." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Hello\n", + "[Hola, Bonjour, Hello, Hello]\n" + ] + } + ], + "source": [ + "String hello = g.get(3);\n", + "System.out.println(hello);\n", + "System.out.println(g);" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Passing an `ArrayList` as a Method Parameter" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The only time that it is wise to use `ArrayList` instead of `ArrayList` is when it is as a function parameter and it is only using `ArrayList<>.get(E)` or `ArrayList<>.size()`. Consider the following code:" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Array is empty\n" + ] + } + ], + "source": [ + "private void accessOnly(ArrayList arr) {\n", + " if (arr.size() > 0) {\n", + " System.out.println(arr.get(0)); // Change the index to the one you want to access\n", + " } else {\n", + " System.out.println(\"Array is empty\");\n", + " }\n", + "}\n", + "\n", + "ArrayList myList = new ArrayList();\n", + "accessOnly(myList);" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Returning an `ArrayList` from a Method\n", + "\n", + "In order for you to return an `ArrayList`, the data type must be specified, and the return type must be the same as the return value. Consider the following code:" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[Hello]\n" + ] + } + ], + "source": [ + "private ArrayList returnTheSame() {\n", + " ArrayList arr = new ArrayList(); // Initialize the ArrayList\n", + " arr.add(\"Hello\");\n", + " return arr;\n", + "}\n", + "\n", + "ArrayList result = returnTheSame();\n", + "System.out.println(result);\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Hacks\n", + "\n", + "- The learning objective is that \"Students will be able to represent collections of related object reference data using `ArrayList` objects.\" What does this mean to you?\n", + "\n", + "- Answer the following questions:\n", + "\n", + " * Look back at *Size of the `ArrayList`*. What does the code output and why?\n", + " * Look back at *Adding items to an `ArrayList`*. What does the code output and why? What type of function is `void`, and what will be the return value?\n", + " * Look back at Example 1. What two lines did we remove? Why?\n", + " * If an `ArrayList` is being used as a parameter, what are the only two methods I can use from it? What would happen if I tried to use any other methods?\n", + "\n", + "- Using the Hack Helper, write code that will:\n", + "\n", + " * Add 2 items to the list.\n", + " * Remove an item from the list anywhere of the user's choice.\n", + " * Replace am item anywhere in the list of the user's choice.\n", + " * Get the first and last element of the list, no matter the length.\n", + " * Return the items added, removed, replaced, and the list's size, in one string." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# HACK START \n", + "\n", + "* Look back at *Size of the `ArrayList`*. What does the code output and why?\n", + "\n", + "ANS: it prints out 0 because we initialized the array with no variables, so default size is 0.\n", + "\n", + "* Look back at *Adding items to an `ArrayList`*. What does the code output and why? What type of function is `void`, and what will be the return value?\n", + "\n", + "ANS: the code output was [1.0, 4.0, 2.0, 3.0]. The void function is used with a2.add(1, 4.0); to set 4 at index 1. The return value is null because we are not using it.\n", + "\n", + "\n", + "* Look back at Example 1. What two lines did we remove? Why?\n", + "\n", + "ANS: I don't see an example 1 but at the removal example we remove Hello at index 0 and Hello at index 3, since the code uses removal methods\n", + "that remove the items at the given index.\n", + "\n", + "* If an `ArrayList` is being used as a parameter, what are the only two methods I can use from it? What would happen if I tried to use any other methods?\n", + "\n", + "ANS: I believe the only 2 methods you can use are access methods and methods adding to the list. I think if you tried to use other methods you would\n", + "return an error, but I haven't thoroughly tested this.\n", + "\n", + "\n", + "### Using the Hack Helper, write code that will:\n", + "\n", + " * Add 2 items to the list.\n", + " * Remove an item from the list anywhere of the user's choice.\n", + " * Replace am item anywhere in the list of the user's choice.\n", + " * Get the first and last element of the list, no matter the length.\n", + " * Return the items added, removed, replaced, and the list's size, in one string." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### finished hack" + ] + }, + { + "cell_type": "code", + "execution_count": 39, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[1, 2, 3, 4]\n", + "Enter the index of the element to remove\n", + "removed number4\n", + "[1, 2, 3]\n", + "Enter the index of the element to replace\n", + "Enter the new element\n", + "replaced element1\n", + "beginning element: 3\n", + "end element: 3\n", + "[3, 2, 3]41\n", + "[3, 2, 3]\n" + ] + } + ], + "source": [ + "import java.util.ArrayList;\n", + "import java.util.Scanner;\n", + "\n", + "public class ArrayListMethodsExample {\n", + " private String manipulateList() { \n", + " ArrayList nums = new ArrayList<>();\n", + " Scanner scanner = new Scanner(System.in);\n", + " nums.add(1);\n", + " nums.add(2);\n", + " nums.add(3);\n", + " nums.add(4);\n", + " System.out.println(nums.toString());\n", + " \n", + " System.out.println(\"Enter the index of the element to remove\");\n", + " int index = scanner.nextInt();\n", + " System.out.println(\"removed number\" + nums.get(index));\n", + " int i = nums.get(index);\n", + " nums.remove(index);\n", + " System.out.println(nums.toString());\n", + "\n", + " System.out.println(\"Enter the index of the element to replace\");\n", + " int indexrep = scanner.nextInt();\n", + " System.out.println(\"Enter the new element\");\n", + " int newelement = scanner.nextInt();\n", + " System.out.println(\"replaced element\" + nums.get(indexrep));\n", + " int j = nums.get(indexrep);\n", + "\n", + " nums.set(indexrep, newelement);\n", + " System.out.println(\"beginning element: \" + nums.get(0));\n", + " int length = nums.size();\n", + " length--;\n", + " System.out.println(\"end element: \" + nums.get(length));\n", + " System.out.println(nums.toString() + i + j);\n", + " return nums.toString();\n", + " }\n", + "\n", + " public static void main(String[] args) {\n", + " ArrayList nums = new ArrayList<>();\n", + " ArrayListMethodsExample example = new ArrayListMethodsExample();\n", + " \n", + " String output = example.manipulateList();\n", + " System.out.println(output);\n", + " }\n", + "}\n", + "ArrayListMethodsExample.main(null);" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# 7.3: Traversing Arraylists" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Learning Objectives:\n", + "- With an Arraylist you can traverse objects using a for or while loop.\n", + "\n", + "- Traversing objects is similar to iterating through objects.\n", + "\n", + "### Essential Knowledge:\n", + "- Iteration statements can be used to accsess all the elements in an Arraylist. This is called traversing the Arraylist.\n", + "\n", + "- Deleting elements during a traversal of an Arraylist requires special techniques to avoid skiping elements. This is called traversing the Arraylist.\n", + "\n", + "- The indicies of an Arraylist start at 0; If you try to use any value lower than 0, you will get an *ArrayIndexOutOfBoundsException* error" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "14\n" + ] + } + ], + "source": [ + "import java.util.ArrayList;\n", + "import java.util.List;\n", + "\n", + "public class Main {\n", + " public static void main(String[] args) {\n", + " ArrayList roster = new ArrayList<>();\n", + " roster.add(\"Hello\");\n", + " roster.add(\"World\");\n", + " roster.add(\"Java\");\n", + " \n", + " int sum = 0;\n", + " for (int i = 0; i < roster.size(); i++) {\n", + " String element = roster.get(i);\n", + " if (element != null) {\n", + " sum += element.length();\n", + " }\n", + " }\n", + " System.out.println(sum);\n", + " }\n", + "}\n", + "\n", + "Main.main(null);\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Breakdown:\n", + "- We are first declaring a new arraylist and adding a few elements.\n", + "\n", + "- Next, we set the \"sum\" variable as 0.\n", + "\n", + "- We set a for loop to traverse through the arraylist, iterating through all the indices in the arraylist and adding up the lengths of all the values.\n", + "\n", + "- Lastly, we print it out.\n", + "\n", + "#### Loop Conditions:\n", + "\n", + "- There are a few diffrent loop conditions you can use to traverse an Arraylist:\n", + "\n", + ">First, there are three major parts of a for loop:\n", + ">Initialisation, in which you declare the index, can be modified to change where you want to traverse from.\n", + "\n", + ">Boolean condition, in which you declare the stop condition, can be modified in order to change the index you want to stop traversing in.\n", + "\n", + ">Update, in which you declare how many indexes to go through, can be modified to skip certain indicies and traverse in a certain direction." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Practice:\n", + "Suppose we have an arraylist named grades, and we want to remove the entries that are lower than 70.\n", + "replace the question marks with code to solve the problem:" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "metadata": {}, + "outputs": [ + { + "ename": "CompilationException", + "evalue": "", + "output_type": "error", + "traceback": [ + "\u001b[1m\u001b[30m| \u001b[1m\u001b[30m grades.add(\u001b[0m\u001b[1m\u001b[30m\u001b[41m68.9\u001b[0m\u001b[1m\u001b[30m);\u001b[0m", + "\u001b[1m\u001b[31mincompatible types: double cannot be converted to java.lang.Integer\u001b[0m", + "", + "\u001b[1m\u001b[30m| \u001b[1m\u001b[30m Double grade = \u001b[0m\u001b[1m\u001b[30m\u001b[41mgrades.get(i)\u001b[0m\u001b[1m\u001b[30m;\u001b[0m", + "\u001b[1m\u001b[31mincompatible types: java.lang.Integer cannot be converted to java.lang.Double\u001b[0m", + "" + ] + } + ], + "source": [ + "import java.util.ArrayList;\n", + "import java.util.List;\n", + "\n", + "public class Main {\n", + " public static void main(String[] args) {\n", + " ArrayList grades = new ArrayList<>();\n", + " grades.add(68.9);\n", + " grades.add(71);\n", + " grades.add(100);\n", + " grades.add(80);\n", + " for(Integer i = 0; i < grades.size(); i++){\n", + " if(grades.get(i) < 70){\n", + " grades.remove(i);\n", + " }\n", + " }\n", + " System.out.println(grades);\n", + " }\n", + "}\n", + "Main.main(null);" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Using Enhanced For-Loop With Traversing:\n", + "\n", + "- Using Enhanced for loop is easier to read and write and is also more concise and avoids errors.\n", + "\n", + "- Indexes are not explicitly used and copies of the current element are made at each iteration." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import java.util.ArrayList;\n", + "import java.util.List;\n", + "\n", + "public class Main {\n", + " public static void main(String[] args) {\n", + " List roster = new ArrayList<>();\n", + " roster.add(\"Hello\");\n", + " roster.add(\"World\");\n", + " roster.add(\"Java\");\n", + "\n", + " // Using an enhanced for loop to iterate through the ArrayList\n", + " for (String element : roster) {\n", + " System.out.println(element);\n", + " }\n", + " }\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Common mistakes:\n", + "- Using the Wrong Data Type: Ensure that you declare your ArrayList with the correct data type. Using the wrong data type can lead to type mismatches and errors.\n", + "\n", + "- Incorrect Indexing: Be cautious when using a standard for loop. Off-by-one errors or accessing elements that don't exist can lead to runtime exceptions.\n", + "\n", + "- Modifying the List During Iteration: Modifying an ArrayList (adding or removing elements) while iterating over it can lead to a ConcurrentModificationException. To avoid this, use an Iterator or create a copy of the list if modifications are needed.\n", + "\n", + "- Not Checking for Null Elements: When using enhanced for loops or iterators, check for null elements if there's a possibility that your list contains them to avoid NullPointerExceptions.\n", + "\n", + "- Inefficient Searching: If you need to find a specific element, avoid using a linear search within a loop. Use appropriate methods like contains() or indexOf() to find elements efficiently." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Hacks:\n", + "- Create a scenario which requires the use of arraylist traversal and create code to solve it. \n", + "- Extra points to creative scenarios\n", + "- 90% credit to any working code and scenario\n", + "- 80% credit to incomplete code if you provide explanation of it\n", + "- -10% deduction for late submition" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# scenario\n", + "\n", + "The Mexican drug cartel has kidnapped you and asked you to prove your worth as a programmer by traversing an array list containing\n", + "the names of people who must be killed, and only printing out names that start with \"police:\". " + ] + }, + { + "cell_type": "code", + "execution_count": 42, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "police: samuel\n", + "police: jose\n" + ] + } + ], + "source": [ + "import java.util.ArrayList;\n", + "import java.util.List;\n", + "\n", + "public class Hitlist {\n", + " public static void main(String[] args) {\n", + " List hits = new ArrayList<>();\n", + " hits.add(\"police: samuel\");\n", + " hits.add(\"debt: michael\");\n", + " hits.add(\"police: jose\");\n", + " hits.add(\"rival gang member: mati\");\n", + " hits.add(\"cartel member: james\");\n", + " hits.add(\"cartel member: finn\");\n", + "\n", + "\n", + " for (String name : hits) { // enhanced for loop\n", + " if (name.startsWith(\"police:\")) {\n", + " System.out.println(name);\n", + " }\n", + " }\n", + " }\n", + "}\n", + "\n", + "\n", + "Hitlist.main(null);" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# 7.4: Developing Algorithms Using ArrayLists" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Learning Objectives\n", + "\n", + "In the context of `ArrayList` objects, this module aims to teach the following skills:\n", + "\n", + "a. Iterating through `ArrayLists` using `for` or `while` loops.\n", + "\n", + "b. Iterating through `ArrayLists` using enhanced `for` loops.\n", + "\n", + "In the realm of algorithms, within the context of specific requirements that demand the utilization of `ArrayList` traversals, students will be able to:\n", + "\n", + "- Recognize established algorithms.\n", + "- Customize existing algorithms.\n", + "- Create new algorithms.\n", + "\n", + "### Essential Knowledge\n", + "\n", + "- Iteration statements provide a means to access all the elements stored within an `ArrayList`. This process is referred to as \"traversing the `ArrayList`.\"\n", + "\n", + "- The following methods related to `ArrayLists`, their functions, and appropriate use are covered in the Java Quick Reference:\n", + "\n", + " * `int size()` - Returns the count of elements within the list.\n", + " * `boolean add(E obj)` - Appends the object `obj` to the end of the list and returns `true`.\n", + " * `void add(int index, E obj)` - Inserts `obj` at the specified `index`, shifting elements at and above that position to the right (incrementing their indices by 1) and increasing the list's size by 1.\n", + " * `E get(int index)` - Retrieves the element at the given `index` in the list.\n", + " * `E set(int index, E obj)` - Replaces the element at the specified `index` with `obj` and returns the previous element at that index.\n", + " * `E remove(int index)` - Deletes the element at the specified `index`, shifting all subsequent elements one index to the left, reducing the list's size by one, and returning the removed element.\n", + "\n", + "- There exist established algorithms for `ArrayLists` that make use of traversals to:\n", + "\n", + " * Insert elements.\n", + " * Remove elements.\n", + " * Apply the same algorithms commonly used with 1D arrays." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Popcorn Hacks:\n", + "\n", + "Before you uncomment the code and run it, guess what the code will do based on what you've learned.\n", + "\n", + "the code will print the max value out of al the items in the Array." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Let's Look at an Example (Example 1)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "public class ArrayListExample {\n", + " private double findMax(double[] values) {\n", + " // double max = values[0];\n", + " \n", + " //for (int index = 1; index < values.length; index++) {\n", + " // if (values[index] > max) {\n", + " // max = values[index];\n", + " // }\n", + " //}\n", + " \n", + " // return max;\n", + " }\n", + " \n", + " public static void main(String[] args) {\n", + " double[] nums = {1.0, 3.0, 2.0, 2.0, 1.0, 69.0, 2.0, 4.0, 6.0, 2.0, 5.0, 10.0};\n", + " ArrayListExample example = new ArrayListExample();\n", + " double max = example.findMax(nums);\n", + " System.out.println(\"Maximum value: \" + max);\n", + " }\n", + "}\n", + "\n", + "ArrayListExample.main(null);" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Take a closer look at the `findMax()` method. It takes in a list of doubles as parameters. It will then use a `for` loop to find the maximum value in the list. Now, using what we know, can we replace the list of doubles with an ArrayList of Doubles? We sure can! Take a look at how we can use ArrayList to do just that:\n", + "\n", + "This code still gets max but it uses an ArrayList instead of an array of doubles. " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "public class ArrayListExample {\n", + " private double findMax(ArrayList values) {\n", + " // double max = values.get(0);\n", + " \n", + " //for (int index = 1; index < values.size(); index++) {\n", + " // if (values.get(index) > max) {\n", + " // max = values.get(index);\n", + " // }\n", + " //}\n", + " \n", + " //return max;\n", + " }\n", + " \n", + " public static void main(String[] args) {\n", + " ArrayList nums = new ArrayList<>();\n", + " nums.add(1.0);\n", + " nums.add(3.0);\n", + " nums.add(2.0);\n", + " nums.add(2.0);\n", + " nums.add(1.0);\n", + " nums.add(69.0);\n", + " nums.add(2.0);\n", + " nums.add(4.0);\n", + " nums.add(6.0);\n", + " nums.add(2.0);\n", + " nums.add(5.0);\n", + " nums.add(10.0);\n", + " \n", + " ArrayListExample example = new ArrayListExample();\n", + " double max = example.findMax(nums);\n", + " System.out.println(\"Maximum value: \" + max);\n", + " }\n", + "}\n", + "\n", + "ArrayListExample.main(null);" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Let's Look at an Example (Example 2)\n", + "\n", + "Take a look at this code:\n", + "\n", + "This code uses a regular array, and finds minimum instead of max. Now we get the max value and set minimum to values less than max, then a value less \n", + "that can be set to minimum if one is found." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "public class ArrayListExample {\n", + " private int findMin(int[] values) {\n", + " //int min = Integer.MAX_VALUE;\n", + " //for (int currentValue : values) {\n", + " // if (currentValue < min) {\n", + " // min = currentValue;\n", + " // }\n", + " //}\n", + " return min;\n", + " }\n", + "\n", + " public static void main(String[] args) {\n", + " int[] nums = {420, 703, 2034, 582, 1047, 4545};\n", + " ArrayListExample example = new ArrayListExample();\n", + " int min = example.findMin(nums);\n", + " System.out.println(\"Minimum value: \" + min);\n", + " }\n", + "}\n", + "\n", + "ArrayListExample.main(null);" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now, can we use ArrayLists to make this code better? We sure can! Take a look at the new and improved code that uses ArrayLists:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "public class ArrayListExample {\n", + " private int findMin(ArrayList values) {\n", + " //int min = Integer.MAX_VALUE;\n", + " //for (int currentValue : values) {\n", + " // if (currentValue < min) {\n", + " // min = currentValue;\n", + " // }\n", + " //}\n", + " return min;\n", + " }\n", + "\n", + " public static void main(String[] args) {\n", + " ArrayList nums = new ArrayList<>();\n", + " nums.add(420);\n", + " nums.add(703);\n", + " nums.add(2034);\n", + " nums.add(582);\n", + " nums.add(1047);\n", + " nums.add(4545);\n", + " ArrayListExample example = new ArrayListExample();\n", + " int min = example.findMin(nums);\n", + " System.out.println(\"Minimum value: \" + min);\n", + " }\n", + "}\n", + "\n", + "ArrayListExample.main(null);" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Hacks\n", + "\n", + "- Answer the questions: \n", + " * Look back at the examples. What's similar? What's different?\n", + " * Why do we use `ArrayList`? Why not just regular lists?\n", + "- Demonstrate at least two `ArrayList` methods that aren't `ArrayList<>.size()` and `ArrayList<>.get()`.\n", + "- Write the method `findSum()` using the Hack Helper and incorporating `ArrayList`.\n", + "\n", + "# question answers \n", + " \n", + "* Look back at the examples. What's similar? What's different?\n", + "\n", + "both of them iterate through the lists with a for loop, however the usage of arraylist vs array means that we also pass arraylist in func\n", + "over array. I think thats only key difference so far. \n", + "\n", + "* Why do we use `ArrayList`? Why not just regular lists?\n", + "\n", + "ANS: key difference is arraylists can be added onto while arrays are fixed in length." + ] + }, + { + "cell_type": "code", + "execution_count": 47, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[4, 5]\n", + "[]\n" + ] + } + ], + "source": [ + "// 2 methods hack\n", + "\n", + "ArrayList test = new ArrayList<>();\n", + "\n", + "test.add(4); // add is one method we use to add to list\n", + "test.add(5); \n", + "\n", + "System.out.println(test);\n", + "\n", + "test.clear(); //this method resets the list \n", + "\n", + "System.out.println(test);\n" + ] + }, + { + "cell_type": "code", + "execution_count": 45, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "19\n" + ] + } + ], + "source": [ + "// sum hack\n", + "public class ArrayListHacks {\n", + " private int findSum(ArrayList values) {\n", + " int sum = 0;\n", + " for (int i = 0; i < values.size(); i++) {\n", + " sum += values.get(i);\n", + " } \n", + " System.out.println(sum);\n", + " return(sum);\n", + "}\n", + "\n", + " public static void main(String[] args) {\n", + " ArrayList nums = new ArrayList<>();\n", + " nums.add(0);\n", + " nums.add(1);\n", + " nums.add(2);\n", + " nums.add(3);\n", + " nums.add(5);\n", + " nums.add(8);\n", + "\n", + " ArrayListHacks hacks = new ArrayListHacks();\n", + " hacks.findSum(nums);\n", + " }\n", + "}\n", + "\n", + "ArrayListHacks.main(null);" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# 7.5 Searching\n", + "\n", + "### Learning Objectives\n", + "- Apply sequential/linear search algorithms to search for specific information in array or ``arraylist`` objects\n", + "\n", + "### Essential Knowledge:\n", + "- Sequential/linear search alogorithms check each element in order untill the desired value is found or all elementsin the array or ``arraylist`` have been checked\n", + "\n", + "### Search Process\n", + "- Linear searching fits a standard for loop perfectly! We need to specify each element, one at a time, and do not need to track the index after execution\n", + "\n", + "- Inside the for loop, we retrieve the value from the structure at the specified index and compare it to the searched value\n", + "\n", + "- If it matches we return the index, otherwise we keep looking!" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Searching Linear Structures\n", + "\n", + "#### Finding information with a computer is something we need to know how to do. Linear search algorithms are BEST used when we do not have any idea about the order of the data and so we need to look at each element to determine if what we are looking for is in fact inside the array or ``ArrayList``.\n", + "\n", + "#### When searching, we do need to remember that different data types require comparisons!\n", + "- When looking at ``int`` values, the == operator is the tool to use!\n", + "- When searching for a ``double`` value, we need to make sure the value is close enough by doing some math!\n", + "- ``Object`` instances should always use the ``.equals(otheThing)`` method to check for a match!" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Searching an ``ArrayList`` of Double" + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "metadata": {}, + "outputs": [], + "source": [ + "public int where(double magicNumber, ArrayList realNumbers, double delta)\n", + "{\n", + " for (int index = 0; index < realNumbers.size(); index++)\n", + " {\n", + " if (Math.abs(magicNumber - realNumbers.get(index)) < delta)\n", + " {\n", + " return index;\n", + " }\n", + " }\n", + " return -1;\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Explanation\n", + "> The where function searches through a list of numbers to find and return the position of the first number that is very close to a specific target number, known as magicNumber. If no number in the list is close enough to the target number, the function returns -1, indicating that no match was found." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Searching an ``ArrayList`` of book for a ``String``" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "public int findTheWord(String searchedPhrase, ArrayList myBooks)\n", + "{\n", + " for (int index = 0; index < myBooks.size(); index++)\n", + " {\n", + " Book currentBook = myBooks.get(index);\n", + " String currentPhrase = currentBook.getDescription();\n", + " if(currentPhrase.equals(searchedPhrase))\n", + " {\n", + " return index;\n", + " }\n", + " }\n", + " return -1;\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Explanation\n", + ">This little code snippet is like a treasure hunt through a collection of books; it's on a mission to find the one book whose description matches exactly with a special phrase you're looking for. If it finds the perfect match, it'll excitedly tell you where it is in the collection, but if not, it'll sadly let you know with a -1 that the search was a bust.\n", + "\n", + "\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Questions\n", + "\n", + "#### Should we use == when looking for an Object?\n", + "> No, that only will return true if the variable and the element stored at that index point to the same memory, are aliases of each other\n", + "\n", + "#### Why did we subtract the double values?\n", + "> To make sure that the lack of preciosin that is inherit in the data type is handled within our code" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Why does order sometimes matter?\n", + "\n", + "#### When searching for a value to remove from a list, if we search forward we have to make sure to adjust the loop control variable, or we might skip what we are looking for when removing!" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# 7.6 Sorting\n", + "\n", + "### Learning Objectives\n", + "- Apply selection sort and insertion sort algorithms to sort the elements of array or ``ArrayList`` objects.\n", + "\n", + "### Essential Knowledge:\n", + "- Selection sort and insertion sort are iterative sorting algorithms that can be used to sort elements in an array or ``ArrayList``.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Selection Sort\n", + "> This is one of the easiest sorts to demonstrate. The selection sort identifies either the maximum or minimum of the compared values and iterates over the structure checking if the item stored at the index matches that condition, if so, it will swap the value stored at that index and continue. This implementation uses a helper method to perform the swap operation since variables can hold only one value at a time!\n", + "\n", + "Example:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "// with normal arrays\n", + "for (int outerLoop = 0; outerLoop < myDucks.length; outerLoop ++)\n", + "{\n", + " int minIndex = outerLoop;\n", + " for (int inner = outerLoop +1; inner < myDucks.length; inner++)\n", + " {\n", + " if (myDucks[inner].compareT(myDucks[minIndex]) < 0)\n", + " {\n", + " minIndex = inner;\n", + " }\n", + " }\n", + " if (minIndex != outerLoop)\n", + " {\n", + " swapItems(minIndex, outerloop, myDucks);\n", + " }\n", + "}\n", + "\n", + "// with array lists\n", + "for (int outerLoop = 0; outerLoop < myDucks.size(); outerLoop++) {\n", + " int minIndex = outerLoop;\n", + " for (int inner = outerLoop + 1; inner < myDucks.size(); inner++) \n", + " {\n", + " if (myDucks.get(inner).compareT(myDucks.get(minIndex)) < 0) \n", + " {\n", + " minIndex = inner;\n", + " }\n", + " }\n", + " if (minIndex != outerLoop) {\n", + " swapItems(minIndex, outerLoop, myDucks); \n", + " }\n", + "}\n", + "/*\n", + "This code performs a selection sort on the myDucks ArrayList, ordering its elements based on the compareT method. \n", + "During each iteration of the outer loop, it finds the index of the minimum element in the unsorted portion of the list and swaps it with the first element of the unsorted portion.\n", + " */ " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Insertion Sort Algorithm\n", + "> The insertion sort is characterized by building a sorted structure as it proceeds. It inserts each value it finds at the appropriate location in the data structure. This is often accomplished by using a while loop as the inner loop.\n", + "\n", + "Example:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "for (int outer = 1; outer < randomList.size(); outer++)\n", + "{\n", + " DebugDuck tested = randomList.get(outer);\n", + " int inner = outer -1;\n", + "\n", + " while ( innter >= 0 && tested.compareTo(randomList.get(inner)) < 0)\n", + " {\n", + " ramdomList.set(inner +1, randomList.get(inner));\n", + " inner--;\n", + " }\n", + " randomList.set(inner +1, tested)\n", + "}\n", + "// This code arranges a list of DebugDuck objects in order using the insertion sort method, \n", + "// by moving through the list and putting each item in its proper place one by one." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# 7.7: Ethical Issues around Data Collection" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Learning Objectives:\n", + "- Explaining the risks of privacy from collecting and storing personal data on computer systems.\n", + "\n", + "### Essential Knowledge:\n", + "- When using the computer, personal privacy is at risk. Programmers should attempt to safeguard personal privacy." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Privacy Protection:\n", + "- A simple way to protect privacy is to delete personal user info after done using it.\n", + "- Another way is to minimize the amount of data used by the program in order to protect privacy.\n", + "- Anonymizing personal data via the object method *hashCode()* is another way." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Hacks:\n", + "- Think of other ways to safeguard user privacy (any other method not listed is fine)\n", + "- Extra points to creative solutions\n", + "- 90% credit to any solution\n", + "- 80% credit to incomplete solution (how did you do that?)\n", + "- -10% deduction for late submition" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# answer\n", + "\n", + "You can use fake or \"burner\" information to bypass requests for information without giving critical information.\n", + "\n", + "EXAMPLEs: \n", + "\n", + "use proton mail (https://proton.me/mail) to create a burner email you can use instead of your real email.\n", + "\n", + "Use google voice (https://voice.google.com/u/0/) to get a 2nd phone number you can give instead of your real phone number.\n", + "\n", + "other information like names, addresses, etc. are easy to fake. You can usually make it up on the spot.\n", + "\n", + "if your very serious, you can use privacy (https://privacy.com/) to hide credit card information when making online purchases.\n", + "\n", + "If you want to be even more secure, using a free vpn (proton vpn, windscribe, tunnelbear, etc.) is a good idea.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Grading:\n", + "\n", + "- 7.2 Hacks (0.19)\n", + "- 7.3 Hacks (0.19)\n", + "- 7.4 Hacks (0.19)\n", + "- 7.7 Hacks (0.19)\n", + "- Popcorn Hacks (0.19)\n", + "- Anything else creative or above-and-beyond showing your understanding of ArrayLists (0.05)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Java", + "language": "java", + "name": "java" + }, + "language_info": { + "codemirror_mode": "java", + "file_extension": ".jshell", + "mimetype": "text/x-java-source", + "name": "java", + "pygments_lexer": "java", + "version": "20.0.2+9" + }, + "orig_nbformat": 4 + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/_notebooks/2023-10-26-Unit8.ipynb b/_notebooks/2023-10-26-Unit8.ipynb new file mode 100755 index 0000000..b2725fa --- /dev/null +++ b/_notebooks/2023-10-26-Unit8.ipynb @@ -0,0 +1,1891 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "layout: post\n", + "title: Unit 8 Lesson - 2D Arrays\n", + "description: Group Lesson on Unit 8 which covers 2D arrays\n", + "toc: true\n", + "courses: { compsci: {week: 0} } \n", + "type: tangibles\n", + "---" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# 8.1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## What is a 2D array\n", + "\n", + "A 2D array is an array of arrays.\n", + "\n", + "![image.png](https://github.com/Krishiv111/KPNSTeam/assets/111609656/fc04c520-ec82-414e-897c-0b0753c73f8d)\n", + "\n", + "## Why use 2D arrays?\n", + "\n", + "1D array of people \n", + "```\n", + "{\n", + "\"Patrick Mahomes\"\n", + "\"Mr. Mortensen\"\n", + "\"Taylor Swift\"\n", + "\"Margot Robbie\"\n", + "}\n", + "```\n", + "\n", + "2D array of men and women \n", + "```\n", + "{\n", + "{ \"Patrick Mahomes\", \"Mr. Mortensen\"} ,\n", + "{\"Taylor Swift\", \"Margot Robbie\"}\n", + "}\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Declaring a 2D Array\n", + "\n", + "Very similar to declaring a 1D array.\n", + "\n", + "```\n", + "DataType[] name // 1D array\n", + "DataType[][] name // 2D array\n", + "```\n" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [], + "source": [ + "int[][] intArray; //primitive\n", + "String[][] stringArray; //object" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Initalizing a 2D Array\n" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1 2 3 4 \n", + "5 6 7 8 \n", + "9 10 11 12 \n" + ] + } + ], + "source": [ + "public class TwoDArrayExample {\n", + " public static void main(String[] args) {\n", + " int rows = 3;\n", + " int cols = 4;\n", + " \n", + " // Declare and initialize a 2D array\n", + " int[][] myArray = {\n", + " {1, 2, 3, 4},\n", + " {5, 6, 7, 8},\n", + " {9, 10, 11, 12}\n", + " };\n", + " \n", + " // Access and print elements\n", + " for (int i = 0; i < rows; i++) {\n", + " for (int j = 0; j < cols; j++) {\n", + " System.out.print(myArray[i][j] + \" \");\n", + " }\n", + " System.out.println();\n", + " }\n", + " }\n", + "}\n", + "TwoDArrayExample.main(null)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Popcorn HACK 1" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [], + "source": [ + "public class TwoDArrayHack1 {\n", + " public static void main(String[] args) {\n", + " int rows = 5;\n", + " int columns = 4;\n", + " // Declare and initialize a 2D array with 5 rows (arrays) and 4 columns (elements per array) of int data type.\n", + " int[][] Array = {\n", + " \n", + "\n", + " {1, 2, 3, 4},\n", + " {5, 6, 7, 8},\n", + " {9, 10, 11, 12},\n", + " {13,14, 15, 16},\n", + " {17,18, 19, 20}\n", + "\n", + " };\n", + " \n", + " }\n", + "\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# More Initializing and Accessing Array Elements of a 2D Array" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Student Name: Yuri\n", + "Student Age: 16\n", + "Name: Gorlcok\n", + "Age: 135\n" + ] + } + ], + "source": [ + "class Student {\n", + " private String name;\n", + " private int age;\n", + "\n", + " // Constructor to initialize a Student object\n", + " public Student(String name, int age) {\n", + " this.name = name;\n", + " this.age = age;\n", + " }\n", + "\n", + " // Getter method to retrieve the student's name\n", + " public String getName() {\n", + " return name;\n", + " }\n", + "\n", + " // Getter method to retrieve the student's age\n", + " public int getAge() {\n", + " return age;\n", + " }\n", + "\n", + " // Method to print student information\n", + " public void printInfo() {\n", + " System.out.println(\"Name: \" + name);\n", + " System.out.println(\"Age: \" + age);\n", + " }\n", + "}\n", + "\n", + "public class TwoDArrayHack2 {\n", + " public static void main(String[] args) {\n", + " // Declare and initialize a 2D array with 6 rows and 6 columns of Student objects\n", + " Student[][] studentArray = new Student[6][6];\n", + "\n", + " // Creating and initializing Student objects in the array\n", + " studentArray[0][0] = new Student(\"Yuri\", 16);\n", + " studentArray[1][2] = new Student(\"Gorlcok\", 135);\n", + "\n", + " // Accessing and using the Student objects' methods\n", + " String studentName = studentArray[0][0].getName();\n", + " int studentAge = studentArray[0][0].getAge();\n", + "\n", + " System.out.println(\"Student Name: \" + studentName);\n", + " System.out.println(\"Student Age: \" + studentAge);\n", + "\n", + " studentArray[1][2].printInfo();\n", + " }\n", + "}\n", + "TwoDArrayHack2.main(null)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# More Initializing + Accessing + Popcorn HACK 2" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Team: Team17\n", + "City: City17\n", + "Championships: 4\n", + "Team: Team21\n", + "City: City21\n", + "Championships: 0\n", + "Team: Team3\n", + "City: City3\n", + "Championships: 1\n" + ] + } + ], + "source": [ + "class NFLTeams {\n", + " private String teamName;\n", + " private String city;\n", + " private int championships;\n", + "\n", + " // Constructor to initialize NFL team data\n", + " public NFLTeams(String teamName, String city, int championships) {\n", + " this.teamName = teamName;\n", + " this.city = city;\n", + " this.championships = championships;\n", + " }\n", + "\n", + " // Method to display team information\n", + " public void displayTeamInfo() {\n", + " System.out.println(\"Team: \" + teamName);\n", + " System.out.println(\"City: \" + city);\n", + " System.out.println(\"Championships: \" + championships);\n", + " }\n", + "}\n", + "\n", + "public class NFLTeams2DArray {\n", + " public static void main(String[] args) {\n", + " // Declare a 2D array of NFLTeams to store data for 5 teams and 5 columns\n", + " NFLTeams[][] nflArray = {\n", + " {new NFLTeams(\"Team1\", \"City1\", 2), new NFLTeams(\"Team2\", \"City2\", 3), new NFLTeams(\"Team3\", \"City3\", 1), new NFLTeams(\"Team4\", \"City4\", 0), new NFLTeams(\"Team5\", \"City5\", 5)},\n", + " {new NFLTeams(\"Team6\", \"City6\", 3), new NFLTeams(\"Team7\", \"City7\", 4), new NFLTeams(\"Team8\", \"City8\", 0), new NFLTeams(\"Team9\", \"City9\", 1), new NFLTeams(\"Team10\", \"City10\", 2)},\n", + " {new NFLTeams(\"Team11\", \"City11\", 1), new NFLTeams(\"Team12\", \"City12\", 0), new NFLTeams(\"Team13\", \"City13\", 3), new NFLTeams(\"Team14\", \"City14\", 2), new NFLTeams(\"Team15\", \"City15\", 4)},\n", + " {new NFLTeams(\"Team16\", \"City16\", 2), new NFLTeams(\"Team17\", \"City17\", 4), new NFLTeams(\"Team18\", \"City18\", 1), new NFLTeams(\"Team19\", \"City19\", 5), new NFLTeams(\"Team20\", \"City20\", 3)},\n", + " {new NFLTeams(\"Team21\", \"City21\", 0), new NFLTeams(\"Team22\", \"City22\", 2), new NFLTeams(\"Team23\", \"City23\", 5), new NFLTeams(\"Team24\", \"City24\", 3), new NFLTeams(\"Team25\", \"City25\", 1)}\n", + " };\n", + "\n", + " // Print out Team 17's Team info\n", + " nflArray[3][1].displayTeamInfo();\n", + " \n", + " // Print out Team 21's Team Info\n", + "\n", + " nflArray[4][0].displayTeamInfo();\n", + "\n", + " // Print out Team 3's team Info\n", + "\n", + " nflArray[0][2].displayTeamInfo();\n", + "\n", + " }\n", + "}\n", + "NFLTeams2DArray.main(null)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Updating 2D Arrays" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Original 2D Array:\n", + "1 2 3 \n", + "4 5 6 \n", + "7 8 9 \n", + "\n", + "Updated 2D Array:\n", + "11 2 3 \n", + "4 22 6 \n", + "7 8 33 \n" + ] + } + ], + "source": [ + "public class Update2DArray {\n", + " public static void main(String[] args) {\n", + " // Create a 3x3 2D array of integers\n", + " int[][] matrix = {\n", + " {1, 2, 3},\n", + " {4, 5, 6},\n", + " {7, 8, 9}\n", + " };\n", + "\n", + " // Display the original 2D array\n", + " System.out.println(\"Original 2D Array:\");\n", + " printArray(matrix);\n", + "\n", + " // Update specific elements in the array\n", + " matrix[0][0] = 11; // Update the element in the first row, first column\n", + " matrix[1][1] = 22; // Update the element in the second row, second column\n", + " matrix[2][2] = 33; // Update the element in the third row, third column\n", + "\n", + " // Display the updated 2D array\n", + " System.out.println(\"\\nUpdated 2D Array:\");\n", + " printArray(matrix);\n", + " }\n", + "\n", + " // Helper method to print the 2D array\n", + " public static void printArray(int[][] arr) {\n", + " for (int i = 0; i < arr.length; i++) {\n", + " for (int j = 0; j < arr[i].length; j++) {\n", + " System.out.print(arr[i][j] + \" \");\n", + " }\n", + " System.out.println();\n", + " }\n", + " }\n", + "}\n", + "Update2DArray.main(null)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Popcorn HACK 3" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "250 2 3 4 125 \n", + "6 7 135 9 10 \n", + "11 12 69 14 15 \n", + "16 17 18 19 20 \n", + "21 22 23 24 96 \n" + ] + } + ], + "source": [ + "public class Update2DArrayHACK {\n", + "\n", + " // Helper method to print the 2D integer array\n", + " public static void printIntArray(int[][] arr) {\n", + " for (int i = 0; i < arr.length; i++) {\n", + " for (int j = 0; j < arr[i].length; j++) {\n", + " System.out.print(arr[i][j] + \" \");\n", + " }\n", + " System.out.println();\n", + " }\n", + " }\n", + "\n", + " public static void main(String[] args) {\n", + "\n", + " // Declare and Initialize a 2D integer array with the same dimensions (5x5)\n", + " int[][] integerArray = {\n", + " {1, 2, 3, 4, 5},\n", + " {6, 7, 8, 9, 10},\n", + " {11, 12, 13, 14, 15},\n", + " {16, 17, 18, 19, 20},\n", + " {21, 22, 23, 24, 25}\n", + " };\n", + "\n", + " // Update the element in the first row, first column to 250\n", + " integerArray[0][0] = 250; \n", + " // Update the element in the third row, third column to 69\n", + " integerArray[2][2] = 69; \n", + "\n", + " // Update the element in the fifth row, fifth column to 96\n", + " integerArray[4][4] = 96; \n", + "\n", + " // Update the element in the first row, fifth column to 125\n", + " integerArray[0][4] = 125; \n", + " // Update the element in the second row, third column to 135 \n", + " integerArray[1][2] = 135; \n", + " // Display the updated 2D integer array\n", + " printIntArray(integerArray);\n", + " }\n", + "}\n", + "Update2DArrayHACK.main(null)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Popcorn HACK 4 - Review Quiz\n", + "\n", + "```\n", + "What is a 2D array?\n", + "A. A single row of elements.\n", + "B. A data structure with rows and columns.\n", + "C. A list of 2 elements.\n", + "D. A binary representation of data.\n", + "\n", + "ANS: B\n", + "\n", + "How do you declare a 2D array in Java?\n", + "A. int myArray = new int[3][3];\n", + "B. 2DArray myArray = new 2DArray[3][3];\n", + "C. int[][] myArray;\n", + "D. myArray = declare 2D array;\n", + "\n", + "ANS: C\n", + "\n", + "How do you access an element in a 2D array at row 2 and column 3?\n", + "A. myArray[3][2]\n", + "B. myArray[2][3]\n", + "C. myArray[1][2]\n", + "D. myArray[2][1]\n", + "\n", + "ANS: C\n", + "\n", + "What is the purpose of initializing a 2D array?\n", + "A. To specify its data type.\n", + "B. To allocate memory for the array.\n", + "C. To access its elements.\n", + "D. To declare the number of rows and columns.\n", + "\n", + "ANS: D\n", + "\n", + "In a 2D array, what does myArray[2][3] represent?\n", + "A. The element in the second row and third column.\n", + "B. The element in the third row and second column.\n", + "C. The element in the third row and third column.\n", + "D. The element in the second column and third row.\n", + "\n", + "ANS: the element is the third row and the FOURTH column \n", + "\n", + "\n", + "What happens when you update an element in a 2D array in Java?\n", + "A. The entire array is cleared.\n", + "B. Only the updated element is affected.\n", + "C. The entire row is shifted.\n", + "D. The element is removed from the array.\n", + "\n", + "ANS: B\n", + "\n", + "Which of the following represents a 2D array with 4 rows and 3 columns in Java?\n", + "A. int[4][3] myArray;\n", + "B. myArray[4,3] = int;\n", + "C. int[3][4] myArray;\n", + "D. myArray[3][4] = int;\n", + "```\n", + "\n", + "ANS: C" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## HACKS" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Finish Popcorn HACKS, type DONE Here when you finish\n", + "\n", + "Done\n", + "\n", + "## HACK 1\n", + "- Create a class (for object 2D arrays), and declare and initialize a 2D array\n", + "- Show updating a 2D array with object functionality\n" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1 2 3 4 \n", + "5 6 7 8 \n", + "9 10 11 12 \n", + "13 14 15 16 \n", + "17 18 19 20 \n" + ] + } + ], + "source": [ + "// HACK 1 ANSWER\n", + "\n", + "public class TwoDArrayHack1 {\n", + " public static void main(String[] args) {\n", + " int rows = 5; \n", + " int columns = 4;\n", + " int[][] Array = {\n", + " \n", + "\n", + " {1, 2, 3, 4},\n", + " {5, 6, 7, 8},\n", + " {9, 10, 11, 12},\n", + " {13,14, 15, 16},\n", + " {17,18, 19, 20}\n", + "\n", + " };\n", + " for (int i = 0; i < Array.length; i++) { \n", + " for (int j = 0; j < Array[i].length; j++) {\n", + " System.out.print(Array[i][j] + \" \");\n", + " }\n", + " System.out.println();\n", + " }\n", + " }\n", + " }\n", + "\n", + "TwoDArrayHack1.main(null);\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# experimental version which uses methods to accomplish the same feat" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1 2 3 4 \n", + "5 6 7 8 \n", + "9 10 11 12 \n", + "13 14 15 16 \n", + "17 18 19 20 \n" + ] + } + ], + "source": [ + "public class TwoDArrayHack1 {\n", + " public static void main(String[] args) {\n", + " int rows = 5;\n", + " int columns = 4;\n", + " TwoDArray array = new TwoDArray(rows, columns);\n", + " \n", + " array.setData(0, 0, 1);\n", + " array.setData(0, 1, 2);\n", + " array.setData(0, 2, 3);\n", + " array.setData(0, 3, 4);\n", + " array.setData(1, 0, 5);\n", + " array.setData(1, 1, 6);\n", + " array.setData(1, 2, 7);\n", + " array.setData(1, 3, 8);\n", + " array.setData(2, 0, 9);\n", + " array.setData(2, 1, 10);\n", + " array.setData(2, 2, 11);\n", + " array.setData(2, 3, 12);\n", + " array.setData(3, 0, 13);\n", + " array.setData(3, 1, 14);\n", + " array.setData(3, 2, 15);\n", + " array.setData(3, 3, 16);\n", + " array.setData(4, 0, 17);\n", + " array.setData(4, 1, 18);\n", + " array.setData(4, 2, 19);\n", + " array.setData(4, 3, 20);\n", + " \n", + " array.printData();\n", + " }\n", + "}\n", + "\n", + "class TwoDArray {\n", + " private int[][] data;\n", + " \n", + " public TwoDArray(int rows, int columns) {\n", + " data = new int[rows][columns];\n", + " }\n", + " \n", + " public void setData(int row, int col, int value) {\n", + " data[row][col] = value;\n", + " }\n", + " \n", + " public void printData() {\n", + " for (int i = 0; i < data.length; i++) {\n", + " for (int j = 0; j < data[i].length; j++) {\n", + " System.out.print(data[i][j] + \" \");\n", + " }\n", + " System.out.println();\n", + " }\n", + " }\n", + "}\n", + "\n", + "TwoDArrayHack1.main(null);" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# 8.2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Traversing\n", + "- Traversing is known to acsess each element in a array also known as itteration, in the case of 2D Arrays we will acsess elements in the 2D array, but we will need to use specfiic methods of nested for loops, and enhanced for loops." + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Element at index 0 is: 1\n", + "Element at index 1 is: 2\n", + "Element at index 2 is: 3\n", + "Element at index 3 is: 4\n", + "Element at index 4 is: 5\n" + ] + } + ], + "source": [ + "public class ArrayTraversalExample {\n", + " public static void main(String[] args) {\n", + " // Array that is created in order to be traversed/itterate through\n", + " int[] numbers = {1, 2, 3, 4, 5};\n", + "\n", + " // Traverse the array and print each element\n", + " // How this works: 1. First it sets i to 0 in order to keep track of the index by using a for loop\n", + " // Then it checks if the number is greater index if so then it will continue\n", + " // uses i++ to continue to go through the indicies \n", + " // prints outs the number if greater than index\n", + " for (int i = 0; i < numbers.length; i++) {\n", + " System.out.println(\"Element at index \" + i + \" is: \" + numbers[i]);\n", + " }\n", + " }\n", + "}\n", + "ArrayTraversalExample.main(null)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Nested For Loop\n", + "- A nested for loop is a type of loop that contains an inner loop and outer loop, allowing to create a two dimensional piece that will now allow us to traverse through 2D Arrays." + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1 2 \n", + "1 2 \n", + "1 2 \n", + "1 2 \n" + ] + } + ], + "source": [ + "public class NestedLoops {\n", + " public static void main(String[] args) {\n", + " for (int outer = 1; outer < 5; outer++) {\n", + " for (int inner = 1; inner < 3; inner++) {\n", + " System.out.print(inner + \" \");\n", + " }\n", + " System.out.println();\n", + " }\n", + " }\n", + "}\n", + "NestedLoops.main(null)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Enhanced For Loop\n" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Apple\n", + "Banana\n", + "Cherry\n", + "Date\n", + "Fig\n" + ] + } + ], + "source": [ + "public class EnhancedForLoopExample {\n", + " public static void main(String[] args) {\n", + " String[] fruits = {\"Apple\", \"Banana\", \"Cherry\", \"Date\", \"Fig\"};\n", + "\n", + " // Here you use a en enhanced for loop to itterate through the array of strings\n", + " for (String fruit : fruits) {\n", + " System.out.println(fruit);\n", + " }\n", + " }\n", + "}\n", + "EnhancedForLoopExample.main(null)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Cumulative Knowledge \n", + "- Hint: Popcorn Hacks\n", + "- From the class discussion fill these out\n", + "\n", + "- **What does traverse mean?**\n", + "\n", + "ANS: traverse means to travel, in this case travelling through the 2d array\n", + "\n", + "- **What is a nested loop**\n", + "\n", + "ANS: its a loop in a loop\n", + "\n", + "- **What is an enhanced for loop**\n", + "\n", + "ANS: its a special for loop that goes through each item without need of intitializing value and incrementing it" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Nested Loops traversing through a 2D Array" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1 2 3 \n", + "4 5 6 \n", + "7 8 9 \n" + ] + } + ], + "source": [ + "public class TwoDArrayTraversal {\n", + " public static void main(String[] args) {\n", + " // First Create the 2D array\n", + " int[][] twoDArray = {\n", + " {1, 2, 3},\n", + " {4, 5, 6},\n", + " {7, 8, 9}\n", + " };\n", + " \n", + " // Using a Nested loops to traverse the 2D array\n", + " for (int row = 0; row < 3; row++) {\n", + " for (int col = 0; col < 3; col++) {\n", + " int element = twoDArray[row][col];\n", + " System.out.print(element + \" \");\n", + " }\n", + " System.out.println(); \n", + " }\n", + " }\n", + "}\n", + "TwoDArrayTraversal.main(null)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Popcorn Hack\n", + "- What would you replace the question marks with if we didnt know the dimensions of this 2D Array\n", + "\n", + "ANS: we replace it with the length" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1 2 3 \n", + "4 5 6 \n", + "7 8 9 \n" + ] + } + ], + "source": [ + "public class TwoDArrayTraversal {\n", + " public static void main(String[] args) {\n", + " // First Create the 2D array\n", + " int[][] twoDArray = {\n", + " {1, 2, 3},\n", + " {4, 5, 6},\n", + " {7, 8, 9}\n", + " };\n", + " \n", + " // Using a Nested loops to traverse the 2D array\n", + " for (int row = 0; row < twoDArray.length; row++) { //grid makes sense becuase it gives you dimension\n", + " for (int col = 0; col < twoDArray[row].length; col++) { // colliumn makes senseas it starts at 0 \n", + " int element = twoDArray[row][col];\n", + " System.out.print(element + \" \");\n", + " }\n", + " System.out.println(); \n", + " }\n", + " }\n", + "}\n", + "TwoDArrayTraversal.main(null)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Practice\n", + "- Create a 2D Array Based and Traverse through it using a nested loop based on this problem" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1 2 3 4 \n", + "5 6 7 8 \n", + "9 10 11 12 \n" + ] + } + ], + "source": [ + "public class Practice {\n", + " public static void main(String[] args) {\n", + "\n", + " int[][] complexIntArray = {\n", + " {1, 2, 3, 4},\n", + " {5, 6, 7, 8},\n", + " {9, 10, 11, 12}\n", + " };\n", + "\n", + " // MISSING CODE HERE \n", + " for (int row = 0; row < complexIntArray.length; row++) { \n", + " for (int col = 0; col < complexIntArray[row].length; col++) { //nested for loop\n", + " int element = complexIntArray[row][col];\n", + " System.out.print(element + \" \");\n", + " }\n", + " System.out.println(); \n", + " }\n", + "\n", + " }\n", + " }\n", + " Practice.main(null);" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Using Enhanced For- Loops to Traverse an Array" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1 2 3 \n", + "4 5 6 \n", + "7 8 9 \n" + ] + } + ], + "source": [ + "public class EnhancedForLoop2DArray {\n", + " public static void main(String[] args) {\n", + " // Define and initialize a 2D array\n", + " int[][] twoDArray = {\n", + " {1, 2, 3},\n", + " {4, 5, 6},\n", + " {7, 8, 9}\n", + " };\n", + "\n", + " // Use nested enhanced for loops to traverse the 2D array\n", + " for (int[] row : twoDArray) {\n", + " for (int element : row) {\n", + " System.out.print(element + \" \");\n", + " }\n", + " System.out.println(); // Move to the next row\n", + " }\n", + " }\n", + "}\n", + "EnhancedForLoop2DArray.main(null)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Row Major Order Vs Column Major Order \n", + "\n", + "- PopCorn Hacks \n", + "\n", + "- **Whats the difference between row major order and column major order**\n", + "\n", + "ANS: row major means that we put our elemments across, and in column the order would be going down\n", + "\n", + "|1, 2, 3|\n", + "\n", + "|4, 5, 6|\n", + "\n", + "|7, 8, 9| (row major)\n", + "\n", + "|1, 4, 7|\n", + "\n", + "|2, 5, 8|\n", + "\n", + "|3, 6, 9| (column major)" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "A B C \n", + "D E F \n", + "G H I \n" + ] + } + ], + "source": [ + "public class PrintArray {\n", + " public static void printArray(String[][] grid) {\n", + " for (int row = 0; row < grid.length; row++) {\n", + " for (int col = 0; col < grid[0].length; col++) {\n", + " System.out.print(grid[row][col] + \" \");\n", + " }\n", + " System.out.println(); \n", + " }\n", + " }\n", + "\n", + " public static void main(String[] args) {\n", + " String[][] myGrid = {\n", + " {\"A\", \"B\", \"C\"},\n", + " {\"D\", \"E\", \"F\"},\n", + " {\"G\", \"H\", \"I\"}\n", + " };\n", + " printArray(myGrid);\n", + " }\n", + "}\n", + "PrintArray.main(null)" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "A D G \n", + "B E H \n", + "C F I \n" + ] + } + ], + "source": [ + "public class PrintArray {\n", + " public static void printArray(String[][] grid) {\n", + " for (int col = 0; col < grid[0].length; col++) // outer loop for collums switched\n", + " { for (int row = 0; row < grid.length; row++) //notice the outer is switched with the inner loop for rows\n", + " {\n", + " System.out.print(grid[row][col] + \" \");\n", + " }\n", + " System.out.println(); \n", + " }\n", + " }\n", + "\n", + " public static void main(String[] args) {\n", + " String[][] myGrid = {\n", + " {\"A\", \"B\", \"C\"},\n", + " {\"D\", \"E\", \"F\"},\n", + " {\"G\", \"H\", \"I\"}\n", + " };\n", + " printArray(myGrid);\n", + " }\n", + "}\n", + "PrintArray.main(null)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Practice\n", + "- Print My AP CS A Class Rocks Using a column major traversal." + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "My AP C S s Ap A p Cs Class s R o c k ! " + ] + } + ], + "source": [ + "public class PrintArray {\n", + " public static void printArray(String[][] grid) {\n", + " \n", + " for (int col = 0; col < grid[0].length; col++) {\n", + " for (int row = 0; row < grid.length; row++) {\n", + "\n", + " System.out.print(grid[row][col] + \" \");\n", + " }\n", + " }\n", + " }\n", + "\n", + " public static void main(String[] args) {\n", + " String[][] message = {\n", + " {\"My\", \"Ap\", \"Cs\", \"R\"},\n", + " {\"AP\", \"A\", \"Class\", \"o\"},\n", + " {\"C\", \"p\", \" \", \"c\"},\n", + " {\"S\", \" \", \" \", \"k\"},\n", + " {\"s\", \" \", \"s\", \"!\"},\n", + " };\n", + "\n", + " printArray(message);\n", + " }\n", + "}\n", + "\n", + "\n", + "PrintArray.main(null)\n", + "\n", + "// how are you supposed to print out exactly My AP CS A Class Rocks?" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Algorithms That use 2D Arrays Traversing " + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Krishiv is not in the array.\n" + ] + } + ], + "source": [ + "public class SearchExample {\n", + " public static boolean search(String[][] chart, String name) {\n", + " for (int r = 0; r < chart.length; r++) {\n", + " for (int c = 0; c < chart[0].length; c++) {\n", + " if (chart[r][c].equals(name)) {\n", + " return true;\n", + " }\n", + " }\n", + " }\n", + " return false; // Name not found in the array\n", + " }\n", + "\n", + " public static void main(String[] args) {\n", + " String[][] chart = {\n", + " {\"Alice\", \"Bob\", \"Charlie\"},\n", + " {\"David\", \"Eve\", \"Frank\"},\n", + " {\"Grace\", \"Hannah\", \"Isaac\"}\n", + " };\n", + "\n", + " String nameToSearch = \"Krishiv\";\n", + " boolean found = search(chart, nameToSearch);\n", + "\n", + " if (found) {\n", + " System.out.println(nameToSearch + \" is in the array.\");\n", + " } else {\n", + " System.out.println(nameToSearch + \" is not in the array.\");\n", + " }\n", + " }\n", + "}\n", + "SearchExample.main(null)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Hacks 8.2\n", + "- Complete the popcorn hacks \n", + "- Main Hack:\n", + " - Traverse Through a 2D Array Using Any of the following methods that we learned \n", + " - Traverse Through A 2D Array Using Specfically The Collumn Major Order. (Make Sure your using correct type of nested loop )\n", + " - Create your own situration of an Algorthm that needs to traverse a 2D array and then write the code for it \n", + " - Extra: Create an Extra Problem or Go further in depth about something we learned (MUST HAVE CODE FOR CREDIT!)" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Apple Banana Cherry \n", + "Date Fig Grape \n", + "Lemon Mango Orange \n" + ] + } + ], + "source": [ + "// MAIN HACK\n", + "\n", + "\n", + "// Traversing through 2D Array using a nested enhanced for loop\n", + "public class TwoDArray {\n", + " public static void main(String[] args) {\n", + " // Define and initialize a 2D array to store fruits\n", + " String[][] twoDArray = {\n", + " {\"Apple\", \"Banana\", \"Cherry\"},\n", + " {\"Date\", \"Fig\", \"Grape\"},\n", + " {\"Lemon\", \"Mango\", \"Orange\"}\n", + " };\n", + "\n", + " // Use nested enhanced for loops to traverse the 2D array and print the fruits\n", + " for (String[] row : twoDArray) {\n", + " for (String fruit : row) {\n", + " System.out.print(fruit + \" \");\n", + " }\n", + " System.out.println();\n", + " }\n", + " }\n", + "}\n", + "\n", + "TwoDArray.main(null);\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "A B C \n", + "D E F \n", + "G H I \n" + ] + } + ], + "source": [ + "// Column major order traversal\n", + "public class ColumnMajorTraversal {\n", + " public static void printArray(String[][] grid) {\n", + " // Outer loop for columns (major order)\n", + " for (int col = 0; col < grid[0].length; col++) {\n", + " // Inner loop for rows (minor order)\n", + " for (int row = 0; row < grid.length; row++) {\n", + " System.out.print(grid[row][col] + \" \");\n", + " }\n", + " System.out.println(); // Print a new line for each column\n", + " }\n", + " }\n", + "\n", + " public static void main(String[] args) {\n", + " String[][] myGrid = {\n", + " {\"A\", \"D\", \"G\"},\n", + " {\"B\", \"E\", \"H\"},\n", + " {\"C\", \"F\", \"I\"}\n", + " };\n", + " printArray(myGrid);\n", + " }\n", + "}\n", + "\n", + "ColumnMajorTraversal.main(null);\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Create your own situration of an Algorthm that needs to traverse a 2D array and then write the code for it \n", + "\n", + "Scenario: After you proved your ability to traverse through 1d arrays to the cartel, with your hitlist traversal,\n", + "the cartel gives you another question in your deadly technical interview. You must now traverse through a 2d array storing\n", + "different types of guns, and print out items from the 2d array that are chambered in 9mm rounds. You can use any method of traversal,\n", + "and success will allow you to survive and potentially work for the cartel." + ] + }, + { + "cell_type": "code", + "execution_count": 40, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "All Guns:\n", + "9mm: glock 12 gauge: riot shotgun 7.62x25mm: calibrated pistol \n", + "5.56x45mm: assault rifle 0000 0000 \n", + "9mm: uzi 10mm: submachine gun gernade launcher \n", + "\n", + "9mm Chambered Guns:\n", + "9mm: glock\n", + "9mm: uzi\n" + ] + } + ], + "source": [ + "public class cartelGuns {\n", + "\n", + " // This method prints the contents of a 2D array, row by row.\n", + " public static void printArray(String[][] grid) {\n", + " for (int row = 0; row < grid.length; row++) {\n", + " for (int col = 0; col < grid[0].length; col++) {\n", + " System.out.print(grid[row][col] + \" \");\n", + " }\n", + " System.out.println(); // Move to the next row after printing a row.\n", + " }\n", + " }\n", + "\n", + " // This method prints only the guns that contain \"9mm\" in their names from the 2D array.\n", + " public static void print9mmGuns(String[][] grid) {\n", + " for (int row = 0; row < grid.length; row++) {\n", + " for (int col = 0; col < grid[0].length; col++) {\n", + " if (grid[row][col].contains(\"9mm\")) {\n", + " System.out.println(grid[row][col]); // Print the gun name.\n", + " }\n", + " }\n", + " }\n", + " }\n", + "\n", + " public static void main(String[] args) {\n", + " // Define a 2D array containing gun names and their calibers.\n", + " String[][] guns = {\n", + " {\"9mm: glock\", \"12 gauge: riot shotgun\", \"7.62x25mm: calibrated pistol\"},\n", + " {\"5.56x45mm: assault rifle\", \"0000\", \"0000\"},\n", + " {\"9mm: uzi\", \"10mm: submachine gun\", \"gernade launcher\"}\n", + " };\n", + "\n", + " System.out.println(\"All Guns:\");\n", + " // Call the printArray method to print all guns in the array.\n", + " printArray(guns);\n", + "\n", + " System.out.println(\"\\n9mm Chambered Guns:\");\n", + " // Call the print9mmGuns method to print only the guns chambered in 9mm.\n", + " print9mmGuns(guns);\n", + " }\n", + "}\n", + "\n", + "\n", + "cartelGuns.main(null);\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Image Representation with 2D Arrays\n", + "\n", + "Digital images are essentially a collection of small, discrete elements called pixels. Pixels are organized in a 2D grid, where each pixel represents a single point of color or intensity. Each element (pixel) in the 2D array corresponds to one pixel in the image. In a color image, each pixel contains three color components: Red, Green, and Blue (RGB), while in grayscale images, each pixel has a single intensity value." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Traversing and Processing an Image\n", + "\n", + "Traversing an image's 2D array involves systematically visiting every pixel in the image grid. This process often uses nested loops, with the outer loop iterating over the rows and the inner loop iterating over the columns. By traversing the array, you gain access to each pixel's information, such as color values or intensity. This structured access is fundamental for various image processing tasks." + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Image downloaded and saved to: ../images/MORT1.png\n", + "Success! Image Dimensions (Width x Height): 1030 x 1372\n", + "Resolution: 39 pixels per inch (PPI)\n" + ] + } + ], + "source": [ + "import java.io.*;\n", + "import java.net.URL;\n", + "import javax.imageio.ImageIO; // ImageIO is a class in Java libraries which gives an easy way to use different image formats\n", + "import java.awt.image.BufferedImage; // BufferedImage is a class in Java libraries to help perform operations on images (read + write)\n", + "\n", + "public class ImageProcessing {\n", + " public static void main(String[] args) {\n", + " String imageUrl = \"https://user-images.githubusercontent.com/111609656/277895130-d15b0768-01d9-4522-8ef7-4f8bcf69c42e.png\";\n", + " String outputFolder = \"../images\";\n", + " String customFileName = \"MORT1.png\"; \n", + "\n", + " try {\n", + " String outputPath = outputFolder + File.separator + customFileName;\n", + "\n", + " URL url = new URL(imageUrl); // create URL object\n", + "\n", + " try (InputStream in = url.openStream(); // try-catch block where errors are handled\n", + " OutputStream out = new FileOutputStream(outputPath)) { // input stream reads data and output stream writes the data\n", + "\n", + " byte[] buffer = new byte[1024];\n", + " int bytesRead;\n", + "\n", + " while ((bytesRead = in.read(buffer)) != -1) {\n", + " out.write(buffer, 0, bytesRead);\n", + " } // reading the data from the URL and writes in 1024 byte chunks\n", + " }\n", + "\n", + " System.out.println(\"Image downloaded and saved to: \" + outputPath);\n", + "\n", + " File imageFile = new File(outputPath);\n", + " BufferedImage image = ImageIO.read(imageFile); \n", + " int width = image.getWidth();\n", + " int height = image.getHeight(); // get the image dimensions\n", + "\n", + " System.out.println(\"Success! Image Dimensions (Width x Height): \" + width + \" x \" + height);\n", + "\n", + " // Process the image using a 2D array\n", + " int[][] pixels = new int[width][height];\n", + "\n", + " for (int x = 0; x < width; x++) {\n", + " for (int y = 0; y < height; y++) {\n", + " int pixel = image.getRGB(x, y);\n", + " // Process the pixel here, e.g., apply filters or transformations\n", + " pixels[x][y] = pixel;\n", + " }\n", + " }\n", + "\n", + " // Calculate resolution in pixels per inch (PPI)\n", + " int ppi = (int) (image.getWidth() / (width * 0.0254));\n", + " System.out.println(\"Resolution: \" + ppi + \" pixels per inch (PPI)\");\n", + " } catch (IOException e) {\n", + " e.printStackTrace();\n", + " }\n", + " }\n", + "}\n", + "ImageProcessing.main(null)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Grayscale Conversion with Images\n", + "\n", + "Grayscale conversion is a fundamental image processing operation. When converting an image to grayscale, you effectively remove color information and retain only the pixel intensity. This is typically done by calculating the average intensity from the RGB components of each pixel. The result is a grayscale image where variations in pixel intensity represent the image's features and details. This operation can serve as a starting point for more complex image processing techniques." + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Success! Image converted to grayscale, downloaded, and saved to: ../images/MORT2_Grayscale.png\n" + ] + } + ], + "source": [ + "import java.awt.image.BufferedImage;\n", + "import java.awt.image.ColorConvertOp;\n", + "import java.io.*;\n", + "import java.net.URL;\n", + "import javax.imageio.ImageIO;\n", + "\n", + "public class ImageToGrayscaleWithArray {\n", + " public static void main(String[] args) {\n", + " String imageUrl = \"https://user-images.githubusercontent.com/111609656/277895164-5f93f1d8-88b5-4b08-b9a1-b54fb6d55d96.png\"; // Replace with the actual image URL\n", + " String outputFolder = \"../images\";\n", + " String customFileName = \"MORT2_Grayscale.png\"; // Change this to your desired file name for the grayscale image\n", + "\n", + " try {\n", + " // Define the output file path\n", + " String outputPath = outputFolder + File.separator + customFileName;\n", + "\n", + " // Create a URL object from the image URL\n", + " URL url = new URL(imageUrl);\n", + "\n", + " // Open a connection to the URL and get the input stream\n", + " try (InputStream in = url.openStream();\n", + " OutputStream out = new FileOutputStream(outputPath)) {\n", + "\n", + " // Read data from the URL and save it to the output file\n", + " byte[] buffer = new byte[1024];\n", + " int bytesRead;\n", + "\n", + " while ((bytesRead = in.read(buffer)) != -1) {\n", + " out.write(buffer, 0, bytesRead);\n", + " }\n", + " }\n", + "\n", + " // Read the downloaded image\n", + " BufferedImage originalImage = ImageIO.read(new File(outputPath));\n", + " int width = originalImage.getWidth();\n", + " int height = originalImage.getHeight();\n", + "\n", + " // Create a 2D array to store grayscale values\n", + " int[][] grayscaleArray = new int[width][height];\n", + "\n", + " // Convert the image to grayscale and populate the array\n", + " for (int x = 0; x < width; x++) {\n", + " for (int y = 0; y < height; y++) {\n", + " int pixel = originalImage.getRGB(x, y);\n", + " int red = (pixel >> 16) & 0xFF;\n", + " int green = (pixel >> 8) & 0xFF;\n", + " int blue = pixel & 0xFF;\n", + " int gray = (red + green + blue) / 3;\n", + " grayscaleArray[x][y] = gray;\n", + " }\n", + " }\n", + "\n", + " // Save the grayscale image\n", + " String grayscaleOutputPath = outputFolder + File.separator + customFileName;\n", + " BufferedImage grayscaleImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);\n", + "\n", + " for (int x = 0; x < width; x++) {\n", + " for (int y = 0; y < height; y++) {\n", + " int grayValue = grayscaleArray[x][y];\n", + " int grayPixel = (grayValue << 16) | (grayValue << 8) | grayValue;\n", + " grayscaleImage.setRGB(x, y, grayPixel);\n", + " }\n", + " }\n", + "\n", + " ImageIO.write(grayscaleImage, \"png\", new File(grayscaleOutputPath));\n", + "\n", + " System.out.println(\"Success! Image converted to grayscale, downloaded, and saved to: \" + grayscaleOutputPath);\n", + " } catch (IOException e) {\n", + " e.printStackTrace();\n", + " }\n", + " }\n", + "}\n", + "ImageToGrayscaleWithArray.main(null)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Image Conversion\n", + "\n", + "\n", + "
\n", + "\n", + "\n", + " Why do we Convert Images ? \n", + "\n", + "ANS: images have different purposes for each format, and it could help with writing image data, if we want to also change the image\n", + "along with the conversion.\n", + "\n", + "#### How Does Image Conversion Work:" + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "javax.imageio.IIOException: Can't read input file!\n", + "\tat java.desktop/javax.imageio.ImageIO.read(ImageIO.java:1308)\n", + "\tat REPL.$JShell$69$ImageConverter.main($JShell$69.java:37)\n", + "\tat REPL.$JShell$70.do_it$($JShell$70.java:21)\n", + "\tat java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)\n", + "\tat java.base/java.lang.reflect.Method.invoke(Method.java:578)\n", + "\tat io.github.spencerpark.ijava.execution.IJavaExecutionControl.lambda$execute$1(IJavaExecutionControl.java:95)\n", + "\tat java.base/java.util.concurrent.FutureTask.run(FutureTask.java:317)\n", + "\tat java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1144)\n", + "\tat java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:642)\n", + "\tat java.base/java.lang.Thread.run(Thread.java:1623)\n" + ] + } + ], + "source": [ + "import javax.imageio.ImageIO; // allows you to read and write images in various formats.\n", + "import java.io.File; // allows you to work with files and directories in your file system.\n", + "import java.io.IOException; // allows you to handle input and output exceptions that may occur during file operations.\n", + "import java.awt.image.BufferedImage; // allows you to work with images stored in memory, providing methods to manipulate image data.\n", + "\n", + "public class ImageConverter {\n", + "\n", + " public static void main(String[] args) {\n", + " try {\n", + " // Input and output file paths\n", + " String[] inputPaths = {\n", + " \"/Users/nikhilchakravarthula/vscode/KPNSLESSON/images/woodworker_mort.png\",\n", + " \"/Users/nikhilchakravarthula/vscode/KPNSLESSON/images/Mort2.png\"\n", + " };\n", + " String outputPath = \"/Users/nikhilchakravarthula/vscode/KPNSLESSON/imagesConvert\";\n", + "\n", + " // Loop through each image in the array\n", + " for (String inputPath : inputPaths) {\n", + " // Read the image\n", + " File inputFile = new File(inputPath);\n", + " BufferedImage img = ImageIO.read(inputFile); // Buffered image is a class in java for handling image data\n", + "\n", + " // Write the image\n", + " String outputFileName = \"converted_\" + new File(inputPath).getName().replace(\".png\", \".gif\");\n", + " String outputFilePath = outputPath + File.separator + outputFileName;\n", + " File outputFile = new File(outputFilePath);\n", + " ImageIO.write(img, \"gif\", outputFile);\n", + "\n", + " System.out.println(\"Image conversion successful for: \" + inputPath);\n", + " }\n", + " } catch (IOException e) {\n", + " e.printStackTrace();\n", + " }\n", + " }\n", + "}\n", + "ImageConverter.main(null)\n" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Image conversion successful!\n" + ] + } + ], + "source": [ + "import javax.imageio.ImageIO;\n", + "import java.io.File;\n", + "import java.io.IOException;\n", + "import java.awt.image.BufferedImage;\n", + "\n", + "public class ImageConverter {\n", + "\n", + " public static void main(String[] args) {\n", + " try {\n", + " // Input and output file paths\n", + " String inputPath = \"/mnt/c/Users/super/vscode/getsums/images/MORT1.png\";\n", + " String outputPath = \"/mnt/c/Users/super/vscode/getsums/images\";\n", + "\n", + " // Read the PNG image\n", + " BufferedImage img = ImageIO.read(new File(inputPath));\n", + "\n", + " // Convert image to RGB format \n", + " BufferedImage rgbImage = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_RGB);\n", + " rgbImage.createGraphics().drawImage(img, 0, 0, null);\n", + "\n", + " // Define the output file name and path\n", + " String outputFileName = inputPath.substring(inputPath.lastIndexOf(\"/\") + 1).replace(\".png\", \".jpeg\");\n", + " String outputFilePath = outputPath + File.separator + outputFileName;\n", + "\n", + " // Convert and save the image as JPEG\n", + " ImageIO.write(rgbImage, \"jpeg\", new File(outputFilePath));\n", + "\n", + " System.out.println(\"Image conversion successful!\");\n", + " } catch (IOException e) {\n", + " e.printStackTrace();\n", + " }\n", + " }\n", + "}\n", + "\n", + "ImageConverter.main(null);\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Scaling the Image" + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "javax.imageio.IIOException: Can't read input file!\n", + "\tat java.desktop/javax.imageio.ImageIO.read(ImageIO.java:1308)\n", + "\tat REPL.$JShell$73$ImageScaler.main($JShell$73.java:37)\n", + "\tat REPL.$JShell$74.do_it$($JShell$74.java:23)\n", + "\tat java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)\n", + "\tat java.base/java.lang.reflect.Method.invoke(Method.java:578)\n", + "\tat io.github.spencerpark.ijava.execution.IJavaExecutionControl.lambda$execute$1(IJavaExecutionControl.java:95)\n", + "\tat java.base/java.util.concurrent.FutureTask.run(FutureTask.java:317)\n", + "\tat java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1144)\n", + "\tat java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:642)\n", + "\tat java.base/java.lang.Thread.run(Thread.java:1623)\n" + ] + } + ], + "source": [ + "import javax.imageio.ImageIO;\n", + "import java.awt.*;\n", + "import java.awt.image.BufferedImage;\n", + "import java.io.File;\n", + "import java.io.IOException;\n", + "\n", + "public class ImageScaler {\n", + "\n", + " public static void main(String[] args) {\n", + " try {\n", + " // Input and output file paths\n", + " String inputPath = \"/Users/nikhilchakravarthula/vscode/KPNSLESSON/images/snow_mort.png\";\n", + " String outputPath = \"/Users/nikhilchakravarthula/vscode/KPNSLESSON/imagesConvert\";\n", + "\n", + " // Desired width and height of the scaled image\n", + " int scaledWidth = 100;\n", + " int scaledHeight = 100;\n", + "\n", + " // Read the image\n", + " File inputFile = new File(inputPath);\n", + " BufferedImage inputImage = ImageIO.read(inputFile);\n", + "\n", + " // Scale the image\n", + " BufferedImage scaledImage = scaleImage(inputImage, scaledWidth, scaledHeight);\n", + "\n", + " // Write the scaled image\n", + " String outputFileName = \"scaled_\" + new File(inputPath).getName();\n", + " String outputFilePath = outputPath + File.separator + outputFileName;\n", + " File outputFile = new File(outputFilePath);\n", + " ImageIO.write(scaledImage, \"png\", outputFile); \n", + "\n", + " System.out.println(\"Image scaling successful!\");\n", + " } catch (IOException e) {\n", + " e.printStackTrace();\n", + " }\n", + " }\n", + "\n", + " public static BufferedImage scaleImage(BufferedImage originalImage, int scaledWidth, int scaledHeight) {\n", + " // Create a new BufferedImage with the desired width and height\n", + " BufferedImage scaledImage = new BufferedImage(scaledWidth, scaledHeight, originalImage.getType());\n", + " \n", + " // g2d more into\n", + " // Create a Graphics2D object and set the rendering hints for scaling\n", + " Graphics2D g2d = scaledImage.createGraphics();\n", + " g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);\n", + " \n", + " // Draw the original image on the new BufferedImage with the desired width and height\n", + " g2d.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null);\n", + " \n", + " // Dispose of the Graphics2D object\n", + " g2d.dispose();\n", + " \n", + " return scaledImage;\n", + " }\n", + "}\n", + "\n", + "ImageScaler.main(null);\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Images Hack\n", + "\n", + "Hack: Create a functioning code in which you convert a PNG image to a JPEG image (make it funny).\n" + ] + }, + { + "cell_type": "code", + "execution_count": 49, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Image conversion successful!\n" + ] + } + ], + "source": [ + "import javax.imageio.ImageIO;\n", + "import java.io.File;\n", + "import java.io.IOException;\n", + "import java.awt.image.BufferedImage;\n", + "\n", + "public class ImageConverter {\n", + "\n", + " public static void main(String[] args) {\n", + " try {\n", + " // Input and output file paths\n", + " String inputPath = \"/mnt/c/Users/super/vscode/getsums/images/Pills.png\";\n", + " String outputPath = \"/mnt/c/Users/super/vscode/getsums/images/conversion\";\n", + "\n", + " // Read the PNG image\n", + " BufferedImage img = ImageIO.read(new File(inputPath));\n", + "\n", + " // Convert image to RGB format \n", + " BufferedImage rgbImage = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_RGB);\n", + " rgbImage.createGraphics().drawImage(img, 0, 0, null);\n", + "\n", + " // Define the output file name and path\n", + " String outputFileName = inputPath.substring(inputPath.lastIndexOf(\"/\") + 1).replace(\".png\", \".jpeg\");\n", + " String outputFilePath = outputPath + File.separator + outputFileName;\n", + "\n", + " // new part here will create objects for further image compression\n", + " ImageWriter writer = (ImageWriter) ImageIO.getImageWritersByFormatName(\"jpeg\").next();\n", + " ImageOutputStream ios = ImageIO.createImageOutputStream(new FileImageOutputStream(new File(outputFilePath)));\n", + " writer.setOutput(ios);\n", + "\n", + " // with object from earler we can set compression quality with this\n", + " ImageWriteParam param = writer.getDefaultWriteParam();\n", + " param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);\n", + " param.setCompressionQuality(0.01f); // Adjust the compression quality (0.1 = very low quality)\n", + " \n", + " // Convert and save the image as JPEG\n", + " ImageIO.write(rgbImage, \"jpeg\", new File(outputFilePath));\n", + "\n", + " System.out.println(\"Image conversion successful!\");\n", + " } catch (IOException e) {\n", + " e.printStackTrace();\n", + " }\n", + " }\n", + "}\n", + "\n", + "ImageConverter.main(null);\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# the png\n", + "\n", + "![image.png](images/Pills.png)\n", + "\n", + "# the jpeg\n", + "\n", + "![image.png](images/conversion/Pills.jpeg)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Grading for Hacks\n", + "\n", + "- 0.7 for Completing Lesson Hacks\n", + "- 0.2 for Popcorn Hacks + Practice\n", + "- 0.1 for Doing Extra Work" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Java", + "language": "java", + "name": "java" + }, + "language_info": { + "codemirror_mode": "java", + "file_extension": ".jshell", + "mimetype": "text/x-java-source", + "name": "java", + "pygments_lexer": "java", + "version": "20.0.2+9" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/_notebooks/2023-10-30-Unit9LessonEDNP.ipynb b/_notebooks/2023-10-30-Unit9LessonEDNP.ipynb new file mode 100755 index 0000000..d9004a2 --- /dev/null +++ b/_notebooks/2023-10-30-Unit9LessonEDNP.ipynb @@ -0,0 +1,1411 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# this is YAML front matter\n", + "layout: post\n", + "title: Unit 9 Lesson\n", + "description: A progressive journey through Java Inheritance\n", + "courses: { compsci: {week: 0} }\n", + "categories: [C4.0]\n", + "type: tangibles\n", + "---" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# 9.1 What is inheritance?\n", + "\n", + "- Inheritance is like a family, except the kids only have one parent instead of two\n", + "- For example:\n", + "\n", + "

\n", + " \n", + "

\n", + "The java code for it:\n", + "\n", + "```java\n", + "class Mom{\n", + " // CODE\n", + "}\n", + "class Son extends Mom{\n", + " // CODE\n", + "}\n", + "class Daughter extends Mom{\n", + " // CODE\n", + "}\n", + "```\n", + "In this example, the Son and Daughter inherits the Mom, meaning it inherit the components of the mother. This makes the \"Son\" and \"Daughter\" classes the __ subclass__ of the \"Mom\" class as they inherit the \"Mom\" class components and the \"Mom\" class the __superclass___. " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 9.2 Using the Super keyword for Constructors\n", + "- One keyword to know is the super keyword\n", + "- The super keyword allows the subclass to store key variables in the main class's _ instance variables___ (also known as the super class)\n", + "- Example below:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "VROOM! VROOM!\n", + "I am the Tesla\n", + "I was made in 2003\n", + "I move at 200 miles per hour\n", + "I hold at most 5 people\n" + ] + } + ], + "source": [ + "public class Vehicle { //This is the Superclass, it inherits the key variables for its subclasses\n", + " public String Name; //They don't have to be public, but I just put public word for fun\n", + " public String Sound;\n", + " public int creation;\n", + " public int Mph;\n", + " public Vehicle(String name, int dateMade, String sound, int mph){ //Similar to the constructor used in Javascript. It maintains values within this superclass\n", + " Name = name; \n", + " Sound = sound;\n", + " creation = dateMade;\n", + " Mph = mph;\n", + " }\n", + "}\n", + "\n", + "public class Car extends Vehicle {\n", + " public int capacity;\n", + " public Car(String name, int dateMade, String sound, int mph, int passangerCapacity){\n", + " super(name, dateMade,sound, mph); //Uses the superclass's constructor to store the key variables for the Car subclass\n", + " capacity = passangerCapacity;\n", + " }\n", + " public void Information(){ //Prints out the values the super class's constructors inherits\n", + " System.out.println(super.Sound + \" \" + this.Sound);\n", + " System.out.println(\"I am the \" + super.Name);\n", + " System.out.println(\"I was made in \" + super.creation);\n", + " System.out.println(\"I move at \" + super.Mph +\" miles per hour\");\n", + " System.out.println(\"I hold at most \" + capacity + \" people\");\n", + " }\n", + "}\n", + "\n", + "public class Test {\n", + " public static void main(String[] args){\n", + " Car Tesla = new Car(\"Tesla\", 2003, \"VROOM!\", 200, 5);\n", + " Tesla.Information();\n", + " }\n", + "}\n", + "\n", + "Test.main(null);" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Popcorn Hack: \n", + "Make it so that a new instance of Bob runs\n", + "message any of us on slack \"I\" for an extra 0.01 (max of 1/1) <----- HMMMMMMM" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Name: Bob\n", + "Age: 20\n", + "Salary: 100000.0\n", + "Position: Manager\n" + ] + } + ], + "source": [ + "public class Worker{\n", + " String Name;\n", + " int Age;\n", + " double Salary;\n", + " public Worker(String name, int age, double salary){\n", + " //Write codes that inherits its key properties\n", + " this.Name = name;\n", + " this.Age = age;\n", + " this.Salary = salary;\n", + " }\n", + "}\n", + "public class Bob extends Worker{\n", + " String Position;\n", + " public Bob(String name, int age, double salary,String position){\n", + " super(name, age, salary);\n", + " this.Position = position;\n", + " //Write code that maintains bob's information\n", + " }\n", + " public void Information(){\n", + " //Write code that writes out Bob's key information\n", + " System.out.println(\"Name: \" + super.Name);\n", + " System.out.println(\"Age: \" + super.Age);\n", + " System.out.println(\"Salary: \" + super.Salary);\n", + " System.out.println(\"Position: \" + this.Position);\n", + "\n", + " }\n", + "}\n", + "public class Test{\n", + " public static void main(String[] args){\n", + " //Make sure that it runs\n", + " \n", + " Bob bob = new Bob(\"Bob\", 20, 100000, \"Manager\");\n", + " bob.Information();\n", + " }\n", + "}\n", + "\n", + "Test.main(null);" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 9.3 Overriding Methods\n", + "\n", + "Method overriding is a concept in object-oriented programming (OOP) that allows a subclass to provide a specific implementation of a method that is already defined in its superclass. This enables a subclass to provide its own behavior for a method while maintaining a relationship with its superclass.\n", + "\n", + "In the context Java, here's how method overriding works:\n", + "\n", + "Inheritance: Method overriding is closely related to inheritance. You have a superclass (or base class) and a subclass (or derived class). The subclass inherits properties and behaviors from the superclass.\n", + "\n", + "Superclass Method: The superclass defines a method. This method can be overridden by the subclass.\n", + "\n", + "Subclass Overrides: In the subclass, you can provide a new implementation of the same method. This is done by using the same method name, return type, and parameter list.\n", + "\n", + "@Override Annotation (Java): In Java, it's common to use the @Override annotation to explicitly indicate that a method in the subclass is intended to override a method in the superclass. This helps catch errors during compilation if the method doesn't correctly match the superclass method signature.\n", + "\n", + "message any of us on slack \"Love\" for an extra 0.01 (max of 1/1) <--- HMMMMM\n", + "\n", + "### Why Override Methods:\n", + "\n", + "Method overriding is used for several reasons:\n", + "\n", + "Customization: It allows you to customize or extend the behavior of a superclass method in the subclass to meet the specific needs of the subclass.\n", + "\n", + "Polymorphism: Method overriding is a key component of polymorphism. It enables you to treat objects of the subclass as if they were objects of the superclass, promoting flexibility and extensibility.\n", + "\n", + "Consistency: Method overriding helps maintain a consistent interface for classes in an inheritance hierarchy. Code that uses the superclass doesn't need to be changed when a subclass overrides a method.\n", + "\n", + "Code Reusability: It promotes code reusability by allowing you to build on existing code in the superclass." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Animals make sounds\n", + "Dog barks\n", + "Cat meows\n" + ] + } + ], + "source": [ + "class Animal {\n", + " void makeSound() {\n", + " System.out.println(\"Animals make sounds\");\n", + " }\n", + "}\n", + "\n", + "class Dog extends Animal {\n", + " @Override\n", + " void makeSound() {\n", + " System.out.println(\"Dog barks\");\n", + " }\n", + "}\n", + "\n", + "class Cat extends Animal {\n", + " @Override\n", + " void makeSound() {\n", + " System.out.println(\"Cat meows\");\n", + " }\n", + "}\n", + "\n", + "public class Main {\n", + " public static void main(String[] args) {\n", + " Animal animal = new Animal();\n", + " Animal dog = new Dog();\n", + " Animal cat = new Cat();\n", + "\n", + " animal.makeSound(); // Output: Animals make sounds\n", + " dog.makeSound(); // Output: Dog barks\n", + " cat.makeSound(); // Output: Cat meows\n", + " }\n", + "}\n", + "\n", + "Main.main(null);" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## In this example:\n", + "\n", + "We have a base class Animal with a method makeSound().\n", + "\n", + "We create two subclasses, Dog and Cat, which inherit from the Animal class.\n", + "\n", + "Both Dog and Cat classes override the makeSound() method with their own implementations.\n", + "\n", + "In the main method, we create instances of the base class and its subclasses.\n", + "\n", + "We demonstrate polymorphism by calling the makeSound() method on objects of the base class and the subclasses. The method called depends on the actual type of the object, not the reference type.\n", + "\n", + "This showcases how method overriding allows you to provide specific implementations for methods in subclasses, promoting polymorphism and custom behavior for each subclass." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Another Example:\n", + "\n", + "\n", + "\n", + "\n", + "" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "Imagine you're building a program to manage sports team rosters. You can have a base class 'Athlete' representing common attributes and actions of all athletes. Then, create subclasses for specific sports like 'FootballPlayer', 'BasketballPlayer', and 'SoccerPlayer'." + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "John Mortensen is training.\n", + "Athlete Info:\n", + "Name: John Mortensen\n", + "Age: 19\n", + "Jersey Number: 4\n", + "Position: Teacher\n" + ] + } + ], + "source": [ + "// Base Class\n", + "class Athlete {\n", + " String name;\n", + " int age;\n", + " int jerseyNumber;\n", + " String position;\n", + "\n", + " public Athlete(String name, int age, int jerseyNumber, String position) {\n", + " this.name = name;\n", + " this.age = age;\n", + " this.jerseyNumber = jerseyNumber;\n", + " this.position = position;\n", + " }\n", + "\n", + " public void train() {\n", + " System.out.println(name + \" is training.\");\n", + " }\n", + "\n", + " public void displayInfo() {\n", + " System.out.println(\"Athlete Info:\");\n", + " System.out.println(\"Name: \" + name);\n", + " System.out.println(\"Age: \" + age);\n", + " System.out.println(\"Jersey Number: \" + jerseyNumber);\n", + " System.out.println(\"Position: \" + position);\n", + " }\n", + "}\n", + "\n", + "Athlete athlete = new Athlete(\"John Mortensen\", 19, 4, \"Teacher\");\n", + "athlete.train();\n", + "athlete.displayInfo();" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [], + "source": [ + "class FootballPlayer extends Athlete {\n", + " public FootballPlayer(String name, int age, int jerseyNumber, String position) {\n", + " super(name, age, jerseyNumber, position);\n", + " }\n", + "\n", + " @Override\n", + " public void train() {\n", + " System.out.println(name + \" is practicing football drills.\");\n", + " }\n", + "\n", + " @Override\n", + " public void displayInfo() {\n", + " super.displayInfo();\n", + " }\n", + "}\n", + "\n", + "class BasketballPlayer extends Athlete {\n", + " public BasketballPlayer(String name, int age, int jerseyNumber, String position) {\n", + " super(name, age, jerseyNumber, position);\n", + " }\n", + "\n", + " @Override\n", + " public void train() {\n", + " System.out.println(name + \" is shooting 3s on the court.\");\n", + " }\n", + "\n", + " @Override\n", + " public void displayInfo() {\n", + " super.displayInfo();\n", + " }\n", + "}\n", + "\n", + "class SoccerPlayer extends Athlete {\n", + " public SoccerPlayer(String name, int age, int jerseyNumber, String position) {\n", + " super(name, age, jerseyNumber, position);\n", + " }\n", + "\n", + " @Override\n", + " public void train() {\n", + " System.out.println(name + \" is practicing taking free kicks.\");\n", + " }\n", + "\n", + " @Override\n", + " public void displayInfo() {\n", + " super.displayInfo();\n", + " }\n", + "}\n" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Tyreek Hill is practicing football drills.\n", + "Athlete Info:\n", + "Name: Tyreek Hill\n", + "Age: 28\n", + "Jersey Number: 10\n", + "Position: Wide Receiver\n", + "\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Jimmy Butler is shooting 3s on the court.\n", + "Athlete Info:\n", + "Name: Jimmy Butler\n", + "Age: 32\n", + "Jersey Number: 22\n", + "Position: Small Forward\n", + "\n", + "Neymar Jr is practicing taking free kicks.\n", + "Athlete Info:\n", + "Name: Neymar Jr\n", + "Age: 31\n", + "Jersey Number: 10\n", + "Position: Left Winger\n", + "\n" + ] + } + ], + "source": [ + "FootballPlayer footballPlayer = new FootballPlayer(\"Tyreek Hill\", 28, 10, \"Wide Receiver\");\n", + "BasketballPlayer basketballPlayer = new BasketballPlayer(\"Jimmy Butler\", 32, 22, \"Small Forward\");\n", + "SoccerPlayer soccerPlayer = new SoccerPlayer(\"Neymar Jr\", 31, 10, \"Left Winger\");\n", + "\n", + "footballPlayer.train();\n", + "footballPlayer.displayInfo();\n", + "System.out.println();\n", + "\n", + "basketballPlayer.train();\n", + "basketballPlayer.displayInfo();\n", + "System.out.println();\n", + "\n", + "soccerPlayer.train();\n", + "soccerPlayer.displayInfo();\n", + "System.out.println();" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Explanation:\n", + "\n", + "In this Java code, you have a basic \"Athlete\" class with information and actions that all athletes share. Then, there are specific types of athletes (football, basketball, and soccer players) that inherit these common traits but also have their unique behaviors, like training routines. Method overriding lets them have their own way of training while keeping the shared information, making the code easy to manage and reuse for different types of athletes.\n", + "\n", + "### Popcorn Hack:\n", + "\n", + "Why is it helpful to have a common base class like 'Athlete' for all these different types of athletes? How does it make the code more organized?\n", + "\n", + "ANS: with a base class Athelete, we are able to have a common set of methods that can be used by all athletes. This makes it easier to manage and reuse the code. Then, \n", + "we can use override to change specific details of different Athletes we make. Lastly, it gives us multiple subclasses for different types of athletes and in this case, something they might do." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 9.4 Using Super keyword for Methods\n", + "- Why only use super for constructors when you can use them for methods too?\n", + "- With the super key word, not only can you store variables, but also store methods" + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "I am a Dog\n", + "Woof!\n", + "I am a Cow\n", + "MOOOO!\n" + ] + } + ], + "source": [ + "class Animal{\n", + " public void Introduction(String name){\n", + " System.out.println(\"I am a \" + name);\n", + " }\n", + "}\n", + "class Dog extends Animal{ \n", + " public void Woof(){\n", + " super.Introduction(\"Dog\");//Inherits the introduction method in the Animal Class, then introduces itself as a dog\n", + " System.out.println(\"Woof!\"); //Does its own thing\n", + " }\n", + "}\n", + "class Cow extends Animal{\n", + " public void Moo(){\n", + " super.Introduction(\"Cow\");//Inherits the introduction method in the Animal Class, then introduces itself as a cow\n", + " System.out.println(\"MOOOO!\");//Does its own thing\n", + " }\n", + "}\n", + "class Test{\n", + " public static void main(String[] args){\n", + " Dog dog = new Dog();\n", + " Cow cow = new Cow();\n", + " dog.Woof();\n", + " cow.Moo();\n", + " }\n", + "}\n", + "Test.main(null);" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 9.4 Hack\n", + "Finish up the code with this criteria: All subclasses must say their origin, the origin can be from SchoolSupply class, and it must run through main." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "This is a School Supply.\n", + "Pencils: 100\n", + "Erasers: 50\n", + "This is a School Supply.\n", + "Pencils: 100\n", + "Erasers: 50\n", + "This is a Pencil.\n", + "Origin: SchoolSupply\n", + "This is an Eraser.\n", + "Origin: SchoolSupply\n" + ] + } + ], + "source": [ + "class SchoolSupply {\n", + " // Declare instance variables for Pencil and Eraser\n", + " int Pencil = 100;\n", + " int Eraser = 50;\n", + "\n", + " public void BasicInfo() {\n", + " // Output the basic information\n", + " System.out.println(\"This is a School Supply.\");\n", + " System.out.println(\"Pencils: \" + Pencil);\n", + " System.out.println(\"Erasers: \" + Eraser);\n", + " }\n", + "}\n", + "\n", + "class Pencil extends SchoolSupply {\n", + " public void Information() {\n", + " // Output Pencil-specific information\n", + " System.out.println(\"This is a Pencil.\");\n", + " System.out.println(\"Origin: SchoolSupply\");\n", + " }\n", + "}\n", + "\n", + "class Eraser extends SchoolSupply {\n", + " public void Information() {\n", + " // Output Eraser-specific information\n", + " System.out.println(\"This is an Eraser.\");\n", + " System.out.println(\"Origin: SchoolSupply\");\n", + " }\n", + "}\n", + "\n", + "public class Test {\n", + " public static void main(String[] args) {\n", + " Pencil pencil = new Pencil();\n", + " Eraser eraser = new Eraser();\n", + "\n", + " // Output basic information for Pencil and Eraser\n", + " pencil.BasicInfo();\n", + " eraser.BasicInfo();\n", + "\n", + " // Output specific information for Pencil and Eraser\n", + " pencil.Information();\n", + " eraser.Information();\n", + " }\n", + "}\n", + "\n", + "Test.main(null);" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 9.5 Creating References Using Inheritance Hierarchies\n", + "Inheritance can be thought as an upside down tree with the __roots __ on the top and the _ branches___ on the bottom. The __ roots __ is the superclass while the __ branches__ are the subclasses of this superclass. A visual representation of this tree is called a type diagram or hierarchy tree.\n", + "\n", + "A sample structure would be like:\n", + "```\n", + "public class A\n", + "public class B extends A\n", + "public class C extends B\n", + "public class D extends C\n", + "public class E extends I\n", + "public class F extends I\n", + "public class G extends H\n", + "public class H extends A\n", + "public class I extends H\n", + "```\n", + "## Popcorn Hack\n", + "- Draw a hierarchy tree for the above structure and add the picture here\n", + "\n", + "This structure works as C not only inherits properties from B, but it also inherits properties from A. B is like C's parent and A is like C's grandparent. Think about it like real life, all families inherit something from their ancestors.\n", + "\n", + "In addition, you could also create objects like this:\n", + "```\n", + "C c = new C();\n", + "B c = new C();\n", + "A c = new C();\n", + "```\n", + "\n", + "![image.png](images/trash.png)\n" + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "metadata": {}, + "outputs": [], + "source": [ + "// This is the above example in code form\n", + "\n", + "class A {}\n", + "class B extends A {}\n", + "class C extends B {}\n", + "\n", + "public class Main {\n", + " public static void main(String[] args) {\n", + " C c = new C(); // variable c is of type C\n", + " B b = new C(); // variable b is of type B, but refers to an instance of C\n", + " A a = new C(); // variable a is of type A, but refers to an instance of C\n", + " }\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 9.6 Polymorphism\n", + "\n", + "A ______reference___ variable is polymorphic when it can refer to objects from different classes at different points in time\n", + "- A reference variable can store a reference to its declared class or any subclass of it's declared class\n", + "\n", + "A method or operator are considered polymorphic when they are ____overridden______ in at least one subclass\n", + "\n", + "Polymorphism is the act of executing an overridden non-__static___ method from the correct class at runtime based on the actual object type\n", + "\n", + "Polymorphism allows __code __ for a method call to be executed based on the class of the object referenced instead of the declared class\n", + "\n", + "## Example 1\n", + "Java polymorphism is mainly split into 2 types\n", + "\n", + "Runtime_____\n", + "- Process in which a function call to the overridden method is resolved at Runtime. This type of polymorphism is achieved by Method Overriding.\n", + "\n", + "Compile polymorphism_____\n", + "- Also known as static polymorphism. This type is achieved by function overloading or operater overloading\n", + "- Note: But java doesnt support Operator Overloading\n", + "- When there are multiple functions with the same name but different parameters then these functions are said to be overloaded. Functions can be overloaded by changes in the number of arguments or/and a change in the type of arguments. \n", + "\n", + "Here is an example of compile polymorphism" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "8\n", + "42\n" + ] + } + ], + "source": [ + "// Class 1\n", + "// Helper class\n", + "class Helper {\n", + " \n", + " // Method 1\n", + " // Multiplication of 2 numbers\n", + " static int Multiply(int a, int b)\n", + " {\n", + " \n", + " // Return product\n", + " return a * b;\n", + " }\n", + " \n", + " // Method 2\n", + " // // Multiplication of 3 numbers\n", + " static int Multiply(int a, int b, int c)\n", + " {\n", + " \n", + " // Return product\n", + " return a * b * c;\n", + " }\n", + "}\n", + " \n", + "// Class 2\n", + "// Main class\n", + "class GFG {\n", + " \n", + " // Main driver method\n", + " public static void main(String[] args)\n", + " {\n", + " \n", + " // Calling method by passing\n", + " // input as in arguments\n", + " System.out.println(Helper.Multiply(2, 4));\n", + " System.out.println(Helper.Multiply(2, 7, 3));\n", + " }\n", + "}\n", + "GFG.main(null)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Example 2 & Popcorn Hack\n", + "Before executing cell, look at the example below. Think about which methods compiles? Which methods execute?\n", + "\n", + "message any of us on slack \"Inheritance\" for an extra 0.01 (max of 1/1) <---hmmmmm\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Musician\n" + ] + }, + { + "ename": "CompilationException", + "evalue": "", + "output_type": "error", + "traceback": [ + "\u001b[1m\u001b[30m| \u001b[1m\u001b[30mEntertainer soham = new Comedian(\u001b[0m\u001b[1m\u001b[30m\u001b[41m\u001b[0m\u001b[1m\u001b[30m“satire”, oneliners); \u001b[0m", + "\u001b[1m\u001b[31millegal character: '\\u201c'\u001b[0m", + "" + ] + } + ], + "source": [ + "import java.util.Random;\n", + "\n", + "public class Entertainer{\n", + " private String talent;\n", + " public Entertainer (String t){\n", + " talent = t;\n", + " }\n", + " public String getTalent(){\n", + " return talent;\n", + " }\n", + "}\n", + "\n", + "public class Comedian extends Entertainer{\n", + " private ArrayList jokes;\n", + " public Comedian(String t, ArrayList jks){\n", + " super(t);\n", + " jokes = jks;\n", + " }\n", + " public String getTalent(){\n", + " return \"Comedy style: \" + super.getTalent();\n", + " }\n", + " public String tellJoke(){\n", + " return jokes.get((int)(Math.random()*jokes.size()));\n", + " }\n", + "}\n", + "\n", + "// Which one of these will run? Which one of these will not? Comment out the line that isn't working and explain why\n", + "Entertainer kevin = new Entertainer(\"Musician\");\n", + "\n", + "System.out.println(kevin.getTalent());\n", + "//System.out.println(kevin.tellJoke()); This will not run because tellJoke is not a method of Entertainer\n", + "\n", + "\n", + "ArrayList oneLiners = new ArrayList(); \n", + "oneLiners.add(\"test\"); //bruh\n", + "\n", + "//Add code which adds jokes to oneLiners like... Why did the programmer quit his job?.. Why did the developer go broke?..\n", + "Entertainer soham = new Comedian(“satire”, oneliners); \n", + "System.out.println(soham.getTalent()); \n", + "System.out.println(((Comedian)soham).tellJoke());" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Example 3\n", + "Here is an example of runtime polymorphism" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "subclass1\n", + "subclass2\n" + ] + } + ], + "source": [ + "// Class 1\n", + "// Helper class\n", + "class Parent {\n", + " \n", + " // Method of parent class\n", + " void Print()\n", + " {\n", + " \n", + " // Print statement\n", + " System.out.println(\"parent class\");\n", + " }\n", + "}\n", + "// Class 2\n", + "// Helper class\n", + "class subclass1 extends Parent {\n", + " \n", + " // Method\n", + " void Print() { System.out.println(\"subclass1\"); }\n", + "}\n", + "// Class 3\n", + "// Helper class\n", + "class subclass2 extends Parent {\n", + " \n", + " // Method\n", + " void Print()\n", + " {\n", + " \n", + " // Print statement\n", + " System.out.println(\"subclass2\");\n", + " }\n", + "}\n", + "// Class 4\n", + "// Main class\n", + "class GFG {\n", + " \n", + " // Main driver method\n", + " public static void main(String[] args)\n", + " {\n", + " \n", + " // Creating object of class 1\n", + " Parent a;\n", + " \n", + " // Now we will be calling print methods\n", + " // inside main() method\n", + " \n", + " a = new subclass1();\n", + " a.Print();\n", + " \n", + " a = new subclass2();\n", + " a.Print();\n", + " }\n", + "}\n", + "GFG.main(null)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 9.7 Object Superclass\n", + "Now that we have learned about inheritance, what even allows our classes and objects that we have created to work the way they do? Where do the general characteristics of all objects come from? The answer lies in the __object __ class.\n", + "\n", + "The _ object___ class is the superclass of all other classes as well as arrays and other data types. The Object class is part of the java.lang package.\n", + "\n", + "When we call a constructor to a \"top-level class\" that the coder hasn't declared a superclass for, the Object constructor is implicitly called. In other words, the Object constructor is implicitly called when we call a constructor in a class that doesn't explicitly extend another class. This will give the object some properties and methods that are common to all classes." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Example 1" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "true\n", + "false\n" + ] + } + ], + "source": [ + "public class Person {\n", + " String name;\n", + " int age;\n", + "\n", + " public Person(String name, int age) {\n", + " this.name = name;\n", + " this.age = age;\n", + " }\n", + "\n", + " public static void main(String[] args) {\n", + " Person person1 = new Person(\"Jane Doe\", 30);\n", + " Person person2 = new Person(\"Jane Doe\", 30);\n", + "\n", + " System.out.println(person1.equals(person1)); // Since person1 and person1 are the same object, the equals() method will return true\n", + " System.out.println(person1.equals(person2)); // Since person1 and person2 are different objects, the equals() method will return false even though they have the same contents\n", + " }\n", + "}\n", + "\n", + "Person.main(null);\n", + "\n", + "// The equals() method is inherited from the Object class\n", + "// By default, the equals() method in the Object class checks for object identity, which means it compares memory addresses to see if two references point to the exact same object\n", + "// In the code, person1 and person2 are distinct objects, so they have different memory addresses\n", + "// When we call person1.equals(person2), it checks if the memory addresses are the same (which they are not), so it returns false." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Example 2" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "HashCode: 2094718255\n" + ] + } + ], + "source": [ + "public class Book {\n", + " String title;\n", + " String author;\n", + "\n", + " public Book(String title, String author) {\n", + " this.title = title;\n", + " this.author = author;\n", + " }\n", + "\n", + " public static void main(String[] args) {\n", + " Book book = new Book(\"The Catcher in the Rye\", \"J.D. Salinger\");\n", + " int hashCode = book.hashCode();\n", + " System.out.println(\"HashCode: \" + hashCode); // The output will be a unique integer value representing the object's hash code. The integer value will be different every time you run it\n", + " }\n", + "}\n", + "\n", + "Book.main(null);\n", + "\n", + "// The hashCode() method in the Object class returns a unique integer value for each object\n", + "// This value is typically based on the object's memory address.\n", + "// In the code, when we call book.hashCode(), it generates a unique integer value representing the book object\n", + "// This value can be useful for various purposes, such as organizing objects in collections like HashMaps or HashSet where it helps in efficient retrieval of objects." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Hacks\n", + "- Popcorn Hacks (0.2): Participate in the discussion and fill in all of the blanks. \n", + "- MC Questions (0.1): Answer the 10 MC questions below with short explanations\n", + "- FRQ Hacks (0.5): Make a complex FRQ that involves everything we taught. Be sure to have a sample solution along with scoring guidlines and how the solution is scored.\n", + "- Challenge (0.1): Make an example that uses everything we taught and it must run through main and uses input and output. Points will be awarded for complexity and creativity\n", + "\n", + "### MC Questions\n", + "\"Question\n", + "\n", + "the answer is the first one, since we are able to create a car with the vehicle reference as we print as Vehicle vehicle\n", + "\n", + "\n", + "\"Question\n", + "\n", + "C b = new B shouldn't work because C is a superclass of B and thus shouldn't be able to create a new B object as a result, it would work if B was a superclass of C.\n", + "\n", + "\"Question\n", + "\n", + "3: The objects of class G should be able to be treated as objects for H and J because G is extended by H which is extended by J, and its thus in the hierarchy at the end of H and J, allowing it to be an object for H and J.\n", + "\n", + "\"Question\n", + "\n", + "4: C-D-B is the heirarchy, meaning B must be a subclass of C if we follow the heirarchy.\n", + "\n", + "\"Question\n", + "\n", + "5: it should be the compile error, as Bird is the parent of penguin, so we cannot just make a bird object as a result.\n", + "\n", + "\"Question\n", + "\n", + "6: the 2nd one should be right as since J is a parent of K and L we can thus create objects from the 2 children.\n", + "\n", + "\"Question\n", + "\n", + "7: Inheiritance because subclasses are only created by inheiriting from parents.\n", + "\n", + "\"Question\n", + "\n", + "8: G-B-C-H, means that G is an indirect superclass of H.\n", + "\n", + "\"Question\n", + "\n", + "9: the roots would be superclasses and the branches would be subclasses, as branches extend off of roots, and subclasses extend off of parents or the superclasses.\n", + "\n", + "\"Question\n", + "\n", + "10: the object should be successfully assigned as subclasses inheirit the superclasses reference variables. \n", + "\n", + "### please let me know in grading if I got anything wrong and what I should know, cause theres not answer key. also you can use this as an opportunity to make it look like you put a lot of effort into grading, which you did if you do this.\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "- FRQ Hacks (0.5): Make a complex FRQ that involves everything we taught. Be sure to have a sample solution along with scoring guidlines and how the solution is scored.\n", + "\n", + "FRQ: at the local bakery, you are to build a class that can store information about baked goods.\n", + "\n", + "A: add a donut subclass of baked goods that also contains a String variable for flavor, then print out a donut with name: \"Cake Donut\", calories: 250, season: \"Fall\" and flavor: \"Vanilla\". however, do not print out the flavor, only define it." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "public class BakedGoods {\n", + " //code goes here\n", + "\n", + " public static class Donut extends BakedGoods {\n", + " //create the subclass here\n", + " public void InformationBakery() {\n", + " //code here for information \n", + " }\n", + " }\n", + "\n", + " public static void main(String[] args) {\n", + " Donut vanilla = new Donut(\"Cake Donut\", 250, \"Fall\", \"Vanilla\");\n", + " vanilla.InformationBakery();\n", + " }\n", + "}\n", + "\n", + "BakedGoods.main(null);" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Sample answer" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Name: Cake Donut\n", + "Calories: 250\n", + "Season: Fall\n" + ] + } + ], + "source": [ + "public class BakedGoods {\n", + " String Name;\n", + " int Calories;\n", + " String Season;\n", + "\n", + " public BakedGoods(String name, int calories, String season) {\n", + " this.Name = name;\n", + " this.Calories = calories;\n", + " this.Season = season;\n", + " }\n", + "\n", + " public static class Donut extends BakedGoods {\n", + " String Flavor;\n", + "\n", + " public Donut(String name, int calories, String season, String flavor) {\n", + " super(name, calories, season);\n", + " this.Flavor = flavor;\n", + " }\n", + "\n", + " public void InformationBakery() {\n", + " System.out.println(\"Name: \" + super.Name);\n", + " System.out.println(\"Calories: \" + super.Calories);\n", + " System.out.println(\"Season: \" + super.Season);\n", + " }\n", + " }\n", + "\n", + " public static void main(String[] args) {\n", + " Donut vanilla = new Donut(\"Cake Donut\", 250, \"Fall\", \"Vanilla\");\n", + " vanilla.InformationBakery();\n", + " }\n", + "}\n", + "\n", + "BakedGoods.main(null);" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "PART B:\n", + "\n", + "use method overriding to print out the flavor of the donut, using a new method." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "public static class Donut extends BakedGoods {\n", + " //create the subclass here\n", + " public void InformationBakery() {\n", + " //code here for information \n", + " }\n", + "}\n", + "\n", + "public static class Donut extends BakedGoods {\n", + "//use previous donut subclass\n", + "\n", + " @Override\n", + " //create override method here\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Sample answer" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Flavor: Vanilla\n", + "Name: Cake Donut\n", + "Calories: 250\n", + "Season: Fall\n" + ] + } + ], + "source": [ + "public class BakedGoods {\n", + " String Name;\n", + " int Calories;\n", + " String Season;\n", + "\n", + " public BakedGoods(String name, int calories, String season) {\n", + " this.Name = name;\n", + " this.Calories = calories;\n", + " this.Season = season;\n", + " }\n", + "\n", + " public void displayInformation() {\n", + " System.out.println(\"Name: \" + this.Name);\n", + " System.out.println(\"Calories: \" + this.Calories);\n", + " System.out.println(\"Season: \" + this.Season);\n", + " }\n", + "\n", + " public static class Donut extends BakedGoods {\n", + " String Flavor;\n", + "\n", + " public Donut(String name, int calories, String season, String flavor) {\n", + " super(name, calories, season);\n", + " this.Flavor = flavor;\n", + " }\n", + "\n", + " @Override\n", + " public void displayInformation() {\n", + " System.out.println(\"Flavor: \" + this.Flavor);\n", + " super.displayInformation(); // Call the base class method\n", + " }\n", + " }\n", + "\n", + " public static void main(String[] args) {\n", + " BakedGoods bakedGood = new Donut(\"Cake Donut\", 250, \"Fall\", \"Vanilla\");\n", + " bakedGood.displayInformation(); // Demonstrating polymorphism\n", + " }\n", + "}\n", + "\n", + "BakedGoods.main(null);" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# scoring\n", + "\n", + "the frq made is out of 5 points\n", + "\n", + "1 point for correctly initiallizing the required attributes for the bakedGoods class\n", + "\n", + "1 point for correctly extending the bakedGoods class and defining the new donut subclass with all of the previous attributes defined in bakedGoods class\n", + "\n", + "1 point for defining the flavor attribute in the new donut subclass\n", + "\n", + "1 point for displaying the required information about a donut object \n", + "\n", + "1 point for displaying flavor correctly using method overriding in part 2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "- Challenge (0.1): Make an example that uses everything we taught and it must run through main and uses input and output. Points will be awarded for complexity and creativity\n", + "\n", + "\n", + "# expansion to frq answer \n", + "\n", + "I've added onto my frq code from earlier and added a new cake subclass, with its own different attribute, this being frosting. I've also added user input allowing us to\n", + "create our donut or cake with user input, then printing out details about the baked good, with cake having the additional frosting attribute, and donut still having the frosting \n", + "attribute to be printed out." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Enter the name of the baked good: Enter the calories of the baked good: Enter the season of the baked good: Enter the frosting/flavor of the baked good: Is it a cake? (yes or no): Flavor: pumpkin spice\n", + "Name: pumpkin donut\n", + "Calories: 300\n", + "Season: fall\n" + ] + } + ], + "source": [ + "public class BakedGoods {\n", + " String Name;\n", + " int Calories;\n", + " String Season;\n", + "\n", + " public BakedGoods(String name, int calories, String season) {\n", + " this.Name = name;\n", + " this.Calories = calories;\n", + " this.Season = season;\n", + " }\n", + "\n", + " public void displayInformation() {\n", + " System.out.println(\"Name: \" + this.Name);\n", + " System.out.println(\"Calories: \" + this.Calories);\n", + " System.out.println(\"Season: \" + this.Season);\n", + " }\n", + "\n", + " public static class Donut extends BakedGoods {\n", + " String Flavor;\n", + "\n", + " public Donut(String name, int calories, String season, String flavor) {\n", + " super(name, calories, season);\n", + " this.Flavor = flavor;\n", + " }\n", + "\n", + " @Override\n", + " public void displayInformation() {\n", + " System.out.println(\"Flavor: \" + this.Flavor);\n", + " super.displayInformation();\n", + " }\n", + " }\n", + "\n", + " public static class Cake extends BakedGoods {\n", + " String Frosting;\n", + "\n", + " public Cake(String name, int calories, String season, String frosting) {\n", + " super(name, calories, season);\n", + " this.Frosting = frosting;\n", + " }\n", + "\n", + " @Override\n", + " public void displayInformation() {\n", + " System.out.println(\"Frosting: \" + this.Frosting);\n", + " super.displayInformation();\n", + " }\n", + " }\n", + "\n", + " public static void main(String[] args) {\n", + " Scanner scanner = new Scanner(System.in);\n", + "\n", + " System.out.print(\"Enter the name of the baked good: \");\n", + " String name = scanner.nextLine();\n", + "\n", + " System.out.print(\"Enter the calories of the baked good: \");\n", + " int calories = scanner.nextInt();\n", + " scanner.nextLine();\n", + "\n", + " System.out.print(\"Enter the season of the baked good: \");\n", + " String season = scanner.nextLine();\n", + "\n", + " System.out.print(\"Enter the frosting/flavor of the baked good: \");\n", + " String frostingOrFlavor = scanner.nextLine();\n", + "\n", + " System.out.print(\"Is it a cake? (yes or no): \");\n", + " String isCake = scanner.nextLine();\n", + "\n", + " scanner.close();\n", + "\n", + " BakedGoods bakedGood;\n", + " if (isCake.equalsIgnoreCase(\"yes\")) {\n", + " bakedGood = new Cake(name, calories, season, frostingOrFlavor);\n", + " } else {\n", + " bakedGood = new Donut(name, calories, season, frostingOrFlavor);\n", + " }\n", + "\n", + " bakedGood.displayInformation(); // Demonstrating polymorphism\n", + " }\n", + "}\n", + "\n", + "BakedGoods.main(null);" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Java", + "language": "java", + "name": "java" + }, + "language_info": { + "codemirror_mode": "java", + "file_extension": ".jshell", + "mimetype": "text/x-java-source", + "name": "java", + "pygments_lexer": "java", + "version": "20.0.2+9" + }, + "orig_nbformat": 4 + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/_posts/2023-08-15-Tools_Plans_Sample.md b/_posts/2023-08-15-Tools_Plans_Sample.md deleted file mode 100644 index 6d60992..0000000 --- a/_posts/2023-08-15-Tools_Plans_Sample.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -toc: true -comments: false -layout: post -title: Daily Plan Sample -description: Example Blog!!! This shows planning and notes from hacks. -type: plans -courses: { compsci: {week: 0} } ---- - -### PBL Unit 1 / Week 0 -Learning outcome. Installing Tools and showing usage of VSCode. -- Wednesday - Pick pair share partner, Pick crossover pair, Establish team of four. Spend some time talking and getting to know each other, particularly with Computer Science experience and goals. You should be matched with someone that has similar experience. -- Thursday - Setup Tools on laptop and/or Cloud Computer. -- Friday - Review and test as a Pair. Spend 25 minutes at one keyboard then switch for next 25 minutes. - diff --git a/_posts/2023-08-15-Tools_Sprint.md b/_posts/2023-08-15-Tools_Sprint.md deleted file mode 100644 index eb5a0cb..0000000 --- a/_posts/2023-08-15-Tools_Sprint.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -toc: true -comments: true -layout: post -title: Tools Setup -description: Become one with your tools. They could be more important than code, code, coding. -type: plans -courses: { csse: {week: 0}, csp: {week: 0, categories: [4.A]}, csa: {week: 0} } -categories: [C1.4] ---- - -### PBL Unit 1 / Week 0 -Learning outcome. Installing Tools and showing usage of VSCode. -- Wednesday - Pick pair share partner, Pick crossover pair, Establish team of four. Spend some time talking and getting to know each other, particularly with Computer Science experience and goals. You should be matched with someone that has similar experience. -- Thursday - Setup Tools on laptop and/or Cloud Computer. -- Friday - Review and test as a Pair. Spend 25 minutes at one keyboard then switch for next 25 minutes. - -### Hack Prepartation -> Look for 'Hacks' to know what to do next. Try to be done and learn your machine before Monday EOD. -- A laptop, that you bring to class every day with ability to operate Development Tools on it or within the Cloud. -- GitHub Account, VSCode will be used to push/pull changes. GitHub is where we store and share code in the cloud, think of Google Docs but for Code. -- GitHub Pages will be used to host your personal blog: containing notes, answering hacks, and showing tangibles. Building pages will teach Markdown, HTML, CSS, JavaScript and more. -- Jupyter Notebooks will be used in conjunction with GitHub Pages to build running Code in your blog. -- Slack Account, install the App on Laptop and/or phone, get used to reading announcements. Slack is the tool that we will use for messaging, we have been averaging 1000s of essages each year. -- VSCode is the code editor we will be using in this class. VSCode is more than and editor, this type of tool is often called an Interactive Development Environment (IDE). -- Run make commands to build and test blog locally, before pushing changes to GitHub pages. diff --git a/_posts/2023-08-16-Tools_Equipment.md b/_posts/2023-08-16-Tools_Equipment.md deleted file mode 100644 index b2c1b26..0000000 --- a/_posts/2023-08-16-Tools_Equipment.md +++ /dev/null @@ -1,93 +0,0 @@ ---- -toc: true -comments: true -layout: post -title: VSCode, Python, Jupyter, ... -description: Tools and equipment setup for tools used throughout this class. -courses: { csse: {week: 0}, csp: {week: 0}, csa: {week: 0} } -type: hacks ---- - -## Hacks -> Complete the procedure below accurately. These are absolutely required and must be 100% accurate for your success. - -### GitHub Account -- Follow instruction [https://docs.github.com/en/get-started/signing-up-for-github/signing-up-for-a-new-github-account](https://docs.github.com/en/get-started/signing-up-for-github/signing-up-for-a-new-github-account) Use your own personal/permanent email... NOT SCHOOL!!! GitHub account belongs to you. - -### MacOS 1st Time Developer -> VSCode install -- Install [VSCode](https://code.visualstudio.com/docs/setup/mac) - -> Anaconda install -- Download for MacOS: [Anaconda](https://www.anaconda.com/products/distribution) -- Run Install: Answer yes to questions - -> Homebrew install -- Copy and Paste to Install from Terminal [Homebrew](https://brew.sh) - - Copy ```bash ... curl ...``` command using copy box on website - - Launch ```terminal``` from search bar - - Paste ```bash ... curl ...``` command into Terminal ... - - Make sure command starts, this should provide feedback/output in terminal and could take a long time, like 10-min, there could be a prompt in the middle, at about 5-minutes. Follow any on screen instructions provided in terminal output to finish. -- Homebrew installs a tool called "brew" which helps add and manage developer packages on MacOS. - -> At this point, the next task is to prepare tools. You must start a new Terminal. Now the Terminal prompt should be prefixed with (base). If not, you need to go back to Anaconda install. -- Open new Terminal, your prompt should look like this... -```bash -(base) iMac:~ jmort1021$ -``` - -> Key Packages needed on MacOS -- Close and Start a new terminal, run each command in Terminal -```bash -$ brew list # list packages -$ brew update # update package list -$ brew upgrade # upgrade packages -$ brew install git # install latest git -$ brew install python # install python3 for development -$ python --version # version of python3 installed -``` -### Windows 1st Time Developer -> VSCode install using WSL. Windows users have option to have best of Windows and Linux while developing within VSCode. -- Install [VSCode using WSL]({{site.baseurl}}/techtalk/vscode-wsl). -- Required review, become familiar with [Windows WSL development](https://code.visualstudio.com/docs/remote/wsl-tutorial) - -> Anaconda install on WSL. -- Try the exact commands in WSL Command / Powershell. -- Only if there is a wget error... To find the latest Linux-x86 distribution hover over ```64-Bit (x86) Installer``` of this page: https://www.anaconda.com/download#downloads. Hover over wget and Anaconda3 commands based on new link. -```bash -> PS C:\Users\UserName> wsl # Windows prompt to WSL command -$ cd /tmp -$ wget https://repo.anaconda.com/archive/Anaconda3-2023.03-1-Linux-x86_64.sh -$ chmod +x Anaconda3-2023.03-1-Linux-x86_64.sh -# Answer yes to all the prompts -$ ./Anaconda3-2023.03-1-Linux-x86_64.sh -``` - -> At this point, the next task is to prepare for Packages, Jupyter Notebooks, and Kernels. You must start a new WSL Command / Powershell. Now the WSL prompt should be prefixed with (base) from Anaconda install. If not, you need to go back to Anaconda install. -- Open Command / Powershell. If you are not looking like this you need to back up. -```bash -> PS C:\Users\ShayM> wsl # Windows prompt -(base) shay@MSI:/mnt/c/Users/ShayM$ cd ~ # WSL prompt -(base) shay@MSI:~$ # WSL home, best place to install files -``` - -> Key Packages needing update on WSL Ubuntu -- In a WSL Command / Powershell install Python3 -```bash -$ sudo apt list # list packages -$ sudo apt update # update package list -$ sudo apt upgrade # upgrade packages -$ sudo apt install python3 python3-pip # install python3 and pip3 for development -$ python --version # version of python3 should be shown - - -### Jupyter Install and Kernels (MacOs and WSL) - -> Install Jupyter and check python kernel -```bash -(base) id:~$ conda --version -(base) id:~$ conda install jupyter # install jupyter -(base) id:~$ jupyter kernelspec list # list installed kernels -Available kernels: - python3 /home/shay/.local/share/jupyter/kernels/python3 -``` diff --git a/_posts/2023-08-16-Tools_Hacks_Sample.md b/_posts/2023-08-16-Tools_Hacks_Sample.md deleted file mode 100644 index ac3031d..0000000 --- a/_posts/2023-08-16-Tools_Hacks_Sample.md +++ /dev/null @@ -1,93 +0,0 @@ ---- -toc: true -comments: true -layout: post -title: Prunned Tool Procedure ... -description: Example hacks!!! This shows procedures performed by student, not the procedures for the entire class. Modified or prunned for specific machine. -courses: { compsci: {week: 0} } -type: hacks ---- - -## Hacks -> Complete the procedure below accurately. These are absolutely required and must be 100% accurate for your success. - -### GitHub Account -- Follow instruction [https://docs.github.com/en/get-started/signing-up-for-github/signing-up-for-a-new-github-account](https://docs.github.com/en/get-started/signing-up-for-github/signing-up-for-a-new-github-account) Use your own personal/permanent email... NOT SCHOOL!!! GitHub account belongs to you. - -### MacOS 1st Time Developer -> VSCode install -- Install [VSCode](https://code.visualstudio.com/docs/setup/mac) - -> Anaconda install -- Download for MacOS: [Anaconda](https://www.anaconda.com/products/distribution) -- Run Install: Answer yes to questions - -> Homebrew install -- Copy and Paste to Install from Terminal [Homebrew](https://brew.sh) - - Copy ```bash ... curl ...``` command using copy box on website - - Launch ```terminal``` from search bar - - Paste ```bash ... curl ...``` command into Terminal ... - - Make sure command starts, this should provide feedback/output in terminal and could take a long time, like 10-min, there could be a prompt in the middle, at about 5-minutes. Follow any on screen instructions provided in terminal output to finish. -- Homebrew installs a tool called "brew" which helps add and manage developer packages on MacOS. - -> At this point, the next task is to prepare tools. You must start a new Terminal. Now the Terminal prompt should be prefixed with (base). If not, you need to go back to Anaconda install. -- Open new Terminal, your prompt should look like this... -```bash -(base) iMac:~ jmort1021$ -``` - -> Key Packages needed on MacOS -- Close and Start a new terminal, run each command in Terminal -```bash -$ brew list # list packages -$ brew update # update package list -$ brew upgrade # upgrade packages -$ brew install git # install latest git -$ brew install python # install python3 for development -$ python --version # version of python3 installed -``` -### Windows 1st Time Developer -> VSCode install using WSL. Windows users have option to have best of Windows and Linux while developing within VSCode. -- Install [VSCode using WSL]({{site.baseurl}}/techtalk/vscode-wsl). -- Required review, become familiar with [Windows WSL development](https://code.visualstudio.com/docs/remote/wsl-tutorial) - -> Anaconda install on WSL. -- Try the exact commands in WSL Command / Powershell. -- Only if there is a wget error... To find the latest Linux-x86 distribution hover over ```64-Bit (x86) Installer``` of this page: https://www.anaconda.com/download#downloads. Hover over wget and Anaconda3 commands based on new link. -```bash -> PS C:\Users\UserName> wsl # Windows prompt to WSL command -$ cd /tmp -$ wget https://repo.anaconda.com/archive/Anaconda3-2023.03-1-Linux-x86_64.sh -$ chmod +x Anaconda3-2023.03-1-Linux-x86_64.sh -# Answer yes to all the prompts -$ ./Anaconda3-2023.03-1-Linux-x86_64.sh -``` - -> At this point, the next task is to prepare for Packages, Jupyter Notebooks, and Kernels. You must start a new WSL Command / Powershell. Now the WSL prompt should be prefixed with (base) from Anaconda install. If not, you need to go back to Anaconda install. -- Open Command / Powershell. If you are not looking like this you need to back up. -```bash -> PS C:\Users\ShayM> wsl # Windows prompt -(base) shay@MSI:/mnt/c/Users/ShayM$ cd ~ # WSL prompt -(base) shay@MSI:~$ # WSL home, best place to install files -``` - -> Key Packages needing update on WSL Ubuntu -- In a WSL Command / Powershell install Python3 -```bash -$ sudo apt list # list packages -$ sudo apt update # update package list -$ sudo apt upgrade # upgrade packages -$ sudo apt install python3 python3-pip # install python3 and pip3 for development -$ python --version # version of python3 should be shown - - -### Jupyter Install and Kernels (MacOs and WSL) - -> Install Jupyter and check python kernel -```bash -(base) id:~$ conda --version -(base) id:~$ conda install jupyter # install jupyter -(base) id:~$ jupyter kernelspec list # list installed kernels -Available kernels: - python3 /home/shay/.local/share/jupyter/kernels/python3 -``` diff --git a/_posts/2023-08-16-Tools_Help.md b/_posts/2023-08-16-Tools_Help.md deleted file mode 100644 index 1de4a40..0000000 --- a/_posts/2023-08-16-Tools_Help.md +++ /dev/null @@ -1,18 +0,0 @@ ---- -toc: false -comments: false -hide: true -layout: post -type: help -title: Tool References ---- - -### `Visual Studio Code` [Overview](https://code.visualstudio.com/docs/introvideos/basics) - -### `Jupyter Notebooks` [Review Jupyter basics 6-min](https://www.youtube.com/watch?v=3jZYC9rGrNg) - -### `WSL` [Basic Commands](https://learn.microsoft.com/en-us/windows/wsl/basic-commands) - -### `Linux Commands` [Cheat Sheet](https://www.geeksforgeeks.org/linux-commands-cheat-sheet/) - -### `Docker` [Docker Overview](https://docs.docker.com/get-started/overview/) diff --git a/_posts/2023-08-21-GitHub_Pages.md b/_posts/2023-08-21-GitHub_Pages.md deleted file mode 100644 index 5e0cb12..0000000 --- a/_posts/2023-08-21-GitHub_Pages.md +++ /dev/null @@ -1,18 +0,0 @@ ---- -toc: true -comments: true -layout: post -title: GitHub Pages -description: Build your first Blog. This will help us communicate results. -type: plans -courses: { csse: {week: 1}, csp: {week: 1, categories: [4.A]}, csa: {week: 0} } -categories: [C1.4] ---- - -### PBL Unit 1 / Week 1 -Learning outcome. Building a personal and running GitHub Pages. -- Monday: Schedule Live Review - 4 minutes. Finish Tools setup. Attend Office Hours on HTML, CSS, JS and Student Blog. -- Tuesday: Read [Markdown Student Page](https://nighthawkcoders.github.io/teacher//c4.3/c5.0/2023/08/17/markdown-html_fragments.html), Attend Office Hours on Updating Home Page and Plan Page. -- Wednesday: Work Plan Page and Home Page. Prep with pair on live review. -- Thursday: 10:45 live review per Canvas. Read [Linux Shell and Bash](https://nighthawkcoders.github.io/teacher//5.a/c4.1/2023/08/16/linux_shell_IPYNB_2_.html). Tranfer blog and customize for my lab notebook. -- Update Blog to contain all hacks. Review week with Pair and look ahead and start plan for next week. diff --git a/_posts/2023-08-21-GitHub_Pages_Plans.md b/_posts/2023-08-21-GitHub_Pages_Plans.md deleted file mode 100644 index aa4dd60..0000000 --- a/_posts/2023-08-21-GitHub_Pages_Plans.md +++ /dev/null @@ -1,27 +0,0 @@ ---- -toc: true -comments: false -layout: post -title: More Detail Plan -description: Example Plan!!! Analyze hacks and plan. -type: plans -courses: { compsci: {week: 1} } ---- - -### PBL Unit 1 / Week 1 -Learning outcome. Building a personal and running GitHub Pages. -- Monday: Schedule Live Review - 4 minutes. Finish Tools setup. Attend Office Hours on HTML, CSS, JS and Student Blog. -- Tuesday: Read [Markdown Student Page](https://nighthawkcoders.github.io/teacher//c4.3/c5.0/2023/08/17/markdown-html_fragments.html), Attend Office Hours on Updating Home Page and Plan Page. -- Wednesday: Work Plan Page and Home Page. Prep with pair on live review. -- Thursday: 10:45 live review per Canvas. Read [Linux Shell and Bash](https://nighthawkcoders.github.io/teacher//5.a/c4.1/2023/08/16/linux_shell_IPYNB_2_.html). Tranfer blog and customize for my lab notebook. - - -### Pair Planning Meeting -> Update Blog to contain all hacks. Review week with Pair and look ahead and start plan for next week. Try to be done and learn your machine before Monday EOD. -- A laptop, that you bring to class every day with ability to operate Development Tools on it or within the Cloud. -- GitHub Account, VSCode will be used to push/pull changes. GitHub is where we store and share code in the cloud, think of Google Docs but for Code. -- GitHub Pages will be used to host your personal blog: containing notes, answering hacks, and showing tangibles. Building pages will teach Markdown, HTML, CSS, JavaScript and more. -- Jupyter Notebooks will be used in conjunction with GitHub Pages to build running Code in your blog. -- Slack Account, install the App on Laptop and/or phone, get used to reading announcements. Slack is the tool that we will use for messaging, we have been averaging 1000s of essages each year. -- VSCode is the code editor we will be using in this class. VSCode is more than and editor, this type of tool is often called an Interactive Development Environment (IDE). -- Run make commands to build and test blog locally, before pushing changes to GitHub pages. diff --git a/_posts/2023-08-21-GitHub_Pages_Tangibles.md b/_posts/2023-08-21-GitHub_Pages_Tangibles.md deleted file mode 100644 index 553a6f5..0000000 --- a/_posts/2023-08-21-GitHub_Pages_Tangibles.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -toc: true -comments: true -layout: post -title: Review Ticket -description: Example Review Ticket!!! This will help us communicate results. -type: tangibles -courses: { compsci: {week: 1} } ---- - -### Summary of Accomplishments -> Update Blog to contain all hacks. -- Reviewed with Pair. Discuss/Show evidence. -- Discuss laptop, cloud computer. -- Discuss tools setup and troubles. -- Show personal blog / home page. -- Show how you are maintaining notes, answering hacks, and showing tangibles. -- How have you learned Markdown, HTML, CSS, JavaScript. -- Show Jupyter Notebooks and how you have added and organized them in the blog. -- Show evidence of using Slack Account, show app installed on Laptop and/or phone. Show awared of #annoncements, #general, #coding. -- Run make commands to build and test blog locally, before pushing changes to GitHub pages. -- Discuss GitHub Account, show ability to push/pull changes from VSCode. -- Discuss development on Themes, show how you plan to organized lab notebook. \ No newline at end of file diff --git a/_posts/2023-08-26-GitHub_Sync.md b/_posts/2023-08-26-GitHub_Sync.md deleted file mode 100644 index 27ac13d..0000000 --- a/_posts/2023-08-26-GitHub_Sync.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -toc: true -comments: false -hide: true -layout: post -type: help -title: GitHub Overview ---- - -## References - -### `GitHub` [Review GitHub concepts 2-min](https://www.youtube.com/watch?v=phGdqJB6ep0) - -### `Git source control` [VSCode](https://code.visualstudio.com/docs/sourcecontrol/overview) -
- -## Create GitHub Page Repository -You will want to create a personal Github Pages blog for this class. This is a place where you can code, complete the hacks, and record what you have learned. - -### Git Config -Run the following commands to configure user git connection to GitHub. This is required, before pushing code to GitHub. - - ```bash - # Setup GitHub ID - git config --global user.email - git config --global user.name - # Verify Setup - git config --list - ``` - -### [click to Create Repository](https://docs.github.com/en/repositories/creating-and-managing-repositories/creating-a-repository-from-a-template) - -1. Use Template to create [student repository](https://github.com/nighthawkcoders/student) - -2. Once your repository is created, click on the green "Code" button and copy the HTTPS link provided. - -3. In Terminal, to your vscode directory (`cd ~/vscode`). Then clone the repository with `git clone `. - -4. Open your repository in VS Code with `code `. Cloud Terminal requires you to open after lanuching VSCode. -
- -## VSCode commit/sync to GitHub Pages -The VSCode saved files are only stored on your computer locally until you commit and then sync the changes. - -### Commit Changes, version control locally -This creates a version of your files in you local git database. Often developers commit several times before they sync in VSCode or push from command line. This allows lots of small changes that can be easily reviewed and rolled back. - -1. Click on the button that supports "Source Control" in VS Code's left sidebar - -2. Click on the plus sign to stage your changes - - ![]({{ site.baseurl }}/images/stage.jpg) - -3. Enter a message for your commit in the message box. - -4. Click the "Commit button" - - -### Sync Changes, update change in GitHub -Sync will push files to GitHub and create an Action for GitHub Pages updates, site will update if code is without errors. - -- Click the Menu button and then click "Push". - - ![]({{ site.baseurl }}/images/push.jpg) - -- Watch Actions until done, open action link and review changes on github.io - diff --git a/_posts/2023-10-31-csafinalmcq1.md b/_posts/2023-10-31-csafinalmcq1.md new file mode 100755 index 0000000..97a9b01 --- /dev/null +++ b/_posts/2023-10-31-csafinalmcq1.md @@ -0,0 +1,56 @@ +--- +toc: true +comments: true +layout: post +title: CSA MCQ review TRI 1 +description: what should I review? +categories: [C1.0] +courses: { compsci: {week: 0} } +type: hacks +--- + +# CSA MCQ SCORE + +![]({{site.baseurl}}/images/mcq1.png) + +# questions wrong + + + +question 1: + + +I got this one wrong because I didn't realize that we were using an enhanced for loop, which means we don't need to access the specific index. + + college board reason: + The getMileage method does not have any parameters, so v.getMileage() will return the mileage for v. Please note that interface is no longer a part of the AP CSA exam. + + +question 2: + + +I got this one wrong because I put a while loop that doesn't update. I should have paid more attention, cause i'm sure I only got it wrong b/c I rushed. + + +question 3: + + +This one I got wrong because I just went with the 1st iteration and didn't really care too much about tracing through completely. honestly, the college board +answer says it all + +college board reason: + +Correct. The modulus operator (%) evaluates to the remainder when the first operand is divided by the second operand. For example, 2574 % 10 evaluates to 4 the remainder when 2574 is divided by 10. In the first iteration of the loop, result is assigned 0 * 10 + 2574 % 10 or 0 + 4 or 4. The value of num is updated to 257 since the division is integer division between two int values. In the second iteration, result is assigned 4 * 10 + 257 % 10 or 40 + 7 or 47 and num is assigned 25. In the third iteration, result is assigned 47 * 10 + 25 % 10 or 470 + 5 or 475 and num is assigned 2. In the fourth iteration, result is assigned 475 * 10 + 2 % 10 or 4750 + 2 or 4752 and num is assigned 0. At this point the loop will terminate and 4752 will be printed to the screen. + + +I really need to work on tracing... + + +# final revision + +1. pay careful attention when answering while loops + +2. honestly just use paper for tracing problems because theres lots of margin for error + +3. understand that enchanced for loops don't need to access specific indexes. + diff --git a/scripts/__pycache__/convert_notebooks.cpython-310.pyc b/scripts/__pycache__/convert_notebooks.cpython-310.pyc new file mode 100644 index 0000000..6213cf0 Binary files /dev/null and b/scripts/__pycache__/convert_notebooks.cpython-310.pyc differ