diff --git a/_config.yml b/_config.yml
index c7d0d69a..3bf6ac4b 100644
--- a/_config.yml
+++ b/_config.yml
@@ -1,9 +1,9 @@
-title: Nighthawk Pages
-description: "Class of 2025"
+title: DNHS Flocker
+description: "Social Media for Del Norte High School"
owner_name: John Mortensen
github_username: nighthawkcoders
-github_repo: "portfolio_2025"
-baseurl: "/portfolio_2025"
+github_repo: "flocker_frontend"
+baseurl: "/flocker_frontend"
future: true
remote_theme: jekyll/minima
minima:
@@ -20,9 +20,5 @@ minima:
plugins:
- jekyll-remote-theme
header_pages:
- - navigation/blog.md
- - navigation/rpg.md
- - navigation/game.md
- navigation/search.md
- - README4YML.md
- navigation/about.md
\ No newline at end of file
diff --git a/_includes/nav/CSA_Units/csa_unit1.html b/_includes/nav/CSA_Units/csa_unit1.html
deleted file mode 100644
index 8296fd16..00000000
--- a/_includes/nav/CSA_Units/csa_unit1.html
+++ /dev/null
@@ -1,11 +0,0 @@
-
\ No newline at end of file
diff --git a/_includes/nav/CSA_Units/csa_unit2.html b/_includes/nav/CSA_Units/csa_unit2.html
deleted file mode 100644
index dd03ddd8..00000000
--- a/_includes/nav/CSA_Units/csa_unit2.html
+++ /dev/null
@@ -1,11 +0,0 @@
-
\ No newline at end of file
diff --git a/_includes/nav/CSA_Units/csa_unit3.html b/_includes/nav/CSA_Units/csa_unit3.html
deleted file mode 100644
index 4d8673f6..00000000
--- a/_includes/nav/CSA_Units/csa_unit3.html
+++ /dev/null
@@ -1,11 +0,0 @@
-
\ No newline at end of file
diff --git a/_includes/nav/CSA_Units/csa_unit3_p1.html b/_includes/nav/CSA_Units/csa_unit3_p1.html
deleted file mode 100644
index fb2b0194..00000000
--- a/_includes/nav/CSA_Units/csa_unit3_p1.html
+++ /dev/null
@@ -1,13 +0,0 @@
-
\ No newline at end of file
diff --git a/_includes/nav/CSA_Units/csa_unit4.html b/_includes/nav/CSA_Units/csa_unit4.html
deleted file mode 100644
index bda1f5ed..00000000
--- a/_includes/nav/CSA_Units/csa_unit4.html
+++ /dev/null
@@ -1,11 +0,0 @@
-
\ No newline at end of file
diff --git a/_includes/nav/CSA_Units/csa_unit4_p1.html b/_includes/nav/CSA_Units/csa_unit4_p1.html
deleted file mode 100644
index 8d50a835..00000000
--- a/_includes/nav/CSA_Units/csa_unit4_p1.html
+++ /dev/null
@@ -1,10 +0,0 @@
-
\ No newline at end of file
diff --git a/_includes/nav/CSA_Units/csa_unit5.html b/_includes/nav/CSA_Units/csa_unit5.html
deleted file mode 100644
index 4bc8b1c9..00000000
--- a/_includes/nav/CSA_Units/csa_unit5.html
+++ /dev/null
@@ -1,12 +0,0 @@
-
\ No newline at end of file
diff --git a/_includes/nav/CSA_Units/csa_unit5_p1.html b/_includes/nav/CSA_Units/csa_unit5_p1.html
deleted file mode 100644
index b2dd2450..00000000
--- a/_includes/nav/CSA_Units/csa_unit5_p1.html
+++ /dev/null
@@ -1,12 +0,0 @@
-
\ No newline at end of file
diff --git a/_includes/nav/CSA_Units/csa_unit5_p3.html b/_includes/nav/CSA_Units/csa_unit5_p3.html
deleted file mode 100644
index 01d62226..00000000
--- a/_includes/nav/CSA_Units/csa_unit5_p3.html
+++ /dev/null
@@ -1,16 +0,0 @@
-
\ No newline at end of file
diff --git a/_includes/nav/CSA_Units/csa_unit6.html b/_includes/nav/CSA_Units/csa_unit6.html
deleted file mode 100644
index 83942049..00000000
--- a/_includes/nav/CSA_Units/csa_unit6.html
+++ /dev/null
@@ -1,10 +0,0 @@
-
\ No newline at end of file
diff --git a/_includes/nav/CSA_Units/csa_unit6_p1.html b/_includes/nav/CSA_Units/csa_unit6_p1.html
deleted file mode 100644
index 83942049..00000000
--- a/_includes/nav/CSA_Units/csa_unit6_p1.html
+++ /dev/null
@@ -1,10 +0,0 @@
-
\ No newline at end of file
diff --git a/_includes/nav/CSA_Units/csa_unit6_p3.html b/_includes/nav/CSA_Units/csa_unit6_p3.html
deleted file mode 100644
index 1a12c15b..00000000
--- a/_includes/nav/CSA_Units/csa_unit6_p3.html
+++ /dev/null
@@ -1,9 +0,0 @@
-
\ No newline at end of file
diff --git a/_includes/nav/CSA_Units/csa_unit7_p1.html b/_includes/nav/CSA_Units/csa_unit7_p1.html
deleted file mode 100644
index 1d5945c0..00000000
--- a/_includes/nav/CSA_Units/csa_unit7_p1.html
+++ /dev/null
@@ -1,14 +0,0 @@
-
diff --git a/_includes/nav/CSA_Units/csa_unit7_p3.html b/_includes/nav/CSA_Units/csa_unit7_p3.html
deleted file mode 100644
index 9abcc4db..00000000
--- a/_includes/nav/CSA_Units/csa_unit7_p3.html
+++ /dev/null
@@ -1,14 +0,0 @@
-
\ No newline at end of file
diff --git a/_includes/nav/CSA_Units/csa_unit8.html b/_includes/nav/CSA_Units/csa_unit8.html
deleted file mode 100644
index d7e947d0..00000000
--- a/_includes/nav/CSA_Units/csa_unit8.html
+++ /dev/null
@@ -1,10 +0,0 @@
-
\ No newline at end of file
diff --git a/_includes/nav/CSA_Units/csa_unit8_p1.html b/_includes/nav/CSA_Units/csa_unit8_p1.html
deleted file mode 100644
index d7e947d0..00000000
--- a/_includes/nav/CSA_Units/csa_unit8_p1.html
+++ /dev/null
@@ -1,10 +0,0 @@
-
\ No newline at end of file
diff --git a/_includes/nav/CSA_Units/csa_unit8_p3.html b/_includes/nav/CSA_Units/csa_unit8_p3.html
deleted file mode 100644
index d7bd57e8..00000000
--- a/_includes/nav/CSA_Units/csa_unit8_p3.html
+++ /dev/null
@@ -1,9 +0,0 @@
-
\ No newline at end of file
diff --git a/_includes/nav/CSA_Units/unit2/period3.html b/_includes/nav/CSA_Units/unit2/period3.html
deleted file mode 100644
index ac020ecc..00000000
--- a/_includes/nav/CSA_Units/unit2/period3.html
+++ /dev/null
@@ -1,11 +0,0 @@
-
\ No newline at end of file
diff --git a/_includes/nav/GPT_overview.html b/_includes/nav/GPT_overview.html
deleted file mode 100644
index 89ca453b..00000000
--- a/_includes/nav/GPT_overview.html
+++ /dev/null
@@ -1,8 +0,0 @@
-
\ No newline at end of file
diff --git a/_includes/nav/csp_unit3.html b/_includes/nav/csp_unit3.html
deleted file mode 100644
index e69de29b..00000000
diff --git a/_includes/nav/csp_units/csp_unit3_p1_fundamentals.html b/_includes/nav/csp_units/csp_unit3_p1_fundamentals.html
deleted file mode 100644
index 5fc38873..00000000
--- a/_includes/nav/csp_units/csp_unit3_p1_fundamentals.html
+++ /dev/null
@@ -1,83 +0,0 @@
-Fall 2024 - P1
-
\ No newline at end of file
diff --git a/_includes/nav/csp_units/csp_unit3_p2_fundamentals.html b/_includes/nav/csp_units/csp_unit3_p2_fundamentals.html
deleted file mode 100644
index 51322f88..00000000
--- a/_includes/nav/csp_units/csp_unit3_p2_fundamentals.html
+++ /dev/null
@@ -1,124 +0,0 @@
-
-
- Fall 2024 - P2
-
\ No newline at end of file
diff --git a/_includes/nav/csp_units/csp_unit3_p3_fundamentals.html b/_includes/nav/csp_units/csp_unit3_p3_fundamentals.html
deleted file mode 100644
index f999245c..00000000
--- a/_includes/nav/csp_units/csp_unit3_p3_fundamentals.html
+++ /dev/null
@@ -1,97 +0,0 @@
-Fall 2024 - P3
-
-
\ No newline at end of file
diff --git a/_includes/nav/csp_units/csp_unit3_p4_fundamentals.html b/_includes/nav/csp_units/csp_unit3_p4_fundamentals.html
deleted file mode 100644
index 2b9723fa..00000000
--- a/_includes/nav/csp_units/csp_unit3_p4_fundamentals.html
+++ /dev/null
@@ -1,96 +0,0 @@
-Fall 2024 - P4
-
-
\ No newline at end of file
diff --git a/_includes/nav/csp_units/csp_unit3_p5_fundamentals.html b/_includes/nav/csp_units/csp_unit3_p5_fundamentals.html
deleted file mode 100644
index 1522e8e3..00000000
--- a/_includes/nav/csp_units/csp_unit3_p5_fundamentals.html
+++ /dev/null
@@ -1,82 +0,0 @@
-Fall 2024 - P5
-
-
\ No newline at end of file
diff --git a/_includes/nav/flask.html b/_includes/nav/flask.html
deleted file mode 100644
index 7d610d2e..00000000
--- a/_includes/nav/flask.html
+++ /dev/null
@@ -1,15 +0,0 @@
-
\ No newline at end of file
diff --git a/_includes/nav/frontend_basics.html b/_includes/nav/frontend_basics.html
deleted file mode 100644
index 7871e578..00000000
--- a/_includes/nav/frontend_basics.html
+++ /dev/null
@@ -1,13 +0,0 @@
-
\ No newline at end of file
diff --git a/_includes/nav/fullstack_java.html b/_includes/nav/fullstack_java.html
deleted file mode 100644
index 5a2508bf..00000000
--- a/_includes/nav/fullstack_java.html
+++ /dev/null
@@ -1,10 +0,0 @@
-
\ No newline at end of file
diff --git a/_includes/nav/game_animations.html b/_includes/nav/game_animations.html
deleted file mode 100644
index e69de29b..00000000
diff --git a/_includes/nav/game_intro.html b/_includes/nav/game_intro.html
deleted file mode 100644
index bededd5f..00000000
--- a/_includes/nav/game_intro.html
+++ /dev/null
@@ -1,10 +0,0 @@
-
\ No newline at end of file
diff --git a/_includes/nav/game_mario.html b/_includes/nav/game_mario.html
deleted file mode 100644
index f707e450..00000000
--- a/_includes/nav/game_mario.html
+++ /dev/null
@@ -1,11 +0,0 @@
-
\ No newline at end of file
diff --git a/_includes/nav/github_pages.html b/_includes/nav/github_pages.html
deleted file mode 100644
index be747dcf..00000000
--- a/_includes/nav/github_pages.html
+++ /dev/null
@@ -1,11 +0,0 @@
-
\ No newline at end of file
diff --git a/_includes/nav/home.html b/_includes/nav/home.html
index 4f0b4cda..01c59249 100644
--- a/_includes/nav/home.html
+++ b/_includes/nav/home.html
@@ -1,10 +1,10 @@
- CSSE
- CSP
- CSA
- Kasm
+ Math
+ English
+ Band
+ Sports
Login
diff --git a/_includes/nav/inheritance.html b/_includes/nav/inheritance.html
deleted file mode 100644
index f5dc5344..00000000
--- a/_includes/nav/inheritance.html
+++ /dev/null
@@ -1,12 +0,0 @@
-
\ No newline at end of file
diff --git a/_includes/nav/java_spring.html b/_includes/nav/java_spring.html
deleted file mode 100644
index 54a0484e..00000000
--- a/_includes/nav/java_spring.html
+++ /dev/null
@@ -1,13 +0,0 @@
-
\ No newline at end of file
diff --git a/_includes/nav/javascript_project.html b/_includes/nav/javascript_project.html
deleted file mode 100644
index 93c20ca7..00000000
--- a/_includes/nav/javascript_project.html
+++ /dev/null
@@ -1,11 +0,0 @@
-
\ No newline at end of file
diff --git a/_includes/nav/kasm_cloud.html b/_includes/nav/kasm_cloud.html
deleted file mode 100644
index 7ed03dba..00000000
--- a/_includes/nav/kasm_cloud.html
+++ /dev/null
@@ -1,108 +0,0 @@
-
-
-
-
-
diff --git a/_includes/nav/p4prompt.html b/_includes/nav/p4prompt.html
deleted file mode 100644
index 9ad64519..00000000
--- a/_includes/nav/p4prompt.html
+++ /dev/null
@@ -1,39 +0,0 @@
-
-
-
\ No newline at end of file
diff --git a/_includes/nav/pair_programming.html b/_includes/nav/pair_programming.html
deleted file mode 100644
index 20bca2f4..00000000
--- a/_includes/nav/pair_programming.html
+++ /dev/null
@@ -1,8 +0,0 @@
-
\ No newline at end of file
diff --git a/_includes/nav/sass_basics.html b/_includes/nav/sass_basics.html
deleted file mode 100644
index aac2430e..00000000
--- a/_includes/nav/sass_basics.html
+++ /dev/null
@@ -1,9 +0,0 @@
-
\ No newline at end of file
diff --git a/_includes/nav/tools_setup.html b/_includes/nav/tools_setup.html
deleted file mode 100644
index adcc5d14..00000000
--- a/_includes/nav/tools_setup.html
+++ /dev/null
@@ -1,11 +0,0 @@
-
\ No newline at end of file
diff --git a/_notebooks/2023-08-23-jupyter-notebook-python.ipynb b/_notebooks/2023-08-23-jupyter-notebook-python.ipynb
index 2389a638..2771184d 100644
--- a/_notebooks/2023-08-23-jupyter-notebook-python.ipynb
+++ b/_notebooks/2023-08-23-jupyter-notebook-python.ipynb
@@ -13,9 +13,8 @@
"layout: post\n",
"title: Playing with Jupyter Notebooks and Python\n",
"description: GitHub pages was built with Python and Jupyter Notebooks in mind. This post is to verify tools by using Python. \n",
- "categories: [DevOps, Python]\n",
+ "categories: [Python]\n",
"permalink: /jupyter/notebook/python\n",
- "menu: nav/tools_setup.html\n",
"toc: true\n",
"comments: true\n",
"---"
diff --git a/_notebooks/CSA/2024-10-06-sprint2_plan.ipynb b/_notebooks/CSA/2024-10-06-sprint2_plan.ipynb
deleted file mode 100644
index 65e111f8..00000000
--- a/_notebooks/CSA/2024-10-06-sprint2_plan.ipynb
+++ /dev/null
@@ -1,158 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "title: Sprint 2 - CSA Objectives \n",
- "description: Student Teach and Software Development Objectives for Sprint 2\n",
- "type: issues \n",
- "courses: { csa: {week: 3} }\n",
- "comments: true\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Issues\n",
- "Teacher and Peer evaluation are critical to our success and improvements. Be sure to support meeting objectives by providing feedback and acting on feedback received."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Student Teaching - Part 1 Fundamentals\n",
- "\n",
- "Students will engage in lesson preparation, teaching, and grading. This activity is often called \"Team Teach\". The process and purpose are as follows:\n",
- "\n",
- "1. Learn Units #1-#10 from the College Board.\n",
- "2. Build a lesson using Java for each of the topics provided by the teacher's starters.\n",
- "3. The lesson should include a Tech Talk portion, popcorn hacks, and homework hacks. The lesson should NOT have more than 5 minutes of talking before engaging students in an activity (e.g., popcorn hacks).\n",
- "4. Be prepared to grade homework. This means having a plan for homework and a plan for grading the homework. You will grade on a \"1-point\" scale. Weight popcorn hacks and homework hacks in the grading.\n",
- "5. Lesson time will be between 20 and 30 minutes. Homework time should be about the same as lesson time."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Lesson Building \n",
- "\n",
- "#### Grading Guideline\n",
- "- 55% is minimum per item\n",
- "- 75% is mostly done\n",
- "- 85% is complete\n",
- "- 90% is maximum perfection\n",
- "\n",
- "| **Assignment** | **Points** | **Grade** | **Evidence** |\n",
- "|----------------------------|---------------|-----------|--------------|\n",
- "| Pull Request (Integration) | 2 | | |\n",
- "| Relevancy Checklist (Peer) | 2 | | |\n",
- "| Lesson (Group) | 1 | | |\n",
- "| Homework, Popcorn Hacks | 1 x 8 | | |\n",
- "| Individual Contribution | 1 | | |\n",
- "| Personal Notebooks / Blogs | 1 | | |\n",
- "| **Total** | 12 | | |\n",
- "\n",
- "\n",
- "| **Skill** | **Points** | **Grade** | **Evidence** |\n",
- "|----------------------------|---------------|-----------|--------------|\n",
- "| Work Habits (Analytics) | 1 | | |\n",
- "| Team Planning (Issue) | 1 | | |\n",
- "| Presentation Memories | 1 | | |\n",
- "| Grading and Feedback | 1 | | |\n",
- "| Beyond Perfunctory | 1 | | | \n",
- "| **Total** | 5 | | |\n",
- "\n",
- "#### Raw Form\n",
- "\n",
- "```text\n",
- "| **Assignment** | **Points** | **Grade** | **Evidence** |\n",
- "|----------------------------|---------------|-----------|--------------|\n",
- "| Pull Request (Integration) | 2 | | |\n",
- "| Relevancy Checklist (Peer) | 2 | | |\n",
- "| Lesson (Group) | 1 | | |\n",
- "| Homework, Popcorn Hacks | 1 x 8 | | |\n",
- "| Individual Contribution | 1 | | |\n",
- "| Personal Notebooks / Blogs | 1 | | |\n",
- "| Total | 12 | | |\n",
- "\n",
- "\n",
- "| **Skill** | **Points** | **Grade** | **Evidence** |\n",
- "|----------------------------|---------------|-----------|--------------|\n",
- "| Work Habits (Analytics) | 1 | | |\n",
- "| Team Planning (Issue) | 1 | | |\n",
- "| Presentation Memories | 1 | | |\n",
- "| Grading and Feedback | 1 | | |\n",
- "| Beyond Perfunctory | 1 | | | \n",
- "| Total | 5 | | |\n",
- "```"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Lesson Review - Topic Relevancy (Stdent Review)\n",
- "\n",
- "Peer review checklist. Guideance\n",
- "\n",
- "- Scurm Master should coordinate.\n",
- "\n",
- "- Peer grading should be coordinated in Slack, if there are any issues.\n",
- "\n",
- "- Lesson providers will receive reviews from a peers in another class, doing the same topic, by enabling Utterances on your topic(s).\n",
- "\n",
- "- Peer graders will grade on Utterances. Be sure two people provide a review to every section of lesson (ie 2 reviews on intro, 2 reviews on .1, 2 reviews on .2, ...). \n",
- "\n",
- "- Assingments are to review corresponding topics in other classes where possible. Otherwise review topic that does not match one taught in classroom.\n",
- "\n",
- "Note 1. **Student reviewers will be evaluated on how and if you perform a review** \n",
- "Note 2. **Student lesson providers will be evaluated if they improve lesson based off of feedback. Remebmer/document your changes**\n",
- "\n",
- "\n",
- "#### Relevancy Checklist\n",
- "\n",
- "| **Assignment** | **Weightage** | **Grade** | **Comments** |\n",
- "|-------------------------|---------------|-----------|--------------|\n",
- "| College Board Coverage | 20 | TBD | TBD |\n",
- "| Java Examples | 30 | TBD | TBD |\n",
- "| Popcorn Hack Usage | 10 | TBD | TBD |\n",
- "| Homework | 10 | TBD | TBD |\n",
- "| Grading Plan | 10 | TBD | TBD |\n",
- "| Original an Creative | 10 | TBD | TBD |\n",
- "| **Total** | **90** | | |\n",
- "\n",
- "#### Raw Form\n",
- "\n",
- "```text\n",
- "| **Assignment** | **Weightage** | **Grade** | **Comments** |\n",
- "|-------------------------|---------------|-----------|--------------|\n",
- "| College Board Coverage | 20 | TBD | TBD |\n",
- "| Java Examples | 30 | TBD | TBD |\n",
- "| Popcorn Hack Usage | 10 | TBD | TBD |\n",
- "| Homework | 10 | TBD | TBD |\n",
- "| Grading Plan | 10 | TBD | TBD |\n",
- "| Original an Creative | 10 | TBD | TBD |\n",
- "| Total | **90** | | |\n",
- "```"
- ]
- }
- ],
- "metadata": {
- "language_info": {
- "name": "python"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/chatgpt/2024-07-16-chatgpt-code.ipynb b/_notebooks/CSA/chatgpt/2024-07-16-chatgpt-code.ipynb
deleted file mode 100644
index 91dc8c96..00000000
--- a/_notebooks/CSA/chatgpt/2024-07-16-chatgpt-code.ipynb
+++ /dev/null
@@ -1,171 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "title: GPT chatbot code breakdown\n",
- "description: important docmentation for GPT chatbot\n",
- "type: ccc\n",
- "courses: { csa: {week: 7} }\n",
- "menu: nav/GPT_overview.html\n",
- "toc: true\n",
- "comments: true\n",
- "permalink: /GPT_overview/chatbot_code\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "> this part is for developers who want to add features to this chatbot. This code overview will be most helpful if you have gotten the chatbot working and are now working on new features to add."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# notable frontend code:\n",
- "\n",
- "most frontend code is just for handling the response and formatting it for display on the frontend. There is one method which you should know exists in the frontend though. However \n",
- "you won't need to make any changes likely. This function just handles sending the request to the api. Different endpoints are called by creating new methods which call this method, but pass in a different url."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "javascript"
- }
- },
- "outputs": [],
- "source": [
- "//in /assets/js/chatbot.js\n",
- "\n",
- "// Function to fetch data from the API\n",
- "async function fetchData(url, method = \"GET\", data = null) {\n",
- " const options = {\n",
- " method, // HTTP method (GET, POST, DELETE, etc.)\n",
- " headers: { \"Content-Type\": \"application/json\" }, // Headers for the request\n",
- " mode: \"cors\", // Cross-origin resource sharing\n",
- " cache: \"no-cache\", // No caching\n",
- " credentials: \"same-origin\", // Same-origin credentials\n",
- " redirect: \"follow\", // Follow redirects\n",
- " referrerPolicy: \"no-referrer\", // No referrer policy\n",
- " };\n",
- " if (data) options.body = JSON.stringify(data); // Add body data if provided\n",
- " const response = await fetch(url, options); // Fetch data from the API //:)\n",
- " if (!response.ok){\n",
- " const errorMsg = 'AI Bot Error: ' + response.status;\n",
- " console.log(errorMsg);\n",
- " \n",
- " return Promise.reject(errorMsg);\n",
- " }\n",
- " console.log(response); // Log the response for debugging\n",
- " return response.json(); // Return the response text\n",
- " }\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "See how this delete method uses this method, but passes in different parameters:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "javascript"
- }
- },
- "outputs": [],
- "source": [
- "async function deleteChat(id){\n",
- " const chats = await fetchData(`${urls.deleteChat}${id}?personid=${elements.personid.value}`, \"DELETE\"); // Send a DELETE request to clear chat history\n",
- " // it returns the update chat history\n",
- " // display updated chat history\n",
- " console.log(chats);\n",
- " elements.chat.innerHTML = \"\"; // Clear the chat display area\n",
- " appendMessage(assets.botName, assets.botImg, \"left\", \"Your updated chat history!\", assets.botTitle, \"\", formatDate(new Date())); // Inform the user that the chat history is loaded\n",
- "\n",
- " chats.forEach(chat => { // Loop through each chat message\n",
- " console.log(chat);\n",
- " appendMessage(assets.personName, assets.personImg, \"right\", chat['chatMessage'], assets.personTitle, chat['id'], formatMessageDate(chat['timestamp'])); // Append user's message\n",
- " appendMessage(assets.botName, assets.botImg, \"left\", chat['chatResponse'], assets.botTitle, chat['id'], formatMessageDate(chat['timestamp'])); // Append bot's response\n",
- " });\n",
- " \n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# backend code\n",
- "\n",
- "The most important file to take note of from the chathistory folder is the AIChatbotController.java. This contains all of the endpoints and the methods associated with them. So if you wanted to add a new backend endpoint for new functionality, you would likely start here with creating the endpoint and method.\n",
- "\n",
- "In the file itself, most of the methods are self explanatory. This method however is incredibly important, so I will go over it here:\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "@GetMapping(\"/chat\")\n",
- "public ResponseEntity> chat(@RequestParam String message,@RequestParam Long personid) {\n",
- " try {\n",
- " // user sends a message that is sent to chat gpt and a response is returned\n",
- " String response = getResponseFromAI(message);\n",
- " // getResponseFromAI method is used to send actual request.\n",
- " System.out.println(\"Chat: \" + message);\n",
- " System.out.println(\"Response: \" + response);\n",
- " \n",
- " Chat chat = new Chat(message, response, new Date(System.currentTimeMillis()), personid);\n",
- " Chat chatUpdated = chatJpaRepository.save(chat);\n",
- " System.out.println(\"Chat saved in db: \" + chatUpdated.getId());\n",
- " return new ResponseEntity(chatUpdated, HttpStatus.OK);\n",
- " //return response\n",
- " } catch (Exception e) {\n",
- " e.printStackTrace();\n",
- " return new ResponseEntity(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);\n",
- " }\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "this method is the endpoint which sends the response using the message from the frontend. Look at this function in conjunction with the frontend to understand how it works.\n",
- "\n",
- "If you want to develop new methods, consider looking at other methods and taking inspiration from their implementations."
- ]
- }
- ],
- "metadata": {
- "kernelspec": {
- "display_name": "Java",
- "language": "java",
- "name": "java"
- },
- "language_info": {
- "name": "java"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/chatgpt/2024-07-16-chatgpt-intro.ipynb b/_notebooks/CSA/chatgpt/2024-07-16-chatgpt-intro.ipynb
deleted file mode 100644
index d2daf60d..00000000
--- a/_notebooks/CSA/chatgpt/2024-07-16-chatgpt-intro.ipynb
+++ /dev/null
@@ -1,203 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "title: GPT chatbot overview and basic guide\n",
- "description: Simple overview of a basic chatbot implementation using nighthawk pages and java spring backend.\n",
- "type: ccc\n",
- "courses: { csa: {week: 7} }\n",
- "menu: nav/GPT_overview.html\n",
- "toc: true\n",
- "comments: true\n",
- "permalink: /GPT_overview/overview\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# what is this? \n",
- "\n",
- "> This is a GPT chatbot implementation that runs off of the gpt API. \n",
- "\n",
- "With this, you will be able to create a basic chatbot that can easily be implemented in your projects. \n",
- "\n",
- "# But ChatGPT already exists and requires no setup, why should I do what has already been done?\n",
- "\n",
- "Creating a custom chatbots can work as a good personal project to add to your github page or your resume. If you add some truly impressive features or adapt this chatbot to your project in \n",
- "a creative way, adding this project to your personal projects wouldn't be a bad idea.\n",
- "\n",
- "And although it is true that chatGPT already exists and this is a near 1-1 copy of chatGPT in it's browser state, the difference is that you can customize this chatbot\n",
- "and add your own features or style the frontend how you would like it to be.\n",
- "\n",
- "In fact, here is a list of all of the features built into this chatbot example that chatgpt does not have:\n",
- "\n",
- "1. custom background which can be stylized to your liking via sass.\n",
- "\n",
- "2. ability to toggle between instant output style and streamed output style.\n",
- "\n",
- "3. store all messages in a sqlite database.\n",
- "\n",
- "4. instantly recall messages from sqlite database.\n",
- "\n",
- "\n",
- "# all important files for setting up chatbot\n",
- "\n",
- "In portfolio_2025, the frontend contains the following important files (https://github.com/nighthawkcoders/portfolio_2025):\n",
- "\n",
- "/_posts/2024-07-11-GPTchatbot.md (the main frontend file)\n",
- "\n",
- "/assets/js/chatbot.js (javascript for functions which call to the endpoints)\n",
- "\n",
- "_sass/nighthawk/chatbot.scss (styling for the frontend)\n",
- "\n",
- "In Spring portfolio, the backend contains these important files/folders (https://github.com/nighthawkcoders/portfolio_2025):\n",
- "\n",
- "src/main/java/com/nighthawk/spring_portfolio/mvc/chatBot (folder containing all of the backend java files for setting up the GPT endpoints)\n",
- "\n",
- ".env (the location where your GPT api key information must be stored)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# how does this work?\n",
- "\n",
- "> open the chatbot demo to follow along with this part.\n",
- "\n",
- "This basic chatbot implementation simply makes calls to the GPT API, taking in the message you typed in and returning the response the api generated from the message sent. Other than basic chatbot functionality, there are a few different new features for experimentation:\n",
- "\n",
- "1: all messages are saved in sqlite.db on the backend.\n",
- "\n",
- "2: pressing the reload button next to the trash can icon on the chatbot frontend will fetch all responses from the database and display them.\n",
- "\n",
- "3: pressing the trash can icon will delete all of the chats from the database.\n",
- "\n",
- "4: pressing the button at the bottom lets you switch between a streamed response, which will gradually feed the response to the user, versus an instant response."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# basic demo instructions\n",
- "\n",
- "1: clone the following repository for the java backend, if you didn't already have this project available: https://github.com/nighthawkcoders/spring_2025\n",
- "\n",
- "this is a java backend built on spring, and will be used for the endpoints for our project. It also contains all the code for calling the api.\n",
- "\n",
- "2: add your own api key variables to the .env file (see guide below for obtaining all the necessary variables)\n",
- "\n",
- "## obtaining api variables from OPENAI\n",
- "\n",
- "This part of the guide will be a walkthrough to acquiring the assistantId, threadId, and aiKey, which are required for accessing the OPENAI api.\n",
- "\n",
- "1. go to https://platform.openai.com/account/api-keys and create an account or log in\n",
- "\n",
- "2. create a new secret key, with all permissions, and save your key. Add the secret to the .env for the ai_key variable.\n",
- "\n",
- "3. click on Assistants on the left navbar and create a new assistant. Take note of the assistant id at the top, as this is the assistant id. add that id variable to your .env for the ai_asst_id variable.\n",
- "\n",
- "\n",
- "4. afterwards, click on the Assistants from the Playground section of the left navbar, and send a message.\n",
- "\n",
- "5. copy the thread id generated from the message and add it to the .env for the ai_thread_id variable.\n",
- "\n",
- "## Setting up payment\n",
- "\n",
- "yes, you do need to pay to use the GPT api. However, pricing is far cheaper than you think. GPT 3.5, the model used in this example, only costs 3 dollars per 1 million tokens. For context,\n",
- "a token is basically pieces of words that make up the input to the API.\n",
- "\n",
- "1 token is about 4 characters in english and 100 tokens is about 75 words, so hitting 1 million tokens used is harder than you think, assuming you don't spam the API. \n",
- "\n",
- "Realistically, the max you would spend on this project would be less than a chocolate bar, And in return, you get to develop a project that can easily be worked into a resume or\n",
- "project portfolio, and will look impressive to employers seeking to hire individuals who are working with the latest tech. \n",
- "\n",
- "to set up payment,\n",
- "\n",
- "i. go to settings and click on billing\n",
- "\n",
- "ii. add a payment option\n",
- "\n",
- "Once payment is setup, you will be able to send your requests to the gpt api.\n",
- "\n",
- "IMPORTANT: It is important to hide your secret variables to prevent theft of keys. Do not commit the .env with all of the variables within directly to github, as your key will likely get stolen. There are many different solutions for hiding secrets, however the one I used was simply splitting each variable into 2 separate strings, then concatenating them when I needed those secret variables.\n",
- "\n",
- "## testing key functionality\n",
- "\n",
- "At this point, you should also test the key functionality by running the static main method in AIChatbotController.java, which will send a test message using your api key. You can run the method by clicking the run button, which should appear above the method. The method should look like this:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "\t// main method for testing key functionality\n",
- "\tpublic static void main(String[] args) throws Exception {\n",
- "\t\tString aiKey = System.getenv(\"AI_KEY\");\n",
- " System.out.println(\"AI key: \" + aiKey);\n",
- "\t\tAIChatbotController ai = new AIChatbotController();\n",
- "\t\tString response = ai.getResponseFromAI(\"Hi\");\n",
- "\t\tSystem.out.println(response);\n",
- "\t}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "run the method and check the console for a response. If you get a basic reply from the bot, then you have successfully setup your backend and can make basic calls\n",
- "to the chatgpt api.\n",
- "\n",
- "If the method fails, check the error message. Its likely that you just setup the gpt key incorrectly."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "\n",
- "### running the full stack (frontend, backend)\n",
- "\n",
- "If you are using portfolio_2025, you should only have to run the frontend locally and open the chatbot frontend page.\n",
- "\n",
- "Then run the backend locally, and send a message through the frontend.\n",
- "\n",
- "check the console of the backend to make sure the request goes through. \n"
- ]
- }
- ],
- "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/CSA/fullstack_java/2024-07-21-Fullstack-intro.ipynb b/_notebooks/CSA/fullstack_java/2024-07-21-Fullstack-intro.ipynb
deleted file mode 100644
index d446feae..00000000
--- a/_notebooks/CSA/fullstack_java/2024-07-21-Fullstack-intro.ipynb
+++ /dev/null
@@ -1,85 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "title: Fullstack Development\n",
- "description: A reminder and guide to full stack development, aka learn how to do everyone job\n",
- "type: ccc\n",
- "courses: { csa: {week: 7} }\n",
- "permalink: /fullstack/java/intro\n",
- "menu: nav/fullstack_java.html\n",
- "toc: true\n",
- "comments: true\n",
- "author: Finn Carpenter\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Introduction\n",
- "> What is Full Stack?\n",
- "- A full stack feature in software development refers to a feature or functionality that spans both the **front end** (client side) and the **back end** (server side) of an application. \n",
- "- This means that the feature includes everything from the **user interface** and user experience (what the user sees and interacts with) to the **server**, **database**, and **logic** that make the feature work behind the scenes.\n",
- "- The components or stack of this feature are usually as follows\n",
- "1. **Frontend**, the part that the user interacts with\n",
- "2. **Backend**, the sever side of the feature, handling requests, interactions with the database\n",
- "3. **Database**, Where the apps data is stored and managed\n",
- "4. **API**, The Application Programming Interface allows the fronted to connect and communicate with backend\n",
- "\n",
- "## Framework\n",
- "- When creating the backend and frontend of your project you should have a clear answer to these two questions\n",
- "1. What **data** will need to be stored for my feature to work, and what **endpoints** are needed for my feature?\n",
- "2. What will the **wireframe** for my feature look like, and how will it be **auto-generated**?\n",
- "- The questions above are what make your feature unique, no matter the feature there will always be a certain partition of the code that is the exact same\n",
- "- If you're able to answer these questions above you will have no problem in seeing the vision of your feature\n",
- "\n",
- "## How to answer the questions with your idea\n",
- "- In these documents im going to be creating a announcement API, so I will be creating that when I talk about my own feature\n",
- "\n",
- "1. Question #1\n",
- "- For a announcement, I'm going to need an **ID** (standard in every database), **author**, **title**, **body**, **time**, and **tags** data\n",
- "- For the endpoints think about how this data need's to be accessed besides the usual CRUD (Create/Read/Update/Delete) methods, maybe a **fetch** by **author** or **tag**\n",
- "\n",
- "2. Question #2\n",
- "- **Search** for similar wireframes online on what to base your feature off of, maybe similar to how tweets look\n",
- "- It will be auto generated by generating each announcement on top of each other with the most present at the top\n",
- "\n",
- "### My example\n",
- "\n",
- " \n",
- "\n",
- "| ID | Author | Title | Body | Timestamp | Tags |\n",
- "| -- | ------ | ----- | ---- | --------- | ---- |\n",
- "| | | | | | |\n",
- "\n",
- "\n",
- " \n",
- "\n",
- "## My thoughts, why you should do this\n",
- "> My thoughts on the matter\n",
- "- The problem with fullstack development is no doubt the barrier entry in terms of knowledge that is needed\n",
- "- Knowing how to create API's with specific endpoints, or self generating javascript wireframes, it seems like an impossible tasks, much easier to do one or even none of what i listed\n",
- "- Through my experience in the Nighthawk CS route I found that most slackers in groups came from a place of self dismissal \"I can't do this\", \"Im never gonna understand this\"\n",
- "- My goal from these blog posts is to make this development as simple as can be, by taking you through these steps\n",
- "- Hopefully if you follow the steps of this notebook, you will be able to use this as a reference for the creation of your'e own features\n"
- ]
- }
- ],
- "metadata": {
- "language_info": {
- "name": "python"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/fullstack_java/2024-07-22-Fullstack-backend.ipynb b/_notebooks/CSA/fullstack_java/2024-07-22-Fullstack-backend.ipynb
deleted file mode 100644
index 5eb7d8c2..00000000
--- a/_notebooks/CSA/fullstack_java/2024-07-22-Fullstack-backend.ipynb
+++ /dev/null
@@ -1,294 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "layout: post\n",
- "title: Backend Fullstack Development\n",
- "description: Guide to the backend development of you're feature\n",
- "permalink: /fullstack/java/backend\n",
- "menu: nav/fullstack_java.html\n",
- "toc: true\n",
- "comments: true\n",
- "author: Finn Carpenter\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## How do API work?\n",
- "> Three main components\n",
- "1. Constructor.java (makes the data object), usually the name of feature + .java\n",
- "2. Controller file, how data in the table is received/changed through links \n",
- "3. JPA (Java Persistence API) file, for the creation of certain methods for the controller file\n",
- "\n",
- "### Why do we use API's\n",
- "> These are the two main reason behind why we use them in this class\n",
- "1. Stores Data that is independent of the computer/frontend (Security, Ease of Accesses)\n",
- "2. Enables lazier coding (the data used from the API can be used to auto-generate HTML)\n",
- "\n",
- "### Accessing API's using fetch\n",
- "> [Article](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)\n",
- "- They are accessed by fetching a specific URL in the fetch() method\n",
- "- This method allows us to send list of headers with information we want the API to know\n",
- " - GET, DELETE, POST, PUT (methods used in the controller file)\n",
- " - Body (sending json data)\n",
- " - CORS\n",
- " - Cookies\n",
- " - Content Type\n",
- " - [The rest of them](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers) (still very important things to know)\n",
- "\n",
- "\n",
- "\n",
- "## Step 1\n",
- "> File Management\n",
- "- Create your features folder name in `src/main/java/com/nighthawk/spring_portfolio/mvc` (for me it is announcement)\n",
- "- Locate the announcement folder, copy and rename to what your feature name is\n",
- "- Copy and rename file to your feature, make sure to match the class name with the file name, change any other appearances of the former files name\n",
- "\n",
- "## Step 2\n",
- "> Constructor File\n",
- "- Change Announcement.java to your features name\n",
- "- Rename each instance of the word **Announcement** to your feature's name use ctrl+f\n",
- "\n",
- "### Step 2.1\n",
- "> Column Variables\n",
- "- There are a few variables at the beginning of the class\n",
- "- Keep ID, but change to what your feature needs on the other variables\n",
- "\n",
- " \n",
- "\n",
- "```java\n",
- " @Id\n",
- " @GeneratedValue(strategy = GenerationType.AUTO)\n",
- " private Long id;\n",
- "\n",
- " @Column(unique=false)\n",
- " //These variables\n",
- " private String author;\n",
- " private String title;\n",
- " private String body;\n",
- " private String timestamp;\n",
- " private String tags;\n",
- "```\n",
- "\n",
- "### Step 2.2\n",
- "> Constructor Method\n",
- "- This is the method that creates the objects that store your data\n",
- "- Create something similar to this but with your variables\n",
- "- You are passing through data for each column\n",
- "\n",
- " \n",
- "\n",
- "```java\n",
- " // Constructor with necessary fields\n",
- " public Announcement(String author, String title, String body, String tags) {\n",
- " this.author = author;\n",
- " this.title = title;\n",
- " this.body = body;\n",
- " this.tags = tags;\n",
- " }\n",
- "```\n",
- "\n",
- "### Step 2.3\n",
- "> Init Method + Initial Data\n",
- "- The innit method is ran at the beginning of the backend\n",
- "- The method is what populates your table with data\n",
- "- I only have it returning the data from init\n",
- "- Why have two methods?\n",
- " - if you need to manipulate the array more you can\n",
- " - other processes need to run before your for your API\n",
- " - nicer to look at too, abstraction helps readability \n",
- "\n",
- " \n",
- "\n",
- "```java\n",
- " // Static method to create initial data\n",
- " public static List createInitialData() {\n",
- " List announcements = new ArrayList<>();\n",
- "\n",
- " // Create announcements with formatted timestamp\n",
- " announcements.add(new Announcement(\"Finn\", \"Test of innit\", \"Don't mind this message\", \"welcome\"));\n",
- "\n",
- " return announcements;\n",
- " }\n",
- "\n",
- " // Static method to initialize the data\n",
- " public static List init() {\n",
- " return createInitialData();\n",
- " }\n",
- "```\n",
- "\n",
- "## Step 3\n",
- "> JPA file\n",
- "- JPA stands for Java Persistence API\n",
- "- This file helps with specif query methods of your database\n",
- "- For example if you wanted to create method for getting posts only based on an author, this file creates them\n",
- "\n",
- "\n",
- "### Step 3.1\n",
- "> Copy + Paste\n",
- "- Replace the names with your project and data type names\n",
- "- Super simple just use the same method name formatting \n",
- "- The compiler will make the methods for you\n",
- "- This code segment is you're whole file\n",
- "\n",
- " \n",
- "\n",
- "```java\n",
- "package com.nighthawk.spring_portfolio.mvc.announcement;\n",
- "\n",
- "import org.springframework.data.jpa.repository.JpaRepository;\n",
- "import org.springframework.stereotype.Repository;\n",
- "import java.util.List; \n",
- "\n",
- "@Repository\n",
- "public interface AnnouncementJPA extends JpaRepository {\n",
- " Announcement findByAuthor(String author); // Method to find announcement by author\n",
- "\n",
- " List findByTags(String tags); // Example method to find announcements by tags\n",
- "\n",
- " Announcement findByTitle(String title); // Example method to find announcements by title\n",
- "\n",
- " List findAllByOrderByTimestampDesc();\n",
- "}\n",
- "\n",
- "```\n",
- "\n",
- "\n",
- "\n",
- "## Step 4\n",
- "> Controller File\n",
- "- Use the announcement controller file, copy and rename all parts to your API's name similar to the first step\n",
- "- This file is how you will manipulate your data from outside the local system\n",
- "- This is done through [fetching](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) different URLs with data embedded in the HTTP request\n",
- "- Each controller file should have a base path that is different from the rest of the other API's\n",
- "- Looking above the class you should see this \n",
- "\n",
- " \n",
- "\n",
- "```java\n",
- "@RestController\n",
- "@RequestMapping(\"/api/announcements\")\n",
- "```\n",
- "\n",
- "### Step 4.1\n",
- "> Basic Methods (do not copy use as example)\n",
- "- All we are doing is just assigning certain methods to URLs, that will do CRUD processes\n",
- "- CRUD stands for Create Read Update Delete, and you want each kind \n",
- "- Create -> POST, Read -> GET, Update -> PUT, Delete -> DELETE\n",
- "- Use CHATGPT to help with creation\n",
- "\n",
- " \n",
- "\n",
- "```java\n",
- " // Create Example\n",
- " @PostMapping(\"/create\") \n",
- " public ResponseEntity createAnnouncement( @RequestParam String author, @RequestParam String title, @RequestParam String body, @RequestParam String tags) {\n",
- " \n",
- " Announcement newAnnouncement = new Announcement(author, title, body, tags);\n",
- " Announcement savedAnnouncement = announcementRepo.save(newAnnouncement);\n",
- " \n",
- " return new ResponseEntity<>(savedAnnouncement, HttpStatus.CREATED);\n",
- " }\n",
- "\n",
- " // Read Example\n",
- " @GetMapping \n",
- " public ResponseEntity> getAllAnnouncements() {\n",
- " List announcements = announcementRepo.findAll();\n",
- " return new ResponseEntity<>(announcements, HttpStatus.OK);\n",
- " }\n",
- "\n",
- " // Update Example\n",
- " @PutMapping(\"/edit/{title}\")\n",
- " public ResponseEntity editAnnouncement(@PathVariable String title, @RequestBody String body) {\n",
- " Announcement announcement = announcementRepo.findByTitle(title);\n",
- " announcement.setBody(body);\n",
- " announcementRepo.save(announcement);\n",
- " return new ResponseEntity<>(announcement, HttpStatus.OK);\n",
- " }\n",
- "\n",
- " // Delete Example\n",
- " @DeleteMapping(\"/{id}\")\n",
- " public ResponseEntity deleteAnnouncement(@PathVariable Long id) {\n",
- " try {\n",
- " announcementRepo.deleteById(id);\n",
- " return new ResponseEntity<>(HttpStatus.NO_CONTENT);\n",
- " } catch (Exception e) {\n",
- " return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);\n",
- " }\n",
- " }\n",
- "```\n",
- "\n",
- "### Detailed Breakdown\n",
- "> What each part of the controller means and does\n",
- "- Breaking down the update method\n",
- "\n",
- " \n",
- "\n",
- "```java\n",
- " // What each part of the method does\n",
- " // Response Entity is used instead because they can send extra data upon the request back\n",
- " //\n",
- "\n",
- " //Determines the Mapping POST GET PUT DELETE \n",
- " @PutMapping(\"/edit/{title}\")\n",
- " public ResponseEntity editAnnouncement(@PathVariable String title, @RequestBody String body)\n",
- " // Data Type Returned Parameters needed for the method\n",
- " {\n",
- " // Getting the announcement from the database\n",
- " Announcement announcement = announcementRepo.findByTitle(title);\n",
- " //Setting the new information into the announcement\n",
- " announcement.setBody(body);\n",
- " //Saving into the database\n",
- " announcementRepo.save(announcement);\n",
- " // Returning the announcement, and the HTTP status, whether it worked or not\n",
- " return new ResponseEntity<>(announcement, HttpStatus.OK);\n",
- " }\n",
- "```\n",
- "\n",
- "### Step 4.2\n",
- "> Custom methods using JPA\n",
- "- Sometimes you want to create specific query methods for your \n",
- "- Example of fetching by author and tags\n",
- "- The methods findByAuthor(), and findByTags() are made by the JPA not me\n",
- "\n",
- " \n",
- "\n",
- "```java\n",
- "@GetMapping(\"/author/{author}\")\n",
- " public ResponseEntity getAnnouncementByAuthor(@PathVariable String author) {\n",
- " Announcement announcement = announcementRepo.findByAuthor(author);\n",
- " if (announcement != null) {\n",
- " return new ResponseEntity<>(announcement, HttpStatus.OK);\n",
- " } else {\n",
- " return new ResponseEntity<>(HttpStatus.NOT_FOUND);\n",
- " }\n",
- " }\n",
- "\n",
- "@GetMapping(\"/tags/{tags}\")\n",
- "public ResponseEntity> getAnnouncementsByTags(@PathVariable String tags) {\n",
- " List announcements = announcementRepo.findByTags(tags);\n",
- " return new ResponseEntity<>(announcements, HttpStatus.OK);\n",
- "}\n",
- "```\n",
- "\n",
- "## Further Questions\n",
- "> Please use the comments below to suggest things to be added\n",
- "- Come to office hours if further help is needed\n",
- "- So we may add to this notebook\n"
- ]
- }
- ],
- "metadata": {
- "language_info": {
- "name": "python"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/fullstack_java/2024-07-22-Fullstack-design.ipynb b/_notebooks/CSA/fullstack_java/2024-07-22-Fullstack-design.ipynb
deleted file mode 100644
index b7b11496..00000000
--- a/_notebooks/CSA/fullstack_java/2024-07-22-Fullstack-design.ipynb
+++ /dev/null
@@ -1,65 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "title: Design a Fullstack Feature\n",
- "description: Starting the project with brainstorming and visualizing of features is an important step in the development process. This article will introduce you through the design process of a fullstack feature. \n",
- "permalink: /fullstack/java/design\n",
- "menu: nav/fullstack_java.html\n",
- "toc: true\n",
- "comments: true\n",
- "author: Finn Carpenter\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Designing a Full Stack Feature \n",
- "There are a few ways people typically get started with designing a Full Stack application. In a team setting, having an idea and dividing the design into layers helps get everyone on the same page. This process, best tackled collaboratively, allows for flexibility and creativity in implementation, encouraging students to explore various tools and methodologies. This process is best approached as a back-and-forth dialogue between designers of UI, API enpoints, and Database.\n",
- "\n",
- "### Frontend View Layer, UI\n",
- "Often called User Interface Design or User Experience, this involves visualizing what your frontend will look like and how a user completes a task. A successful visualization design features interactive screens that not only guide users through their tasks but also incorporate thoughtful style elements and themes. \n",
- "\n",
- "### Backend Control Layer, API endpoints\n",
- "An interface design, known as an Application Programming Interface (API), contains endpoints. Each API endpoint describes how frontend requests will be answered by backend responses, providing the connections between presentation and model. To get started, a designer typically begins by defining the basic Create, Read, Update, and Delete (CRUD) API endpoints.\n",
- "\n",
- "### Backend Model Layer, Database\n",
- "Modeling data and creating a database in the Java language often starts by designing Plain Old Java Objects (POJOs). These can initially be defined using a Unified Modeling Language (UML) diagramming tool (e.g., Draw.io). The key concept is to design your data and data relationships, then write your Java POJOs. "
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "--- This Document should continue with example designs using User database examples ---"
- ]
- }
- ],
- "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": "17.0.11+0"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/fullstack_java/2024-07-22-Fullstack-example.ipynb b/_notebooks/CSA/fullstack_java/2024-07-22-Fullstack-example.ipynb
deleted file mode 100644
index e89d1c08..00000000
--- a/_notebooks/CSA/fullstack_java/2024-07-22-Fullstack-example.ipynb
+++ /dev/null
@@ -1,264 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "layout: post\n",
- "title: Example Fullstack Feature\n",
- "description: Guide to the backend development of you're feature\n",
- "permalink: /fullstack/java/example\n",
- "menu: nav/fullstack_java.html\n",
- "toc: true\n",
- "comments: true\n",
- "author: Finn Carpenter\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## CRUD Table\n",
- "> Must use local backend to test\n",
- "\n",
- "\n",
- "\n",
- " \n",
- " Create \n",
- " Read \n",
- " Update \n",
- " Delete \n",
- " \n",
- " \n",
- "\n",
- " \n",
- " Create \n",
- " Read \n",
- " Update \n",
- " Delete \n",
- " \n",
- " \n",
- "
\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Announcements\n",
- "\n",
- "
\n",
- "\n",
- "\n",
- "\n",
- "\n"
- ]
- }
- ],
- "metadata": {
- "language_info": {
- "name": "python"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/fullstack_java/2024-07-22-Fullstack-frontend.ipynb b/_notebooks/CSA/fullstack_java/2024-07-22-Fullstack-frontend.ipynb
deleted file mode 100644
index a5f15a93..00000000
--- a/_notebooks/CSA/fullstack_java/2024-07-22-Fullstack-frontend.ipynb
+++ /dev/null
@@ -1,469 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {},
- "source": [
- "---\n",
- "layout: post\n",
- "title: Frontend Fullstack Development\n",
- "description: Guide to the backend development of you're feature\n",
- "permalink: /fullstack/java/frontend\n",
- "menu: nav/fullstack_java.html\n",
- "toc: true\n",
- "comments: true\n",
- "author: Finn Carpenter\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Your projects work for you\n",
- "> Don't be a static coder\n",
- "- When it comes to frontend you want to put in the least amount of work into it\n",
- "- While it creates most of HTML for you\n",
- "- Why? You're feature will be changing all time from outside data, so if it's hard coded you will have to change it by hand\n",
- "- So instead of changing all the time, use auto generation\n",
- "\n",
- "## What code should be static?\n",
- "> only exceptions to that rule above\n",
- "- Things that should be static are the things that will never change\n",
- "- Quick Reference: Side Bar, Sub Menu, Help Information, The DIVs that will be filled by you're data"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## How do I begin with Frontend?\n",
- "> Where to start\n",
- "- Start with a sketch, or reference\n",
- "- For my project I chose to reference [Twitter's Tweet](https://www.ledgerinsights.com/wp-content/uploads/2021/03/first-tweet-810x476.jpg)\n",
- "- If you don't know how a certain element is made ask CHAT GPT, I had to for how to format the timestamp\n",
- "- From this I was able to get the this as bare bones\n",
- "\n",
- " \n",
- "\n",
- "```HTML\n",
- "\n",
- "
\n",
- " \n",
- "
Hey whats up
\n",
- "
\n",
- " first \n",
- "
\n",
- "
\n",
- "
\n",
- "```\n",
- "\n",
- "## Result\n",
- "\n",
- "\n",
- "\n",
- "
\n",
- " \n",
- "
Hey whats up
\n",
- "
\n",
- " first \n",
- "
\n",
- "
\n",
- "
\n",
- "\n",
- "\n",
- "## HTML Auto-Generation\n",
- "> Coding less == more\n",
- "- Your aim for projects is to make the least amount of static HTML in your projects\n",
- "- 75% of your feature should be created using data fetched from API's\n",
- "- To show you a example, I show you all the code behind displaying my announcements\n",
- "- What does the announcement variable look like?\n",
- "\n",
- " "
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "javascript"
- }
- },
- "outputs": [],
- "source": [
- "var announcement = `\n",
- " \n",
- " \n",
- "
${body}
\n",
- "
\n",
- " ${tagElements} \n",
- "
\n",
- "
\n",
- "`;"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## JS Auto-Generation method\n",
- "- Create a method that puts data from an object inside that html\n",
- "- This method is custom to every feature\n",
- "- The message data is meant to replicate a GET response\n",
- "\n",
- " "
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 2,
- "metadata": {
- "vscode": {
- "languageId": "html"
- }
- },
- "outputs": [
- {
- "data": {
- "text/html": [
- "\n",
- "\n",
- "Will only show in notebook
\n"
- ],
- "text/plain": [
- ""
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- }
- ],
- "source": [
- "%%html\n",
- "\n",
- "\n",
- "Will only show in notebook
"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## How to Fetch\n",
- "> Replacing message var with a fetch\n",
- "- What is this codeblock mean?\n",
- "- This fetch is getting all the message objects from the database\n",
- "- we have to first parse through the object array, getting specific objects in order\n",
- "- then we are parse the object attributes and create the element with that data\n",
- "\n",
- " \n",
- "\n",
- "```javascript\n",
- "function generateAnnouncements() {\n",
- " var location = document.getElementById(\"read\");\n",
- " location.innerHTML = \"\"; // Clear the contents of the announcements div\n",
- " var myHeaders = new Headers();\n",
- " myHeaders.append(\"Content-Type\", \"application/json\");\n",
- "\n",
- " var requestOptions = {\n",
- " method: 'GET',\n",
- " headers: myHeaders,\n",
- " credentials: 'include',\n",
- " redirect: 'follow'\n",
- " };\n",
- " \n",
- " fetch(\"http://localhost:8085/api/announcements\", requestOptions)\n",
- " .then(response => response.json())\n",
- " .then(result => {\n",
- " result.reverse(); // Reverse the order of announcements\n",
- " console.log(result);\n",
- " for (let i = 0; i < result.length; i++) { // Change to '<'\n",
- " var message = result[i];\n",
- " createAnnouncement(message.title, message.author, message.tags, message.timestamp, message.body);\n",
- " }\n",
- " })\n",
- " .catch(error => console.log('error', error));\n",
- "}\n",
- "```"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Menu creation\n",
- "> Create menu\n",
- "- Will obviously be different for different features\n",
- "- I prompted the user for the creation, and depending on how you make your endpoint the sending of data might be different\n",
- "- Another option, use input elements in html that the user fills out instead of prompt\n",
- "\n",
- " \n",
- "\n",
- "```JS\n",
- "function createReq() {\n",
- " const author = prompt(\"Enter the author's name:\");\n",
- " const body = prompt(\"Enter the body of the announcement:\");\n",
- " const tags = prompt(\"Enter the tags for the announcement (comma separated):\");\n",
- " const title = prompt(\"Enter the title of the announcement:\");\n",
- "\n",
- " if (author && body && tags && title) {\n",
- " const url = `http://localhost:8085/api/announcements/create?author=${encodeURIComponent(author)}&body=${encodeURIComponent(body)}&tags=${encodeURIComponent(tags)}&title=${encodeURIComponent(title)}`;\n",
- "\n",
- " fetch(url, {\n",
- " method: 'POST',\n",
- " headers: {\n",
- " 'Content-Type': 'application/json'\n",
- " }\n",
- " })\n",
- " .then(response => response.json())\n",
- " .then(data => {\n",
- " console.log('Announcement created:', data);\n",
- " alert('Announcement created successfully!');\n",
- " })\n",
- " .catch(error => {\n",
- " console.error('Error creating announcement:', error);\n",
- " alert('Failed to create announcement.');\n",
- " });\n",
- " } else {\n",
- " alert('All fields are required!');\n",
- " }\n",
- "}\n",
- "```\n",
- "\n",
- "## Same thing with input fields instead\n",
- "\n",
- " \n",
- "\n",
- "### HTML that corresponds\n",
- "\n",
- "```HTML\n",
- " Author: \n",
- " Body: \n",
- " Tags: \n",
- " Title: \n",
- "```\n",
- "\n",
- " \n",
- "\n",
- "## New JS\n",
- "\n",
- "```JS\n",
- "function createReq() {\n",
- " const author = document.getElementByID(\"author\");\n",
- " const body = document.getElementByID(\"body\");\n",
- " const tags = document.getElementByID(\"tags\");\n",
- " const title = document.getElementByID(\"title\");\n",
- "\n",
- " if (author && body && tags && title) {\n",
- " const url = `http://localhost:8085/api/announcements/create?author=${encodeURIComponent(author)}&body=${encodeURIComponent(body)}&tags=${encodeURIComponent(tags)}&title=${encodeURIComponent(title)}`;\n",
- "\n",
- " fetch(url, {\n",
- " method: 'POST',\n",
- " headers: {\n",
- " 'Content-Type': 'application/json'\n",
- " }\n",
- " })\n",
- " .then(response => response.json())\n",
- " .then(data => {\n",
- " console.log('Announcement created:', data);\n",
- " alert('Announcement created successfully!');\n",
- " })\n",
- " .catch(error => {\n",
- " console.error('Error creating announcement:', error);\n",
- " alert('Failed to create announcement.');\n",
- " });\n",
- " } else {\n",
- " alert('All fields are required!');\n",
- " }\n",
- "}\n",
- "```\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Hacks\n",
- "> You can do this with the knowledge you just learned\n",
- "- Make Update Method interface for your feature\n",
- "- Make Delete Method interface for your feature"
- ]
- }
- ],
- "metadata": {
- "kernelspec": {
- "display_name": "Python 3",
- "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.8.10"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/spring_boot/2023-10-14-java-spring-anatomy.ipynb b/_notebooks/CSA/spring_boot/2023-10-14-java-spring-anatomy.ipynb
deleted file mode 100644
index 825e27e7..00000000
--- a/_notebooks/CSA/spring_boot/2023-10-14-java-spring-anatomy.ipynb
+++ /dev/null
@@ -1,348 +0,0 @@
-{
- "cells": [
- {
- "attachments": {},
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "title: Anatomy of a Spring Boot Project\n",
- "description: A discussion of key elements in a Java Spring Boot backend project. This includes preparing a project for deployment.\n",
- "categories: [Java Spring]\n",
- "permalink: /java/spring/anatomy\n",
- "menu: nav/java_spring.html\n",
- "courses: { csa: {week: 3} }\n",
- "type: ccc\n",
- "---"
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Highlights of a Spring Web Application\n",
- "This article introduces key considerations in setting up a Java Spring Backend project."
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Overview of files for Spring / Maven / Thymeleaf\n",
- "> Prepare for this review by completing Tools Setup and README instruction to clone and buid.\n",
- "\n",
- "- `README.md`: This file contains instructions and information about the project. It is a standard component of all properly set up GitHub projects.\n",
- "\n",
- "- `pom.xml`: This file is the Maven Project Object Model (POM) file. It defines the project configuration, dependencies, build settings, and other metadata required for building and managing the Java project.\n",
- "\n",
- "- `src/main/java/`: This directory contains your Java source code files, including controllers, services, models, and other backend components of your Spring application.\n",
- "\n",
- "- `src/main/resources/static/`: This directory is the location for static web resources such as CSS, JavaScript, images, and other assets that will be served directly by the web server without any processing.\n",
- "\n",
- "- `src/main/resources/templates/`: This directory contains Thymeleaf template files. These are dynamic HTML templates that can be rendered on the server-side and populated with data from your Java code. Thymeleaf provides powerful templating features and allows you to create dynamic web pages with Java integration.\n",
- "\n",
- "- `application.properties` or `application.yml`: These files contain configuration properties for the Spring application. They can include settings related to the database connection, server port, logging, security, and other application-specific configurations.\n",
- "\n",
- "- `Main.java`: This Java file contains the main entry point of the Spring application. It is annotated with @SpringBootApplication and includes the main method to start the application.\n",
- "\n",
- "- `SecurityConfiguration.java`: This Java file is a Java class that typically plays a crucial role in configuring the security aspects of a web application using Spring Security framework. It is responsible for defining security rules, authentication mechanisms, authorization policies, and other security-related configurations.\n",
- "\n",
- "- `...ApiController.java`: These Java files define the web controllers responsible for handling incoming requests and generating appropriate responses. They typically use annotations like @RestController or @Controller to define the request mapping endpoints.\n",
- "\n",
- "- `...ServiceImpl.java`: These Java files contain the business logic of the application. They encapsulate complex operations and provide services to the controllers. Service classes are often annotated with @Service.\n",
- "\n",
- "- `...JpaRepository.java`: These Java files define the data access layer of the application. They interact with the database or other data sources to perform CRUD operations.\n",
- "\n",
- "Please note that this is a general overview, and the specific file and directory structure can vary as any project progresses or the framework change."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Main.java\n",
- "Entry point for Java Spring Application\n",
- "\n",
- "```java\n",
- "@SpringBootApplication\n",
- "public class Main {\n",
- "\n",
- " // Starts a spring application as a stand-alone application from the main method\n",
- " public static void main(String[] args) {\n",
- " SpringApplication.run(Main.class, args);\n",
- " }\n",
- "\n",
- "}\n",
- "```"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### application.properties\n",
- "Key properties like server.port, secret keys, and database connections are listed in this file. "
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "shellscript"
- }
- },
- "outputs": [],
- "source": [
- "server.error.whitelabel.enabled=false\n",
- "spring.devtools.add-properties=false\n",
- "logging.level.root=warn\n",
- "\n",
- "spring.jpa.database-platform=com.nighthawk.spring_portfolio.SQLDialect\n",
- "spring.jpa.hibernate.ddl-auto=update\n",
- "spring.jpa.show-sql=false\n",
- "spring.jpa.properties.hibernate.format_sql=false\n",
- "spring.jpa.open-in-view=false\n",
- "spring.datasource.url = jdbc:sqlite:volumes/sqlite.db\n",
- "spring.datasource.driver-class-name = org.sqlite.JDBC\n",
- "spring.datasource.username = admin\n",
- "spring.datasource.password = admin\n",
- "\n",
- "server.port=8085\n",
- "\n",
- "jwt.secret=nighthawk"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### pom.xml\n",
- "All the modules included into the project are listed in this file. Here you can see some of the dependencies added to make the Java project into Spring Web Application. As you add features or frameworks you will add to this file.\n",
- "\n",
- "```pom\n",
- "\n",
- " \n",
- " \n",
- " org.springframework.boot \n",
- " spring-boot-starter-validation \n",
- " \n",
- " \n",
- " org.springframework.boot \n",
- " spring-boot-starter-thymeleaf \n",
- " \n",
- " \n",
- " org.springframework.boot \n",
- " spring-boot-starter-web \n",
- " \n",
- " \n",
- " org.springframework.boot \n",
- " spring-boot-starter-security \n",
- " \n",
- " \n",
- " org.springframework.boot \n",
- " spring-boot-devtools \n",
- " runtime \n",
- " true \n",
- " \n",
- " \n",
- " org.springframework.boot \n",
- " spring-boot-starter-test \n",
- " test \n",
- " \n",
- " \n",
- " org.thymeleaf \n",
- " thymeleaf-spring5 \n",
- " \n",
- " ${org.thymeleaf-version} \n",
- " \n",
- " \n",
- " org.thymeleaf.extras \n",
- " thymeleaf-extras-springsecurity4 \n",
- " \n",
- " ${org.thymeleaf.extras.springsecurity4-version} \n",
- " \n",
- " ...\n",
- " \n",
- "```"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### PersonApiController.java\n",
- "Build APIs requires a lot of [annotations](https://www.geeksforgeeks.org/annotations-in-java/#). This controller in Module View Control (MVC) establish mechanism to receive and respond to API requests.\n",
- "\n",
- "```java\n",
- "@RestController\n",
- "@RequestMapping(\"/api/person\")\n",
- "public class PersonApiController {\n",
- " // @Autowired\n",
- " // private JwtTokenUtil jwtGen;\n",
- " /*\n",
- " #### RESTful API ####\n",
- " Resource: https://spring.io/guides/gs/rest-service/\n",
- " */\n",
- "\n",
- " // Autowired enables Control to connect POJO Object through JPA\n",
- " @Autowired\n",
- " private PersonJpaRepository repository;\n",
- "\n",
- " /*\n",
- " GET List of People\n",
- " */\n",
- " @GetMapping(\"/\")\n",
- " public ResponseEntity> getPeople() {\n",
- " return new ResponseEntity<>( repository.findAllByOrderByNameAsc(), HttpStatus.OK);\n",
- " }\n",
- "\n",
- " /*\n",
- " GET individual Person using ID\n",
- " */\n",
- " @GetMapping(\"/{id}\")\n",
- " public ResponseEntity getPerson(@PathVariable long id) {\n",
- " Optional optional = repository.findById(id);\n",
- " if (optional.isPresent()) { // Good ID\n",
- " Person person = optional.get(); // value from findByID\n",
- " return new ResponseEntity<>(person, HttpStatus.OK); // OK HTTP response: status code, headers, and body\n",
- " }\n",
- " // Bad ID\n",
- " return new ResponseEntity<>(HttpStatus.BAD_REQUEST); \n",
- " }\n",
- "\n",
- " /*\n",
- " DELETE individual Person using ID\n",
- " */\n",
- " @DeleteMapping(\"/delete/{id}\")\n",
- " public ResponseEntity deletePerson(@PathVariable long id) {\n",
- " Optional optional = repository.findById(id);\n",
- " if (optional.isPresent()) { // Good ID\n",
- " Person person = optional.get(); // value from findByID\n",
- " repository.deleteById(id); // value from findByID\n",
- " return new ResponseEntity<>(person, HttpStatus.OK); // OK HTTP response: status code, headers, and body\n",
- " }\n",
- " // Bad ID\n",
- " return new ResponseEntity<>(HttpStatus.BAD_REQUEST); \n",
- " }\n",
- "\n",
- " /*\n",
- " POST Aa record by Requesting Parameters from URI\n",
- " */\n",
- " @PostMapping( \"/post\")\n",
- " public ResponseEntity postPerson(@RequestParam String email,\n",
- " @RequestParam String password,\n",
- " @RequestParam String name,\n",
- " @RequestParam(\"dob\") String dobString) {\n",
- " Date dob;\n",
- " try {\n",
- " dob = new SimpleDateFormat(\"MM-dd-yyyy\").parse(dobString);\n",
- " } catch (Exception e) {\n",
- " return new ResponseEntity<>(dobString +\" error; try MM-dd-yyyy\", HttpStatus.BAD_REQUEST);\n",
- " }\n",
- " // A person object WITHOUT ID will create a new record with default roles as student\n",
- " Person person = new Person(email, password, name, dob);\n",
- " repository.save(person);\n",
- " return new ResponseEntity<>(email +\" is created successfully\", HttpStatus.CREATED);\n",
- " }\n",
- "\n",
- " // ... //\n",
- "\n",
- "}\n",
- "\n",
- "```"
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "\n",
- "## Deployment Files\n",
- "> In addition to Java / Spring. It is always a requirement to consider deployment. Be sure your docker files are created modifying the templates below to fit you needs."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "shellscript"
- }
- },
- "outputs": [],
- "source": [
- "# Dockerfile\n",
- "FROM openjdk:18-alpine3.13\n",
- "WORKDIR /app\n",
- "RUN apk update && apk upgrade && \\\n",
- " apk add --no-cache git \n",
- "COPY . /app\n",
- "RUN ./mvnw package\n",
- "CMD [\"java\", \"-jar\", \"target/spring-0.0.1-SNAPSHOT.jar\"]\n",
- "EXPOSE 8085"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "shellscript"
- }
- },
- "outputs": [],
- "source": [
- "# docker-compose.yml\n",
- "version: '3'\n",
- "services:\n",
- " web:\n",
- " image: java_springv1 # Change the image name to something unique to your project, aka my_unique_name_v1\n",
- " build: .\n",
- " ports:\n",
- " - \"8---:8085\" # Edit the number on the left to match the port you selected \n",
- " volumes:\n",
- " - ./volumes:/volumes\n",
- " restart: unless-stopped"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# Hacks\n",
- "Start your own Spring Project: https://github.com/nighthawkcoders/spring_2025"
- ]
- }
- ],
- "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/CSA/spring_boot/2023-10-15-java-spring-intro.ipynb b/_notebooks/CSA/spring_boot/2023-10-15-java-spring-intro.ipynb
deleted file mode 100644
index e1ef4e61..00000000
--- a/_notebooks/CSA/spring_boot/2023-10-15-java-spring-intro.ipynb
+++ /dev/null
@@ -1,89 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post \n",
- "title: Introduction Java Spring Framework\n",
- "description: Introduction to API, JPA, ORM, POJOs in Java Spring Framework\n",
- "categories: [Spring]\n",
- "permalink: /java/spring/intro/\n",
- "menu: nav/java_spring.html\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Introduction\n",
- "\n",
- "APIs build programmatic interactions between applications, people, and businesses. They are designed around sharing data and executing pre-defined processes. Spring Boot and Spring Data JPA reduce time for development; developers implement POJOs and JPA access layers; Spring hanldes the rest. \n",
- "\n",
- "An API allows you to request and receive data from the system. A POJO is the foundation for making an Entity that is turned into a Database. The Java Persistent API (JPA) allows the database to be queried and updated. \n",
- "\n",
- "The subject of this article is Jokes, likes (haha) and dislike (boohoo). User clicks haha or boohoo and updates counters.\n",
- "\n",
- "[Runtime](https://nighthawkcoders.github.io/portfolio_2025/java/spring/jokes)\n",
- "\n",
- "[Back-end Java Spring Files](https://github.com/nighthawkcoders/spring_2025/tree/master/src/main/java/com/nighthawk/spring_portfolio/mvc/jokes)\n",
- "- Jokes.java - contains POJO which defines Model\n",
- "- JokesApiControler.java - contains APIs and Control, which respond to View actions\n",
- "- JokesJpaRepository.java - contains CRUD and data acess queries\n",
- "\n",
- "### Visual Overview\n",
- "\n",
- "```\n",
- " Spring API and ORM\n",
- " ------------------\n",
- " +-------------------+\n",
- " | API Controller |-- Developer defines Request Mappings\n",
- " | Request |----- @PathVariable are received\n",
- " | JPA call |----- @Autowired method is called\n",
- " | Respone |----- ResponseEntity<> wraps data from JPA (ie JSON)\n",
- " +-------------------+\n",
- " |\n",
- " | JPA Methods\n",
- " v\n",
- " +-----------------+\n",
- " | JPA |-- Developer defines Database Queries\n",
- " | Java | ----- a.) JPA built in (long names)\n",
- " | Persistent | ----- b.) SQL native queries\n",
- " | API | \n",
- " +-----------------+\n",
- " |\n",
- " | Database Access Methods\n",
- " v\n",
- " +-----------------+\n",
- " | ORM | -- Spring layers supporting Database Framework\n",
- " | Object | ----- Behind the scene managing tables\n",
- " | Relational | ----- Behind the scene database construction\n",
- " | Model |\n",
- " +-----------------+\n",
- " |\n",
- " | Entities Definition\n",
- " v\n",
- " +-----------------+\n",
- " | Database/POJOs | -- Developer defines each Class\n",
- " | Plain | ----- Define attributes in Table\n",
- " | Old Java | ----- Define relationships in Database\n",
- " | Objects | \n",
- " +-----------------+\n",
- "```"
- ]
- }
- ],
- "metadata": {
- "language_info": {
- "name": "python"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/spring_boot/2023-10-16-java-spring-ui.ipynb b/_notebooks/CSA/spring_boot/2023-10-16-java-spring-ui.ipynb
deleted file mode 100644
index 41401ed6..00000000
--- a/_notebooks/CSA/spring_boot/2023-10-16-java-spring-ui.ipynb
+++ /dev/null
@@ -1,196 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post \n",
- "title: Frontend UI\n",
- "description: Fetching data from the Spring Boot backend API \n",
- "permalink: /java/spring/ui/\n",
- "categories: [Java Spring]\n",
- "menu: nav/java_spring.html\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### JavaScript Frontend UI\n",
- "\n",
- "This frontend and backend project was setup to allow people to HaHa or Boohoo a collection of Computer Jokes.\n",
- "\n",
- "> Amazingly ... the front-end code is in a completely different GitHub repo than the backend code. The backend is deployed seperately.\n",
- "\n",
- "#### Future Hack Ideas\n",
- "\n",
- "This code has lot of limitation. \n",
- "\n",
- "- People can vote more than once and in both categories.\n",
- "- There is no auto refresh if several are voting and updating as you are looking at your static page.\n",
- "- Perhaps Q and A style could hide punch line.\n",
- "- Perhaps we could accept new jokes, or have interface for adding them.\n",
- "\n",
- "#### Frontend API Calls\n",
- "\n",
- "The code below updates the HTML elementID (like or jeer) using the latest data from the backend database.\n",
- "\n",
- "[Latest GitHub Code](hhttps://github.com/nighthawkcoders/portfolio_2025/blob/main/navigation/jokes.md)\n",
- "\n",
- "```html\n",
- "\n",
- "\n",
- " \n",
- " \n",
- " Joke \n",
- " HaHa \n",
- " Boohoo \n",
- " \n",
- " \n",
- " \n",
- " \n",
- " \n",
- "
\n",
- "\n",
- "\n",
- "```\n",
- "\n"
- ]
- }
- ],
- "metadata": {
- "language_info": {
- "name": "python"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/spring_boot/2023-10-17-java-spring-api.ipynb b/_notebooks/CSA/spring_boot/2023-10-17-java-spring-api.ipynb
deleted file mode 100644
index bdb3a0e3..00000000
--- a/_notebooks/CSA/spring_boot/2023-10-17-java-spring-api.ipynb
+++ /dev/null
@@ -1,162 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post \n",
- "title: API Controller\n",
- "description: Creating an API request and response to the Spring Boot application.\n",
- "permalink: /java/spring/api/\n",
- "categories: [Java Spring]\n",
- "menu: nav/java_spring.html\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## API Controller (JokesApiController)\n",
- "\n",
- "> This backend component of the Spring framework is responsible for building out the RESTful API services to access the data. Below is the `JokesApiController`, which is extensively commented to aid understanding.\n",
- "- **@Autowired**: This annotation provides full access to `JokesJpaRepository`.\n",
- "- **@GetMapping** and **@PutMapping**: These annotations enable endpoints for RESTful web services to access (accessor Get) and modify (mutator Put) the data.\n",
- "- **@PathVariable**: This annotation is used for obtaining information from the request URL.\n",
- "- **ResponseEntity**: Review the methods that return `ResponseEntity`, a Spring Framework implementation that encapsulates the entire HTTP response, including the status code, headers, and body. This allows for a more flexible and comprehensive way to handle HTTP responses according to RESTful API standards.\n",
- "- **Method Signatures**: Review the signatures of the methods to understand how the Java return type is converted to JSON using the `ResponseEntity` object. This conversion is handled by Spring's `HttpMessageConverter`, which automatically serializes the Java objects into JSON format for the HTTP response body.\n",
- "- **Generics**: A feature in Java that allows you to define classes, interfaces, and methods with a generic type ``. In the `JokesApiController`, we are consumers of a class definition with generics from `public class ResponseEntity`. This enables the return of a serialized instance of `ResponseEntity>` or `ResponseEntity` using specific types. "
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "### AP CSA Curriculum Comparisons\n",
- "\n",
- "- **Generics**: We are required to use and understand generic types in using `public class ArrayList`. This is similar to how we use `public class ResponseEntity` in the `JokesApiController`.\n",
- "- **Method Signatures**: The term signature is used in the curriculum to describe method definitions: `scope, return type, method name, parameters`. The signature is tightly coupled to the return type, which is important in understanding how methods like `getJokes()` and `setLike()` return `ResponseEntity` objects.\n",
- "- **Accessors and Mutators**: Making `accessors` and `mutators` in APIs reinforces the need to have backend services to perform `accessor` or `mutator` methods in Plain Old Java Objects (POJOs). JPA (Java Persistence API) enables us to inject those services into our POJO class definitions.\n",
- "- **List**: The `interface List` is the parent of the College Board required `class ArrayList implements List`. In the inheritance language, `List` is the interface definition and `ArrayList` is a specific implementation of `List` with enhancements and overrides. The `ArrayList` class adds features such as a resizable array, fast random access, and automatic memory management, constant time performance for get/set.\n",
- " - List Interface: Defines the methods that any list implementation must provide.\n",
- " - ArrayList Implementation: Provides constant-time performance for get and set operations due to its underlying array structure.\n",
- " - LinkedList Implementation: Provides linear-time performance for get and set operations due to its underlying doubly-linked list structure.\n",
- " - Vector Implementation: Synchronized, thread-safe implementation of a dynamic array. Provides similar functionality to `ArrayList` but with synchronization, meaning it can be safely accessed by multiple threads simultaneously. \n",
- " - Stack Implementation: Extends `Vector` and provides LIFO (last-in-first-out) stack operations."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "```java\n",
- "import org.springframework.beans.factory.annotation.Autowired;\n",
- "import org.springframework.http.HttpStatus;\n",
- "import org.springframework.http.ResponseEntity;\n",
- "import org.springframework.web.bind.annotation.*;\n",
- "\n",
- "import java.util.List;\n",
- "import java.util.Optional;\n",
- "\n",
- "@RestController // Annotation to simplify the creation of RESTful web services\n",
- "@RequestMapping(\"/api/jokes\") // All requests in this class begin with this URI\n",
- "public class JokesApiController {\n",
- "\n",
- " /**\n",
- " * @Autowired\n",
- " * This annotation allows Spring to automatically inject the JokesJpaRepository dependency.\n",
- " * The JokesJpaRepository is an interface, so the injected dependency means that Spring is automatically creating an instance of a class that implements this interface. This instance is then used to connect JPA methods to the POJO (Plain Old Java Object) class, enabling easy Database CRUD (Create, Read, Update, Delete) operations.\n",
- " */\n",
- " @Autowired\n",
- " private JokesJpaRepository repository;\n",
- "\n",
- " /**\n",
- " * GET List of Jokes\n",
- " * \n",
- " * @GetMapping annotation is used for mapping HTTP GET requests onto specific handler methods.\n",
- " * \n",
- " * @return ResponseEntity> - A ResponseEntity containing a list of Jokes objects and an HTTP status code.\n",
- " * The ResponseEntity encapsulates the entire HTTP response, including the status code, headers, and body.\n",
- " * The list of Jokes objects is serialized to JSON format for the HTTP response body.\n",
- " */\n",
- " @GetMapping(\"/\")\n",
- " public ResponseEntity> getJokes() {\n",
- " // ResponseEntity returns List of Jokes provided by JPA findAll()\n",
- " return new ResponseEntity<>(repository.findAll(), HttpStatus.OK);\n",
- " }\n",
- "\n",
- " /**\n",
- " * Update Like\n",
- " * \n",
- " * @PutMapping annotation is used for mapping HTTP PUT requests onto specific handler methods.\n",
- " * @PathVariable annotation extracts the templated part {id} from the URI.\n",
- " * \n",
- " * @param id The ID of the joke to be liked.\n",
- " * @return ResponseEntity - A ResponseEntity containing the updated Jokes object and an HTTP status code.\n",
- " * The ResponseEntity encapsulates the entire HTTP response, including the status code, headers, and body.\n",
- " * The Jokes object is serialized to JSON format for the HTTP response body.\n",
- " */\n",
- " @PutMapping(\"/like/{id}\")\n",
- " public ResponseEntity setLike(@PathVariable long id) {\n",
- " /* \n",
- " * Optional (below) is a container object which helps determine if a result is present. \n",
- " * If a value is present, isPresent() will return true\n",
- " * get() will return the value.\n",
- " */\n",
- " Optional optional = repository.findById(id);\n",
- " if (optional.isPresent()) { // Good ID\n",
- " Jokes joke = optional.get(); // Value from findByID\n",
- " joke.setHaha(joke.getHaha() + 1); // Increment value\n",
- " repository.save(joke); // Save entity\n",
- " return new ResponseEntity<>(joke, HttpStatus.OK); // OK HTTP response: status code, headers, and body\n",
- " }\n",
- " // Bad ID\n",
- " return new ResponseEntity<>(HttpStatus.BAD_REQUEST); // Failed HTTP response: status code, headers, and body\n",
- " }\n",
- "\n",
- " /* Update Jeer\n",
- " */\n",
- " @PutMapping(\"/jeer/{id}\")\n",
- " public ResponseEntity setJeer(@PathVariable long id) {\n",
- " Optional optional = repository.findById(id);\n",
- " if (optional.isPresent()) { // Good ID\n",
- " Jokes joke = optional.get();\n",
- " joke.setBoohoo(joke.getBoohoo() + 1);\n",
- " repository.save(joke);\n",
- " return new ResponseEntity<>(joke, HttpStatus.OK);\n",
- " }\n",
- " // Bad ID\n",
- " return new ResponseEntity<>(HttpStatus.BAD_REQUEST);\n",
- " }\n",
- "}\n",
- "```"
- ]
- }
- ],
- "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": "17.0.12+0"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/spring_boot/2023-10-17-java-spring-pojo.ipynb b/_notebooks/CSA/spring_boot/2023-10-17-java-spring-pojo.ipynb
deleted file mode 100644
index 71b4599b..00000000
--- a/_notebooks/CSA/spring_boot/2023-10-17-java-spring-pojo.ipynb
+++ /dev/null
@@ -1,61 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post \n",
- "title: Plain Old Java Objects (POJO) \n",
- "description: Define a POJO, essentially an class with @Entity properties that enables it to be used with Spring Boot in the process of making a database.\n",
- "permalink: /java/spring/pojo/\n",
- "categories: [Java Spring]\n",
- "menu: nav/java_spring.html\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### POJO Review\n",
- "\n",
- "> This code fragment shows power of Spring and Annotations to define a Model. Using Spring, a little bit of POJO code, the Developer is enabling persistent data storage of a table in a database. It is left to student to search up each annotation for personal clarification beyond the comments below.\n",
- "\n",
- "```java\n",
- "import lombok.AllArgsConstructor;\n",
- "import lombok.Data;\n",
- "import lombok.NoArgsConstructor;\n",
- "import javax.persistence.*;\n",
- "\n",
- "@Data // Annotations to simplify writing code (ie constructors, setters)\n",
- "@NoArgsConstructor // Builds zero argument constructor\n",
- "@AllArgsConstructor // Builds constructor for all agurments\n",
- "@Entity // Annotation to simplify creating an entity, which is a lightweight persistence domain object. Typically, an entity represents a table in a relational database, and each entity instance corresponds to a row in that table.\n",
- "public class Jokes {\n",
- " @Id\n",
- " @GeneratedValue(strategy = GenerationType.AUTO)\n",
- " private Long id; // Unique identifier\n",
- "\n",
- " @Column(unique=true)\n",
- " private String joke; // The Joke\n",
- "\n",
- " private int haha; // Store joke likes\n",
- " private int boohoo; // Store joke jeers\n",
- "}\n",
- "```"
- ]
- }
- ],
- "metadata": {
- "language_info": {
- "name": "python"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/spring_boot/2023-10-18-java-spring-jpa.ipynb b/_notebooks/CSA/spring_boot/2023-10-18-java-spring-jpa.ipynb
deleted file mode 100644
index 1efa8644..00000000
--- a/_notebooks/CSA/spring_boot/2023-10-18-java-spring-jpa.ipynb
+++ /dev/null
@@ -1,56 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post \n",
- "title: Java Persistent API (JPA)\n",
- "description: Define the JPA layer. The JPA enables frontend to query backend and returns a list.\n",
- "permalink: /java/spring/jpa/\n",
- "categories: [Java Spring]\n",
- "menu: nav/java_spring.html\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Java Persistence API (JPA)\n",
- "\n",
- "> The JPA code is defined to access the database. The JokesJpaRepository interface extends JpaRepository. This allows the developer access JPA predefined and developer custom interfaces to perform CRUD operations on persistent storage. It is left to student to define \"Delete\" operation in CRUD.\n",
- "\n",
- "```java\n",
- "import java.util.List;\n",
- "import org.springframework.data.jpa.repository.JpaRepository;\n",
- "\n",
- "// JPA is an object-relational mapping (ORM) to persistent data, originally relational databases (SQL). Today JPA implementations has been extended for NoSQL.\n",
- "public interface JokesJpaRepository extends JpaRepository {\n",
- " // JPA has many built in methods, these few have been prototyped for this application\n",
- " void save(String Joke); // used for Create, Update operations in CRUD\n",
- "\n",
- " // Accessors, Read operations in CRUD\n",
- " List findAllByOrderByJokeAsc(); // returns a List of Jokes in Ascending order\n",
- " List findByJokeIgnoreCase(String joke); // look to see if Joke(s) exist\n",
- "}\n",
- "```\n",
- "\n",
- "### JPA returns List\n",
- "> List is a super class to ArrayList. In the JPA code you can see that List of Jokes is common result from JPA accessor method. It is left to the student to review [List and ArrayList from GeeksForGeeks](https://www.geeksforgeeks.org/difference-between-list-and-arraylist-in-java/) and understand research difference between interface and implementation."
- ]
- }
- ],
- "metadata": {
- "language_info": {
- "name": "python"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/spring_boot/2023-10-22-java-spring-hacks.ipynb b/_notebooks/CSA/spring_boot/2023-10-22-java-spring-hacks.ipynb
deleted file mode 100644
index 93efec71..00000000
--- a/_notebooks/CSA/spring_boot/2023-10-22-java-spring-hacks.ipynb
+++ /dev/null
@@ -1,100 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post \n",
- "title: Java Spring Hacks \n",
- "description: A POJO is basis of the Spring framework, but also it is basis of Java and the AP CSA exam. \n",
- "permalink: /java/spring/hacks/\n",
- "categories: [Java Spring]\n",
- "menu: nav/java_spring.html\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Hacks\n",
- "Start work on your own personal blog, using this series as a template.\n",
- "\n",
- "### AP required. \n",
- "Review the lambok annotations (https://projectlombok.org/features/). \n",
- "\n",
- "- Write a POJO and show code generated code by lambok. \n",
- " - Name all the Object methods\n",
- " - Make a blog of this generated code in context of requirements for the AP exam at the end of Unit 9.\n",
- "\n",
- "### PBL foundational. \n",
- "\n",
- "Establish a POJO, JPA and APIs in your own repository. You can begin with Jokes and modify to your needs. \n",
- "\n",
- "This will be beginnings of and **ideation phase** for your Trimester 1 N@tM final project. Everyone at the table should have an idea and create a full stack project. \n",
- "\n",
- "- Integration of your ideation into common repository will be a different phase. This is personal ideation.\n",
- "- Consider this as your final individual PBL test and ideation project. We expect to be completely finished with this by Oct 21st.\n",
- "- Planning at table for collaboritive ideation is highly advised. This project need to be in your team N@tM final.\n",
- "- Scrum Master coordinating with teacher on building something useful for future Teaching is expected in N@tM final. If your project(s) gets pulled into nighthawk coders, you will get an 'A\"!\n",
- "\n",
- "#### Make a new POJO\n",
- "**Alert**, delete /volumes/sqlite.db each time you change schema. Schema changes are not ugraded automatically as you simply rebuild.\n",
- "\n",
- " - Come up with a simple idea to record data updates from User in SQL table\n",
- " - Validate creation of SQL table with SQLite Extension, aka SQLite3 Editor\n",
- " - Add to blog.\n",
- "\n",
- "### Make a new API endpoint\n",
- "An endpoint will require POJO, JPA, and REST controller. [Test your API using Postman](https://www.geeksforgeeks.org/basics-of-api-testing-using-postman/). You should be able to test with localhost:8085 using the spring project.\n",
- "\n",
- " - Build @RESTController\n",
- " - Build custom methods extending JPARepository\n",
- " - Save your Postman queries\n",
- " - Have queries for GET and PUT operations\n",
- " - Add to blog.\n",
- "\n",
- "### Make a new Frontend page\n",
- "The frontend page should be simple to test and should have minimal typing. Just clicking.\n",
- "\n",
- " - Use definitions like config.js to allow easy migration from frontend to backend\n",
- " - Be sure to have both Read and Put operations\n",
- " - Add to blog.\n",
- "\n",
- "\n",
- "### Resources, recommended by ChatGPT\n",
- "1. [Spring Framework Documentation](https://spring.io/projects/spring-framework)\n",
- " The official Spring Framework documentation is entirely free to access. It provides comprehensive information on various Spring modules, including Spring Boot and Spring Data JPA.\n",
- "\n",
- "2. [Baeldung Spring Boot Tutorials](https://www.baeldung.com/spring-boot)\n",
- " Baeldung: Baeldung offers a mix of free and paid content. While some articles may require a subscription, many tutorials and guides on Spring Boot and Spring Data JPA are available for free.\n",
- "\n",
- "3. [Baeldung Spring Boot Tutorials](https://www.baeldung.com/spring-boot)\n",
- " Spring Guides: The Spring Guides are completely free and provide step-by-step tutorials on various aspects of Spring development, including Spring Boot and Spring Data JPA.\n",
- "\n",
- "4. [Spring Guides](https://spring.io/guides)\n",
- "Java Brains YouTube Channel: The Java Brains YouTube channel offers free video tutorials on Java and Spring frameworks, including dedicated playlists for Spring Boot and Spring Data JPA.\n",
- "\n",
- "5 Java Brains YouTube Channe\n",
- " Spring Data JPA Reference Documentation: The Spring Data JPA reference documentation is freely available online and provides in-depth insights into Spring Data JPA features.\n",
- " - [Java Brains Spring Boot Playlist](https://www.youtube.com/playlist?list=PLqq-6Pq4lTTZSKAFG6aCDVDP86Qx4lNas)\n",
- " - [Java Brains Spring Data JPA Playlist](https://www.youtube.com/playlist?list=PLqq-6Pq4lTTZSKAFG6aCDVDP86Qx4lNas)\n",
- "\n",
- "[Spring Data JPA Reference Documentation](https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#reference)\n",
- " The Spring Data JPA reference documentation is freely available online and provides in-depth insights into Spring Data JPA features."
- ]
- }
- ],
- "metadata": {
- "language_info": {
- "name": "python"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/backup_summer_2024/2024-06-24-unit_2.ipynb b/_notebooks/CSA/units_1_to_10/backup_summer_2024/2024-06-24-unit_2.ipynb
deleted file mode 100644
index 9b77c0e6..00000000
--- a/_notebooks/CSA/units_1_to_10/backup_summer_2024/2024-06-24-unit_2.ipynb
+++ /dev/null
@@ -1,352 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "toc: true\n",
- "title: Unit 2 - Using Objects\n",
- "description: Using Objects\n",
- "authors: Aniket Chakradeo, Soham Kamat\n",
- "categories: [AP CSA]\n",
- "permalink: /unit2lesson\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Instances of Classes\n",
- "\n",
- "**Java** is an **object-oriented programming language**, focusing on the manipulation of **objects**. **Objects** are a **reference type**, meaning they combine **primitive** and **reference data types**. When referenced, it points to their storage location.\n",
- "\n",
- "The composition of each object is defined by a **class**, which acts as a template. A **class** outlines what an object is and what it can do, similar to a **blueprint** for a house. Each house (object) built from this blueprint (class) may vary in appearance but shares common features and functions."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Initializing Objects\n",
- "\n",
- "To create an **object**, we call the object's **constructor**. Every **class** must have a constructor; if you don't create one, a default empty constructor is provided. If a **class** is like a blueprint, the **constructor** is the architect bringing it to life. The **constructor** takes in parameters (e.g., name, age) and assigns specific values to create the object. \n",
- "\n",
- "Example:\n",
- "```java\n",
- "Car(String brand, String model, int year)\n",
- "Car flash = new Car(\"BMW\", \"X7\", 2023);\n",
- "```\n",
- "\n",
- "Creating an object is similar to creating a variable: start with the **type**, enter the object's **name**, and use the **equals sign** (assignment operator) to assign a value. Use the **new** keyword to create a new object. The order of parameters in the **constructor** matters; an **IllegalArgumentException** will arise if the order is incorrect. \n",
- "\n",
- "A **class** can have multiple **constructors** (overloading), differentiated by their parameters.\n",
- "\n",
- "The **null** keyword means no reference is created, and the object contains nothing:\n",
- "```java\n",
- "Car lightning = null;\n",
- "```\n",
- "Be cautious with **null** objects, as calling a method on them results in a **NullPointerException**."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Calling a Void Method\n",
- "\n",
- "A **method** consists of five main parts: **scope**, **return type**, **name**, **parameters**, and **body**. Here's an example:\n",
- "\n",
- "```java\n",
- "public void study(int hoursStudied) {\n",
- " totalHours += hoursStudied;\n",
- "}\n",
- "```\n",
- "\n",
- "1. **Scope**: `public` - Anyone can access this method.\n",
- "2. **Return type**: `void` - The method returns nothing.\n",
- "3. **Name**: `study` - Case-sensitive.\n",
- "4. **Parameters**: `int hoursStudied` - Requires an integer input.\n",
- "5. **Body**: `totalHours += hoursStudied;` - The method's action.\n",
- "\n",
- "This method can be called on an object:\n",
- "```java\n",
- "Person bob = new Person(\"bob\");\n",
- "bob.study(2);\n",
- "```\n",
- "In this snippet:\n",
- "- A new **Person** object named **bob** is created.\n",
- "- The `study` method is called on **bob** using **dot notation**.\n",
- "- `2` is passed as an argument, indicating bob studied for 2 hours."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Calling a Void Method with Parameters\n",
- "\n",
- "**Methods**, like constructors, can be **overloaded**, meaning each method has a different parameter list.\n",
- "\n",
- "Example:\n",
- "```java\n",
- "public void waterTracker(int numberOfGlasses)\n",
- "public void waterTracker(String typeOfDrink)\n",
- "```\n",
- "\n",
- "The `waterTracker` method is overloaded with two versions:\n",
- "1. Takes an **integer** parameter.\n",
- "2. Takes a **String** parameter.\n",
- "\n",
- "Depending on the argument passed when calling `waterTracker`, the appropriate method is invoked."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Calling a Non-Void Method\n",
- "\n",
- "In the `study(int hoursStudied)` method, the return type was **void**, meaning nothing was returned. However, methods in Java can have various return types, both **primitive** and **reference types**. Methods can return types like **int**, **String**, **boolean**, **double**, **Object**, and more. Implementing a non-void return type allows storing the result for later use.\n",
- "\n",
- "A method with a non-void return type must end with a **return statement**, specifying what the method returns. The return statement must be the last line in the method.\n",
- "\n",
- "Example:\n",
- "```java\n",
- "public double degreesToRadians(double degrees) {\n",
- " double radians = degrees * (3.141 / 180);\n",
- " return radians;\n",
- "}\n",
- "```\n",
- "\n",
- "In this method, the return type is **double**, so we return the variable **radians**. The result can be stored in a variable like this:\n",
- "```java\n",
- "double result = degreesToRadians(34.5);\n",
- "```\n",
- "\n",
- "The right side evaluates to approximately **0.602**, which becomes the value of **result**. Pretty useful!"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## String Objects: Concatenation, Literals, and More\n",
- "\n",
- "In Java, a **String** object is a sequence of characters. You can create a **String** object using the **String class's constructor**:\n",
- "```java\n",
- "String greeting = new String(\"What's up?\");\n",
- "```\n",
- "However, the more efficient way is to use a **string literal**:\n",
- "```java\n",
- "String greeting = \"What's up?\";\n",
- "```\n",
- "\n",
- "Since a **String** is an object, you can call methods on it, such as `.length()` and `.toLowerCase()`. One special feature of **Strings** is **string concatenation**, which combines two or more strings into a single string using the `+` operator. Remember to add a space between words, as Java does not do that automatically:\n",
- "```java\n",
- "String greeting = \"What's \" + \"up?\";\n",
- "```\n",
- "\n",
- "**Escape characters** represent special characters in a string. For example, `\\n` represents a new line:\n",
- "```java\n",
- "String greeting = \"Hello,\\nworld!\";\n",
- "```\n",
- "This will output:\n",
- "```\n",
- "Hello,\n",
- "world!\n",
- "```"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## String Methods\n",
- "\n",
- "In Java, the **String** class has several methods for performing operations on strings. Some common **String** methods are:\n",
- "\n",
- "- **length()**: Returns the length of the string.\n",
- "- **indexOf(String str)**: Returns the index of the first occurrence of the specified string.\n",
- "- **substring(int beginIndex)**: Returns a new string that starts at the specified **beginIndex** and extends to the end of the string.\n",
- "- **substring(int beginIndex, int endIndex)**: Returns a new string that starts at **beginIndex** and extends to **endIndex - 1**.\n",
- "\n",
- "The **substring** method is overloaded with two versions. In Java, indexing starts at 0, meaning the first character of a string has an index of 0. For example, the string `\"taco cat\"` has a length of 8 characters, with indices from 0 to 7."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 8,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "4\n",
- "1\n"
- ]
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "st\n",
- "s\n"
- ]
- }
- ],
- "source": [
- "String test = \"test\";\n",
- "System.out.println(test.length());\n",
- "System.out.println(test.indexOf(\"es\"));\n",
- "System.out.println(test.substring(2));\n",
- "System.out.println(test.substring(2, 3));"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Using the Math Class\n",
- "\n",
- "The **Math** class in Java provides various mathematical functions and constants. It's included in the standard Java package, so no import is needed. Some common methods of the **Math** class are:\n",
- "\n",
- "- **abs(int a)**: Returns the absolute value of the argument as an **int** or **double**, depending on the input type.\n",
- "- **pow(double a, double b)**: Returns the value of **a** raised to the power of **b** as a **double**.\n",
- "- **sqrt(double a)**: Returns the square root of the argument as a **double**.\n",
- "- **random()**: Returns a random number between 0 (inclusive) and 1 (exclusive) as a **double**.\n",
- "\n",
- "The **Math** class also includes constants like **Math.PI** (approximately 3.14159).\n",
- "\n",
- "### Summary of Topics\n",
- "\n",
- "- **Making/Initializing Objects**\n",
- "- **Writing/Calling Methods**\n",
- "- **String Class**\n",
- "- **String Methods**\n",
- " - **length()**: Returns the length of the string.\n",
- " - **indexOf(String str)**: Returns the index of the first occurrence of the specified string.\n",
- " - **substring(int beginIndex)**: Returns a new string that starts at **beginIndex** and extends to the end.\n",
- " - **substring(int beginIndex, int endIndex)**: Returns a new string that starts at **beginIndex** and extends to **endIndex - 1**.\n",
- "- **Wrapper Classes**\n",
- "- **Math Class**\n",
- " - **abs(int a)**: Returns the absolute value of the argument.\n",
- " - **pow(double a, double b)**: Returns **a** raised to the power of **b**.\n",
- " - **sqrt(double a)**: Returns the square root of the argument.\n",
- " - **random()**: Returns a random number between 0 and 1."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "\n",
- "Additional Resources:\n",
- "\n",
- "[Codecademy](https://www.codecademy.com/learn/learn-java) \n",
- "[HackerRank](https://www.hackerrank.com/domains/tutorials/10-days-of-java)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Hacks\n",
- "### Part 1"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "public class Car {\n",
- " String brand;\n",
- " String model;\n",
- " int year;\n",
- " boolean isElectric;\n",
- "\n",
- " public Car(String brand, String model, int year, boolean isElectric) {\n",
- " this.brand = brand;\n",
- " this.model = model;\n",
- " this.year = year;\n",
- " this.isElectric = isElectric;\n",
- " }\n",
- "\n",
- " public void printCarInfo() {\n",
- " System.out.println(\"Brand: \" + brand + \", Model: \" + model + \", Year: \" + year + \", Electric: \" + isElectric);\n",
- " }\n",
- "\n",
- " public boolean isElectricCar() {\n",
- " return isElectric;\n",
- " }\n",
- "}\n",
- "\n",
- "public static void main(String[] args) {\n",
- " Car car1 = new Car(\"Tesla\", \"Model S\", 2023, true);\n",
- " Car car2 = new Car(\"Ford\", \"Mustang\", 2022, false);\n",
- " Car car3 = new Car(\"Nissan\", \"Leaf\", 2023, true);\n",
- " \n",
- " car1.printCarInfo();\n",
- " System.out.println(\"Is car2 electric? \" + car2.isElectricCar());\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Answer the following questions based on the code above:\n",
- "* a) What is the purpose of the `Car` class in the given code? How does it represent the concept of objects in Java?\n",
- "* Answer: \n",
- "* b) Explain how the `printCarInfo` method is used in the code. What information does it display, and how is it called?\n",
- "* Answer: \n",
- "* c) The method `isElectricCar` returns a boolean value. Explain how this method is used with the `car2` object and what the output will be.\n",
- "* Answer: \n",
- "* d) If you wanted to add a new method to the `Car` class to calculate the car's age, how would you implement it? Provide a brief code example.\n",
- "* Answer: "
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Part 2\n",
- "Situation: You are building an inventory management system where you need to manage different products. Each product has attributes like name, quantity, and price. \n",
- "\n",
- "(a) Define the term \"class\" in Java and explain how it relates to objects. Provide an example to illustrate your explanation.\n",
- "\n",
- "(b) Explain the purpose of a constructor in a Java class. How does it differ from a method?\n",
- "\n",
- "(c) Code:\n",
- "\n",
- "You need to create a `Product` class with attributes `String name`, `int quantity`, and `double price`. Write a constructor for this class that initializes these attributes. Also, write a method `calculateTotalValue` that returns the total value of the product (quantity * price). Provide comments in your code to explain each step."
- ]
- }
- ],
- "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": "19.0.2+7-44"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/backup_summer_2024/2024-06-24-unit_3.ipynb b/_notebooks/CSA/units_1_to_10/backup_summer_2024/2024-06-24-unit_3.ipynb
deleted file mode 100644
index dee81de2..00000000
--- a/_notebooks/CSA/units_1_to_10/backup_summer_2024/2024-06-24-unit_3.ipynb
+++ /dev/null
@@ -1,439 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "toc: true\n",
- "title: Unit 3 - Boolean Expressions and if Statements\n",
- "description: Boolean Expressions and if Statements\n",
- "authors: Aniket Chakradeo, Soham Kamat\n",
- "categories: [AP CSA]\n",
- "permalink: /unit3lesson\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Introduction\n",
- "\n",
- "In Java, evaluating conditions and controlling the flow of your program is fundamental. This involves using boolean expressions and operators, as well as conditional statements like if, if-else, and else if. These constructs help you make decisions and execute different blocks of code based on varying conditions. Understanding how to use these effectively is crucial for writing clear and efficient code."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Boolean Expressions\n",
- "\n",
- "**Boolean expressions** evaluate to either **true** or **false** and use the following operators:\n",
- "- `==` (equals to)\n",
- "- `!=` (not equal to)\n",
- "- `<` (less than)\n",
- "- `<=` (less than or equal to)\n",
- "- `>` (greater than)\n",
- "- `>=` (greater than or equal to)\n",
- "\n",
- "These operators compare **primitive types** like integers and doubles. For example:\n",
- "- `3 < 5` returns **true**\n",
- "- `3 >= 5` returns **false**\n",
- "\n",
- "**Boolean Logic Operators** include:\n",
- "- **! (NOT)**: Negates the expression. Example: `!true` evaluates to `false`.\n",
- "- **&& (AND)**: Returns true if both expressions are true. Example: `(a % 2 == 0) && (a % 3 == 0)` is true if `a` is divisible by both 2 and 3.\n",
- "- **|| (OR)**: Returns true if at least one expression is true. Example: `(a % 2 == 0) || (a % 3 == 0)` is true if `a` is divisible by either 2 or 3.\n",
- "\n",
- "**Order of Operations**:\n",
- "1. NOT\n",
- "2. AND\n",
- "3. OR\n",
- "\n",
- "**Compound Boolean Statements** combine multiple conditions:\n",
- "```java\n",
- "if ((number % 2 == 0) && (number % 3 == 0)) {\n",
- " return \"Even and divisible by 3\";\n",
- "} else if (number % 2 == 0) {\n",
- " return \"Even\"; \n",
- "}\n",
- "```\n",
- "\n",
- "**Truth Tables** help simplify boolean expressions by testing all possible inputs. For example, `a || ((!b && !a) && !b)` simplifies to `a || !b`."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## If Statements and Control Flow\n",
- "\n",
- "**If Statements** \n",
- "An **if statement** allows you to execute a block of code only if a specified condition is **true**. \n",
- "\n",
- "### Example: Even Number Checker\n",
- "```java\n",
- "public static int numberHalver(int number) {\n",
- " if (number % 2 == 0) {\n",
- " number /= 2;\n",
- " }\n",
- " return number;\n",
- "}\n",
- "```\n",
- "In this example, the number is halved if it is even.\n",
- "\n",
- "**Return Statements** \n",
- "A **return statement** inside an **if statement** causes the method to terminate immediately with the return value, skipping any remaining code.\n",
- "\n",
- "### Example: Check Even Number\n",
- "```java\n",
- "public static boolean isEven(int number) {\n",
- " if (number % 2 == 0) {\n",
- " return true;\n",
- " }\n",
- " return false;\n",
- "}\n",
- "```\n",
- "Here, `return false;` is only reached if the condition is not met.\n",
- "\n",
- "**If-Else Statements** \n",
- "An **if-else statement** executes one block of code if a condition is **true**, and another if the condition is **false**.\n",
- "\n",
- "### Example: Number Rounding\n",
- "```java\n",
- "public static int round(double number) {\n",
- " if (number >= 0) {\n",
- " return (int) (number + 0.5);\n",
- " } else {\n",
- " return (int) (number - 0.5);\n",
- " }\n",
- "}\n",
- "```\n",
- "This method rounds a number based on its sign.\n",
- "\n",
- "**If-Else If-Else Statements** \n",
- "The **if-else if-else** structure checks multiple conditions in sequence, executing different blocks of code based on which condition is **true**.\n",
- "\n",
- "### Example: Divisibility Counter\n",
- "```java\n",
- "public static int largestDivisorLessThanTen(int number) {\n",
- " if (number % 10 == 0) { return 10; }\n",
- " else if (number % 9 == 0) { return 9; }\n",
- " else if (number % 8 == 0) { return 8; }\n",
- " else if (number % 7 == 0) { return 7; }\n",
- " else if (number % 6 == 0) { return 6; }\n",
- " else if (number % 5 == 0) { return 5; }\n",
- " else if (number % 4 == 0) { return 4; }\n",
- " else if (number % 3 == 0) { return 3; }\n",
- " else if (number % 2 == 0) { return 2; }\n",
- " else { return 1; }\n",
- "}\n",
- "```\n",
- "This method finds the largest divisor between 1 and 10 for a given number."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## If-Else Statements\n",
- "\n",
- "An **if-else statement** allows you to execute one block of code if a condition is **true**, and another block if the condition is **false**. It’s known as a two-way selection.\n",
- "\n",
- "### Anatomy of an If-Else Statement:\n",
- "```java\n",
- "// Some code that runs before the conditional statement\n",
- "if (condition) {\n",
- " // Code that runs if the condition is true\n",
- "} else {\n",
- " // Code that runs if the condition is false\n",
- "}\n",
- "// Some code that runs after\n",
- "```\n",
- "\n",
- "- **Condition**: Enclosed in parentheses.\n",
- "- **If Block**: Contains code that runs if the condition is true, enclosed in curly braces `{}`.\n",
- "- **Else Block**: Contains code that runs if the condition is false, also enclosed in curly braces `{}`.\n",
- "\n",
- "Make sure to use brackets around the code in both the `if` and `else` blocks. This prevents confusion about which code is associated with each block and avoids unexpected behavior.\n",
- "\n",
- "### Example: Number Rounding\n",
- "\n",
- "Here’s a method that rounds a number to the nearest integer using an if-else statement:\n",
- "```java\n",
- "public static int round(double number) {\n",
- " if (number >= 0) {\n",
- " return (int) (number + 0.5);\n",
- " } else {\n",
- " return (int) (number - 0.5);\n",
- " }\n",
- "}\n",
- "```\n",
- "\n",
- "- **If Block**: Rounds up if the number is non-negative.\n",
- "- **Else Block**: Rounds down if the number is negative."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Else If Statements\n",
- "\n",
- "**Else if** statements are used when you need to handle multiple conditions in sequence. They allow you to test several conditions and execute different blocks of code depending on which condition is true.\n",
- "\n",
- "### Anatomy of an Else If Statement:\n",
- "```java\n",
- "if (condition1) {\n",
- " // Code runs if condition1 is true\n",
- "} else if (condition2) {\n",
- " // Code runs if condition1 is false and condition2 is true\n",
- "} else if (condition3) {\n",
- " // Code runs if condition1 and condition2 are false and condition3 is true\n",
- "}\n",
- "// Additional else if statements as needed\n",
- "else {\n",
- " // Code runs if none of the above conditions are true\n",
- "}\n",
- "```\n",
- "\n",
- "- **If Block**: Executes if `condition1` is true.\n",
- "- **Else If Blocks**: Execute if the preceding conditions are false and the current condition is true.\n",
- "- **Else Block**: Executes if none of the above conditions are true.\n",
- "\n",
- "### Example: Divisibility Counter\n",
- "\n",
- "This method returns the largest divisor between 1 and 10 that a number is divisible by:\n",
- "```java\n",
- "public static int largestDivisorLessThanTen(int number) {\n",
- " if (number % 10 == 0) { return 10; }\n",
- " else if (number % 9 == 0) { return 9; }\n",
- " else if (number % 8 == 0) { return 8; }\n",
- " else if (number % 7 == 0) { return 7; }\n",
- " else if (number % 6 == 0) { return 6; }\n",
- " else if (number % 5 == 0) { return 5; }\n",
- " else if (number % 4 == 0) { return 4; }\n",
- " else if (number % 3 == 0) { return 3; }\n",
- " else if (number % 2 == 0) { return 2; }\n",
- " else { return 1; }\n",
- "}\n",
- "```\n",
- "\n",
- "### Example: Leap Year Decider\n",
- "\n",
- "This method determines if a year is a leap year:\n",
- "```java\n",
- "public static boolean isLeap(int year) {\n",
- " if (year % 400 == 0) { return true; }\n",
- " else if (year % 100 == 0) { return false; }\n",
- " else if (year % 4 == 0) { return true; }\n",
- " return false; // This line runs if none of the above conditions are true\n",
- "}\n",
- "```\n",
- "\n",
- "**Tip**: Order the conditions from most specific to least specific to ensure the correct block of code executes."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Compound Boolean Expressions\n",
- "\n",
- "**Compound boolean expressions** combine multiple boolean conditions using logical operators to form more complex conditions.\n",
- "\n",
- "### Example:\n",
- "```java\n",
- "if ((number % 2 == 0) && (number % 3 == 0)) {\n",
- " return \"Even and divisible by 3\";\n",
- "} else if (number % 2 == 0) {\n",
- " return \"Even\"; \n",
- "}\n",
- "```\n",
- "\n",
- "In this example:\n",
- "- **`(number % 2 == 0) && (number % 3 == 0)`** checks if a number is both even and divisible by 3.\n",
- "- If true, it returns \"Even and divisible by 3\".\n",
- "- If the first condition is false but the number is still even, it returns \"Even\".\n",
- "\n",
- "Compound boolean expressions simplify multiple condition checks into a single statement, enhancing readability and reducing nesting."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Equivalents Boolean Expressions\n",
- "\n",
- "Boolean expressions can often be simplified or transformed into equivalent forms. For example, a boolean expression like `a || ((!b && !a) && !b)` can be simplified. To simplify such expressions, you can use truth tables to test all possible input combinations. \n",
- "\n",
- "Here's how you can simplify expressions:\n",
- "\n",
- "**Truth Table Example for `a || ((!b && !a) && !b)`**:\n",
- "\n",
- "| a | b | !a | !b | !b && !a | (!b && !a) && !b | a || ((!b && !a) && !b) |\n",
- "|-------|-------|-------|-------|----------|------------------|-------------------------|\n",
- "| False | False | True | True | True | True | True |\n",
- "| False | True | True | False | False | False | False |\n",
- "| True | False | False | True | False | False | True |\n",
- "| True | True | False | False | False | False | True |\n",
- "\n",
- "From this truth table, we see that `a || ((!b && !a) && !b)` simplifies to `a || !b`."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Comparing Objects\n",
- "\n",
- "In Java, to compare objects for equality, you should understand the differences between the `==` operator and the `equals()` method:\n",
- "\n",
- "### Equality Operator (`==`)\n",
- "\n",
- "The `==` operator checks if two references point to the exact same object in memory. It does not compare the values or attributes of the objects.\n",
- "\n",
- "**Examples:**\n",
- "```java\n",
- "String a = \"Hi\";\n",
- "String b = \"Hi\";\n",
- "String c = a;\n",
- "String d = new String(\"Hi\");\n",
- "\n",
- "System.out.println(a == c); // true (same reference)\n",
- "System.out.println(a == b); // true (interned string literals)\n",
- "System.out.println(a == d); // false (different references)\n",
- "```\n",
- "\n",
- "### `equals()` Method\n",
- "\n",
- "The `equals()` method compares the values or attributes of two objects. It is often overridden in custom classes to provide meaningful equality checks based on the class's attributes.\n",
- "\n",
- "**Examples:**\n",
- "```java\n",
- "String a = \"Hi\";\n",
- "String b = \"Hi\";\n",
- "String d = new String(\"Hi\");\n",
- "\n",
- "System.out.println(a.equals(b)); // true (same content)\n",
- "System.out.println(a.equals(d)); // true (same content)\n",
- "```\n",
- "\n",
- "**Key Points:**\n",
- "- **`==` Operator**: Checks reference equality. Use it to see if two references point to the same object.\n",
- "- **`equals()` Method**: Checks value equality. Use it to compare the contents of objects.\n",
- "\n",
- "When comparing objects, use `equals()` unless you need to check if the references are the same instance. Understanding these methods helps in writing accurate and effective Java code."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "\n",
- "Additional Resources:\n",
- "\n",
- "[GeeksforGeeks](https://www.geeksforgeeks.org/python-boolean-type/) \n",
- "[Quizlet](https://quizlet.com/799033911/boolean-in-java-flash-cards/)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Hacks\n",
- "### Part 1"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 2,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class Book {\n",
- " String title;\n",
- " String author;\n",
- " int pages;\n",
- "\n",
- " public Book(String title, String author, int pages) {\n",
- " this.title = title;\n",
- " this.author = author;\n",
- " this.pages = pages;\n",
- " }\n",
- "\n",
- " public boolean isLongBook() {\n",
- " if (this.pages > 300) {\n",
- " return true;\n",
- " } else {\n",
- " return false;\n",
- " }\n",
- " }\n",
- "\n",
- " public static void main(String[] args) {\n",
- " Book book1 = new Book(\"1984\", \"George Orwell\", 328);\n",
- " Book book2 = new Book(\"Brave New World\", \"Aldous Huxley\", 288);\n",
- " System.out.println(book1.isLongBook());\n",
- " System.out.println(book2.isLongBook());\n",
- " }\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Answer the following questions based on the code above:\n",
- "* a) What will be the output of the `System.out.println(book1.isLongBook());` statement? Explain the reasoning behind this output based on the code.\n",
- "* Answer: \n",
- "* b) Modify the `isLongBook()` method to use a single return statement without using the `if-else` structure. Rewrite the method and explain how your code achieves the same functionality.\n",
- "* Answer: "
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Part 2\n",
- "Situation: You are developing a library management system where you need to manage book details and check certain conditions based on the book attributes. You want to write methods that utilize Boolean expressions and if statements to control the flow of your program.\n",
- "\n",
- "(a) Explain the purpose of Boolean expressions in Java and how they are used within if statements to control the flow of a program. Provide an example using a simple comparison between two integers.\n",
- "\n",
- "(b) Discuss the importance of order in if-else if-else statements. How does the order of conditions affect the program's execution? Provide an example with three conditions to demonstrate your explanation.\n",
- "\n",
- "(c) Code:\n",
- "\n",
- "You have a method `isEligibleForDiscount` that determines if a book is eligible for a discount based on its price and genre. The method should take two parameters: a double `price` representing the book's price, and a String `genre` representing the book's genre. The book is eligible for a discount if its price is above $20 and its genre is either \"Fiction\" or \"Mystery\".\n",
- "\n",
- "Write the method signature and the method implementation. Include comments to explain 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": "19.0.2+7-44"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/backup_summer_2024/2024-06-24-unit_4.ipynb b/_notebooks/CSA/units_1_to_10/backup_summer_2024/2024-06-24-unit_4.ipynb
deleted file mode 100644
index 6fcfc970..00000000
--- a/_notebooks/CSA/units_1_to_10/backup_summer_2024/2024-06-24-unit_4.ipynb
+++ /dev/null
@@ -1,352 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "toc: true\n",
- "title: Unit 4 - Iteration\n",
- "description: Iteration\n",
- "authors: Aniket Chakradeo, Soham Kamat\n",
- "categories: [AP CSA]\n",
- "permalink: /unit4lesson\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Introduction\n",
- "\n",
- "Loops are fundamental constructs in programming that allow for the repetition of code. They are essential for performing tasks that require iteration, such as processing elements in arrays or strings, and executing repetitive actions. In this guide, we'll explore various types of loops—while loops, for loops—and their applications, including how they interact with strings and nested structures. Understanding these concepts is crucial for developing efficient algorithms and solving complex problems in programming."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## While Loops\n",
- "\n",
- "A while loop repeatedly executes a block of code as long as a specified condition remains true. The condition is evaluated before each iteration, and if it is true, the loop's body runs; if false, the loop terminates. To avoid infinite loops, ensure the condition will eventually become false by modifying it within the loop.\n",
- "\n",
- "### Example:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "int i = 0;\n",
- "while (i < 5) {\n",
- " System.out.print(i);\n",
- " i++;\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "**Explanation:**\n",
- "1. Initialize `i` to 0.\n",
- "2. The loop checks if `i` is less than 5. If true, it executes the body.\n",
- "3. The body prints `i` and increments it.\n",
- "4. After each iteration, the condition is re-evaluated. When `i` reaches 5, the loop stops.\n",
- "\n",
- "**Tracing Table:**\n",
- "| i | Output |\n",
- "|-|-|\n",
- "| 0 | 0 |\n",
- "| 1 | 1 |\n",
- "| 2 | 2 |\n",
- "| 3 | 3 |\n",
- "| 4 | 4 |\n",
- "\n",
- "If the initial condition is false, the loop will not execute. A `return` statement inside a while loop will also stop it immediately, regardless of the condition.\n",
- "\n",
- "**Common Uses:**\n",
- "- Identify individual digits of an integer\n",
- "- Determine a minimum or maximum value\n",
- "- Compute a sum, average, or mode"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## For Loops\n",
- "\n",
- "A for loop provides a concise way to repeat code with initialization, condition-checking, and iteration all in one line. The basic structure in Java is:\n",
- "\n",
- "```java\n",
- "for (initialization; condition; iteration) {\n",
- " // code to be executed\n",
- "}\n",
- "```\n",
- "\n",
- "- **Initialization**: Executes once before the loop starts, typically to set up a loop counter.\n",
- "- **Condition**: Evaluated before each iteration. If true, the loop body executes; if false, the loop terminates.\n",
- "- **Iteration**: Executes after each iteration of the loop body, usually to update the loop counter.\n",
- "\n",
- "### Example:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "for (int i = 0; i < 5; i++) {\n",
- " System.out.print(i);\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "**Explanation:**\n",
- "1. `int i = 0;` initializes the loop counter `i`.\n",
- "2. `i < 5` is the condition. The loop continues as long as `i` is less than 5.\n",
- "3. `i++` increments `i` after each iteration.\n",
- "\n",
- "The for loop achieves the same result as a while loop but in fewer lines, making it more compact and often easier to read. All for loops can be converted to while loops and vice versa."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Developing Algorithms Using Strings\n",
- "\n",
- "Loops can be used to process and analyze strings in various ways. With methods like `.length()` and `.substring()`, you can perform tasks such as counting characters.\n",
- "\n",
- "### Example: Counting Occurrences of a Character"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "String str = \"computer science\";\n",
- "int count = 0;\n",
- "\n",
- "for (int i = 0; i < str.length(); i++) {\n",
- " if (str.substring(i, i+1).equals(\"e\")) {\n",
- " count++;\n",
- " }\n",
- "}\n",
- "\n",
- "System.out.println(count);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "\n",
- "\n",
- "\n",
- "**Explanation:**\n",
- "1. `String str = \"computer science\";` initializes the string.\n",
- "2. `int count = 0;` creates a counter for occurrences of \"e\".\n",
- "3. `for (int i = 0; i < str.length(); i++)` iterates over each character in the string.\n",
- "4. `str.substring(i, i+1).equals(\"e\")` checks if the current character is \"e\".\n",
- "5. If true, increment the count.\n",
- "\n",
- "**Other Uses:**\n",
- "- Reversing a string\n",
- "- Finding substrings with specific properties\n",
- "- Checking for specific substrings\n",
- "\n",
- "**Tip:** Tracing tables can help keep track of iterations and conditions in loops working with strings."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Nested Iteration\n",
- "\n",
- "Nested loops involve placing one loop inside another, which is useful for tasks like traversing 2D arrays. The inner loop completes all its iterations before the outer loop moves to the next iteration.\n",
- "\n",
- "### Example:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "int rows = 5;\n",
- "\n",
- "for (int i = 1; i <= rows; i++) {\n",
- " for (int j = 1; j <= i; j++) {\n",
- " System.out.print(\"*\");\n",
- " }\n",
- " System.out.println();\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "**Explanation:**\n",
- "1. `int rows = 5;` sets the number of rows for the pattern.\n",
- "2. The outer loop (`for (int i = 1; i <= rows; i++)`) iterates over each row.\n",
- "3. The inner loop (`for (int j = 1; j <= i; j++)`) prints asterisks based on the current row number.\n",
- "4. `System.out.println();` moves to the next line after completing the inner loop for each row.\n",
- "\n",
- "**Tip:** Use tracing tables to track the iterations of nested loops for complex patterns or calculations."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Informal Code Analysis\n",
- "\n",
- "Informal code analysis involves examining and understanding code execution without formal tools. This can include manually tracing code execution, predicting output, and identifying logical errors. \n",
- "\n",
- "**Key Techniques:**\n",
- "- **Tracing Code**: Manually following the flow of execution, step-by-step, to understand how variables change and how loops execute.\n",
- "- **Predicting Output**: Anticipating the result of code before running it, based on the logic and structure.\n",
- "- **Identifying Errors**: Spotting potential mistakes or inefficiencies by reviewing code logic and flow.\n",
- "\n",
- "### Example of Manual Tracing:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "int i = 0;\n",
- "while (i < 3) {\n",
- " System.out.print(i);\n",
- " i++;\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "**Tracing Steps:**\n",
- "1. Initialize `i` to 0.\n",
- "2. Check if `i < 3` (true), print `0`, increment `i` to 1.\n",
- "3. Repeat: `i < 3` (true), print `1`, increment `i` to 2.\n",
- "4. Repeat: `i < 3` (true), print `2`, increment `i` to 3.\n",
- "5. Check `i < 3` (false), exit loop.\n",
- "\n",
- "Informal analysis helps in understanding code behavior and debugging before deploying formal testing methods."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "\n",
- "Additional Resources:\n",
- "\n",
- "[Quizlet](https://quizlet.com/27721837/java-concepts-chapter-7-iteration-flash-cards/) \n",
- "[Khan Academy](https://www.khanacademy.org/computing/ap-computer-science-principles/programming-101/lists/a/iterating-over-lists-with-loops)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Hacks\n",
- "### Part 1"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "public class NumberPrinter {\n",
- " public static void main(String[] args) {\n",
- " int i = 1;\n",
- " while (i <= 5) {\n",
- " System.out.print(i + \" \");\n",
- " i++;\n",
- " }\n",
- " System.out.println();\n",
- "\n",
- " for (int j = 5; j > 0; j--) {\n",
- " System.out.print(j + \" \");\n",
- " }\n",
- " System.out.println();\n",
- "\n",
- " for (int k = 1; k <= 3; k++) {\n",
- " for (int l = 1; l <= k; l++) {\n",
- " System.out.print(\"*\");\n",
- " }\n",
- " System.out.println();\n",
- " }\n",
- " }\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Answer the following questions based on the code above:\n",
- "* a) What will be the output of each loop in the code? Explain how each loop works.\n",
- "* Answer: \n",
- "* b) Modify the first while loop so that it prints the numbers in reverse order, from 5 to 1, instead of 1 to 5. Provide the modified code and explain the changes.\n",
- "* Answer: "
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Part 2\n",
- "Situation: You are developing a program to analyze student grades and identify patterns. You need to write methods that use loops to perform these tasks.\n",
- "\n",
- "(a) Explain how a for loop and a while loop differ in structure and usage. Provide an example of when you might prefer one over the other.\n",
- "\n",
- "(b) Write a method `calculateAverage` that takes an array of integers representing student grades and returns the average grade using a for loop. Next, write a method `findHighestGrade` that uses a while loop to find and return the highest grade in the array.\n",
- "\n",
- "Provide the code for both methods and demonstrate how to call them with an example array of grades."
- ]
- }
- ],
- "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": "19.0.2+7-44"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/backup_summer_2024/2024-06-24-unit_5.ipynb b/_notebooks/CSA/units_1_to_10/backup_summer_2024/2024-06-24-unit_5.ipynb
deleted file mode 100644
index 43e8973a..00000000
--- a/_notebooks/CSA/units_1_to_10/backup_summer_2024/2024-06-24-unit_5.ipynb
+++ /dev/null
@@ -1,565 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "toc: true\n",
- "title: Unit 5 - Writing Classes\n",
- "description: Writing Classes\n",
- "authors: Aniket Chakradeo, Soham Kamat\n",
- "categories: [AP CSA]\n",
- "permalink: /unit5lesson\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Introduction\n",
- "\n",
- "A class serves as a blueprint for creating objects in programming. It encapsulates data and methods that operate on that data. To define a class, specify its access level (public or private), use the `class` keyword, and provide a name. Inside the class, you define variables to hold data and methods to perform operations. For instance, in the `AreaCalculator` class, you can define instance variables and methods to calculate areas of various shapes, illustrating how classes structure and manage data and functionality."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Anatomy of a Class\n",
- "\n",
- "A class is a blueprint for creating objects, containing variables and methods to manage data and perform actions. To define a class, specify its access level (public or private), use the `class` keyword, and provide a name. Enclose the class contents within curly braces `{}`. For example, the `AreaCalculator` class can be defined as follows:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 1,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class AreaCalculator {}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Inside the curly braces, you can declare instance variables to store data and methods to perform operations. For instance, an `AreaCalculator` class might include an instance variable to track the number of shapes processed:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class AreaCalculator {\n",
- " private int numShapes;\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "The `numShapes` variable is private to restrict access from other classes, ensuring it is only accessible within the `AreaCalculator` class."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Constructors\n",
- "\n",
- "Constructors are special methods used to initialize objects of a class. They have the same name as the class and no return type. Every class must have at least one constructor, and if none is provided, a default constructor is created. Constructors should be public so that objects can be instantiated from other classes.\n",
- "\n",
- "For example, the `AreaCalculator` class includes a constructor to initialize the `numShapes` variable:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class AreaCalculator {\n",
- " private int numShapes;\n",
- "\n",
- " public AreaCalculator() {\n",
- " numShapes = 0;\n",
- " }\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Constructors can also take parameters to initialize instance variables with specific values. For example, the `Car` class has a parameterized constructor:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class Car {\n",
- " private String brand;\n",
- " private String model;\n",
- " private int year;\n",
- "\n",
- " public Car(String make, String carModel, int yearMade) {\n",
- " brand = make;\n",
- " model = carModel;\n",
- " year = yearMade;\n",
- " }\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "In this case, constructor parameters are used to set the initial values of `brand`, `model`, and `year`."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Accessor Methods\n",
- "\n",
- "Accessor methods, also known as getters, are used to retrieve the value of private instance variables from outside the class. They are public methods that return the value of a variable without modifying it.\n",
- "\n",
- "For example, to access the `numShapes` variable in the `AreaCalculator` class, you can create an accessor method like this:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class AreaCalculator {\n",
- " private int numShapes;\n",
- "\n",
- " // Accessor method for numShapes\n",
- " public int getNumShapes() {\n",
- " return numShapes;\n",
- " }\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Accessor methods typically have a return type matching the variable's type and usually consist of a single line that returns the value of the variable."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Mutator Methods\n",
- "\n",
- "Mutator methods, also known as setters, are used to modify the value of private instance variables. They are public methods that typically have a `void` return type and accept parameters to update the variable.\n",
- "\n",
- "For example, in the `Car` class, a mutator method for the `year` variable might look like this:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class Car {\n",
- " private int year;\n",
- "\n",
- " // Mutator method for year\n",
- " public void setYear(int newYear) {\n",
- " year = newYear;\n",
- " }\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Mutator methods allow you to change the value of instance variables after an object has been created, providing a controlled way to modify data."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Writing Methods\n",
- "\n",
- "Methods are used to perform actions and compute values within a class. They can take parameters and return values. For instance, in the `AreaCalculator` class, you might write methods to calculate the area of different shapes. When writing methods, remember that primitive types are passed by value, meaning changes to parameters do not affect the original variables. Objects are passed by reference, so changes to an object's attributes inside a method will affect the original object.\n",
- "\n",
- "Here are examples of methods for calculating areas in the `AreaCalculator` class:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class AreaCalculator {\n",
- " private int numShapes;\n",
- "\n",
- " // Method to calculate the area of a triangle\n",
- " public double triangleArea(double base, double height) {\n",
- " double area = (base * height) / 2;\n",
- " numShapes++;\n",
- " return area;\n",
- " }\n",
- "\n",
- " // Method to calculate the area of a rectangle\n",
- " public double rectangleArea(double length, double width) {\n",
- " double area = length * width;\n",
- " numShapes++;\n",
- " return area;\n",
- " }\n",
- "\n",
- " // Method to calculate the area of a trapezoid\n",
- " public double trapezoidArea(double base1, double base2, double height) {\n",
- " double area = (base1 + base2) * height / 2;\n",
- " numShapes++;\n",
- " return area;\n",
- " }\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Each method performs a calculation and updates the `numShapes` variable to reflect that a shape's area has been calculated."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Static Variables and Methods\n",
- "\n",
- "Static variables and methods belong to the class rather than to any specific object. They are shared across all instances of the class and can be accessed without creating an object. To define a static variable or method, use the `static` keyword.\n",
- "\n",
- "For example, in the `AreaCalculator` class, you can make `numShapes` and the area calculation methods static:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class AreaCalculator {\n",
- " private static int numShapes;\n",
- "\n",
- " // Static method to calculate the area of a rectangle\n",
- " public static double rectangleArea(double length, double width) {\n",
- " double area = length * width;\n",
- " numShapes++;\n",
- " return area;\n",
- " }\n",
- "\n",
- " // Static method to calculate the area of a triangle\n",
- " public static double triangleArea(double base, double height) {\n",
- " double area = (base * height) / 2;\n",
- " numShapes++;\n",
- " return area;\n",
- " }\n",
- "\n",
- " // Static method to calculate the area of a trapezoid\n",
- " public static double trapezoidArea(double base1, double base2, double height) {\n",
- " double area = (base1 + base2) * height / 2;\n",
- " numShapes++;\n",
- " return area;\n",
- " }\n",
- "\n",
- " // Static method to get the number of shapes calculated\n",
- " public static int getNumShapes() {\n",
- " return numShapes;\n",
- " }\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Static methods and variables are accessed using the class name, like `AreaCalculator.rectangleArea(5.0, 3.0)`, without needing to instantiate an `AreaCalculator` object."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Scope and Access\n",
- "\n",
- "Scope refers to the visibility and accessibility of variables, methods, and other elements within a program. In Java, there are two main types of scope:\n",
- "\n",
- "1. **Global Scope**: Variables and methods with global scope are accessible from anywhere within the class. For example, instance variables defined outside of methods but inside the class have global scope within that class.\n",
- "\n",
- "2. **Local Scope**: Variables with local scope are accessible only within the block of code in which they are defined, such as within a method. For example, variables declared inside a method exist only during the execution of that method and are not accessible outside of it.\n",
- "\n",
- "In the `AreaCalculator` class, the `numShapes` variable has global scope within the class, while the `area` variable used in methods like `triangleArea` has local scope:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class AreaCalculator {\n",
- " private int numShapes; // Global scope within the class\n",
- "\n",
- " public double triangleArea(double base, double height) {\n",
- " double area = (base * height) / 2; // Local scope within this method\n",
- " numShapes++;\n",
- " return area;\n",
- " }\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Understanding scope helps in managing variable visibility and avoiding conflicts, leading to more organized and efficient code."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## This Keyword\n",
- "\n",
- "In Java, the `this` keyword refers to the current instance of a class. It is used within an object's methods to access its fields and methods. It helps to distinguish between instance variables and parameters or local variables with the same name and can also be used to pass the current object as a parameter to another method.\n",
- "\n",
- "Here’s how you can use the `this` keyword:\n",
- "\n",
- "1. **Accessing Instance Variables**: To refer to the current object's instance variables."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class MyClass {\n",
- " int x;\n",
- "\n",
- " public void setX(int x) {\n",
- " this.x = x; // Refers to the instance variable\n",
- " }\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "2. **Passing the Current Object**: To pass the current instance to another method or constructor."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class MyClass {\n",
- " int x;\n",
- "\n",
- " public void setX(int x) {\n",
- " this.x = x;\n",
- " }\n",
- "\n",
- " public void updateX(MyClass obj) {\n",
- " obj.setX(this.x); // Passing the current object as an argument\n",
- " }\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "\n",
- "Using `this` helps to clarify which variables or methods are being accessed and ensures the correct context for operations on object data."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "\n",
- "Additional Resources:\n",
- "\n",
- "[Quizlet](https://quizlet.com/468453689/lecture-11-writing-classes-in-java-flash-cards/) \n",
- "[Runestone Academy](https://runestone.academy/ns/books/published/csjava/Unit6-Writing-Classes/toctree.html)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Hacks\n",
- "### Part 1"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class Rectangle {\n",
- " private double length;\n",
- " private double width;\n",
- "\n",
- " public Rectangle(double length, double width) {\n",
- " this.length = length;\n",
- " this.width = width;\n",
- " }\n",
- "\n",
- " public double getLength() {\n",
- " return length;\n",
- " }\n",
- "\n",
- " public double getWidth() {\n",
- " return width;\n",
- " }\n",
- "\n",
- " public void setLength(double length) {\n",
- " this.length = length;\n",
- " }\n",
- "\n",
- " public void setWidth(double width) {\n",
- " this.width = width;\n",
- " }\n",
- "\n",
- " public double calculateArea() {\n",
- " return length * width;\n",
- " }\n",
- "}\n",
- "\n",
- "public class Main {\n",
- " public static void main(String[] args) {\n",
- " Rectangle rect1 = new Rectangle(5.0, 3.0);\n",
- " Rectangle rect2 = rect1;\n",
- " rect2.setWidth(4.0);\n",
- " System.out.println(\"Area of rect1: \" + rect1.calculateArea());\n",
- " }\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Answer the following questions based on the code above:\n",
- "* a) What is the output of the `System.out.println(\"Area of rect1: \" + rect1.calculateArea())` statement? Explain why.\n",
- "* Answer: \n",
- "* b) Do `rect1` and `rect2` refer to the same memory location? Explain your answer.\n",
- "* Answer: "
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Part 2\n",
- "Situation: You are designing a system to manage employee records in a company. You need to create a class `Employee` and another class `Company` to manage multiple employees.\n",
- "\n",
- "(a) Write a class `Employee` with private instance variables for `name`, `id`, and `salary`. Include a constructor to initialize these variables, accessor methods to retrieve their values, and mutator methods to update them.\n",
- "\n",
- "(b) Explain how encapsulation is achieved in the `Employee` class. What is the role of accessor and mutator methods in achieving encapsulation?\n",
- "\n",
- "(c) Code:\n",
- "\n",
- "Create a class `Company` that contains an array of `Employee` objects. Include a method `addEmployee(Employee newEmployee)` to add a new employee to the array. Write the method signature and implementation, including comments to explain 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": "19.0.2+7-44"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/backup_summer_2024/2024-06-24-unit_6.ipynb b/_notebooks/CSA/units_1_to_10/backup_summer_2024/2024-06-24-unit_6.ipynb
deleted file mode 100644
index 81c62ff5..00000000
--- a/_notebooks/CSA/units_1_to_10/backup_summer_2024/2024-06-24-unit_6.ipynb
+++ /dev/null
@@ -1,1183 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "toc: true\n",
- "title: Unit 6 - Arrays\n",
- "description: Arrays Lesson\n",
- "authors: Aniket Chakradeo, Soham Kamat\n",
- "categories: [AP CSA]\n",
- "permalink: /unit6lesson\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# Topic 6.1 - Array Creation and Access "
- ]
- },
- {
- "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": null,
- "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": null,
- "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": null,
- "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": null,
- "metadata": {},
- "outputs": [],
- "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": null,
- "metadata": {},
- "outputs": [],
- "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": null,
- "metadata": {},
- "outputs": [],
- "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)\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 _ to the number of elements - _. "
- ]
- },
- {
- "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": [
- "![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": [
- "### Things to Consider\n",
- "\n",
- "1. 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",
- "2. What about odd? "
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 5,
- "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? "
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "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",
- "__________________________________"
- ]
- },
- {
- "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? The first index is 0 making the equation invalid. You must change the signs or add a -1"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 6,
- "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": 7,
- "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": 8,
- "metadata": {},
- "outputs": [
- {
- "ename": "CompilationException",
- "evalue": "",
- "output_type": "error",
- "traceback": [
- "\u001b[1m\u001b[30m| \u001b[1m\u001b[30m\u001b[0m\u001b[1m\u001b[30m\u001b[41m\u001b[0m\u001b[1m\u001b[30m[0, 1, 2, 3, 4]\u001b[0m",
- "\u001b[1m\u001b[31millegal start of expression\u001b[0m",
- ""
- ]
- }
- ],
- "source": [
- "[0, 1, 2, 3, 4]"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 9,
- "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": 10,
- "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": [
- "// 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": 11,
- "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 quotes;\n",
- " private List emotions;\n",
- "\n",
- " public Quote(List quotes, List emotions) {\n",
- " this.quotes = quotes;\n",
- " this.emotions = emotions;\n",
- " }\n",
- "\n",
- " public void printQuotesWithEmotions() {\n",
- " // Make a change in the code here! \n",
- " for (int i = 0; i < quotes.size() && i < emotions.size(); i++) {\n",
- " String quote = quotes.get(i);\n",
- " String emotion = emotions.get(i);\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?"
- ]
- },
- {
- "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": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "ArrayList names = new ArrayList<>();\n",
- "String searchName = \"Vivian\";\n",
- "\n",
- "//code goes here\n",
- "for () {\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",
- "\n",
- "//code goes here\n",
- "for () {\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# 6.4: Developing Algorithms Using Arrays \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": null,
- "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": 6,
- "metadata": {},
- "outputs": [],
- "source": [
- "// What needs to be changed to find the index of the max value? (write correct code in cell below)\n",
- "// new code\n",
- "private int findMaxIndex(double[] values) {\n",
- " int maxIndex = 0;\n",
- " double maxValue = values[0];\n",
- "\n",
- " for (int i = 1; i < values.length; i++) {\n",
- " if (values[i] > maxValue) {\n",
- " maxValue = values[i];\n",
- " maxIndex = i;\n",
- " }\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",
- "- Yes\n",
- "**Can you declare the variable inside the loop?**\n",
- "- Yes and usually good practice to do so as it avoids confusion"
- ]
- },
- {
- "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",
- "- For loop so that way you get the desired output"
- ]
- },
- {
- "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",
- "- To calculate the wrapped around index"
- ]
- },
- {
- "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": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "String [] words = {\"alpha\", \"beta\", \"gamma\", \"delta\"};\n",
- "int shiftWord = 2;\n",
- "\n",
- "//new code\n",
- "String[] shiftedWords = new String[words.length];\n",
- "for (int i = 0; i < words.length; i++) {\n",
- " shiftedWords[i] = words[(i + shiftWord) % words.length];\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "**Why should the array index be wrapped in a call to Math.abs?**\n",
- "- To make sure the index remains positive"
- ]
- },
- {
- "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\n",
- "\n",
- "- E. 3-6-4"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Write why you chose that answer! \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(int i = 0; i < numbers.length; i+=2)\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\n",
- "\n",
- "- E. int 1 = 0; i < numbers.length; i+=2"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Write why you chose that answer! \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\n",
- "\n",
- "- A. Change loop condition to: i < arr.length - 1"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "In case you are having trouble with question 3 the answer is B. Write about why! \n",
- "\n",
- "_______________________________"
- ]
- }
- ],
- "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": "11.0.20+8-post-Ubuntu-1ubuntu122.04"
- },
- "orig_nbformat": 4
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/backup_summer_2024/2024-06-29-unit_7.ipynb b/_notebooks/CSA/units_1_to_10/backup_summer_2024/2024-06-29-unit_7.ipynb
deleted file mode 100644
index a5a371c4..00000000
--- a/_notebooks/CSA/units_1_to_10/backup_summer_2024/2024-06-29-unit_7.ipynb
+++ /dev/null
@@ -1,1310 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "toc: true\n",
- "title: Unit 7 - Arraylists\n",
- "description: ArrayLists Lesson\n",
- "authors: Aniket Chakradeo, Soham Kamat\n",
- "categories: [AP CSA]\n",
- "permalink: /unit7lesson\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",
- " //Initialize your ArrayLists\n",
- " \n",
- " }\n",
- "}\n",
- "\n",
- "// new code\n",
- "public class Student {\n",
- " public static void main(String[] args) {\n",
- " // Initialize the ArrayLists\n",
- " List studentNames = new ArrayList<>();\n",
- " List studentAges = 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": null,
- "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": null,
- "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": 3,
- "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": null,
- "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?"
- ]
- },
- {
- "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": null,
- "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": null,
- "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": null,
- "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",
- " - 0 because there are 0 items in the array list\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",
- " - the add() method is a void method which doesnt return anything and simply adds stuff to the array\n",
- " * Look back at Example 1. What two lines did we remove? Why?\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",
- "- 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 Helper"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 2,
- "metadata": {},
- "outputs": [
- {
- "ename": "CompilationException",
- "evalue": "",
- "output_type": "error",
- "traceback": [
- "\u001b[1m\u001b[30m| \u001b[1m\u001b[30m private String manipulateList(/* You can put parameters here if you want to... */) \u001b[0m\u001b[1m\u001b[30m\u001b[41m{\u001b[0m",
- "\u001b[1m\u001b[30m| \u001b[1m\u001b[30m\u001b[41m // Your code here\u001b[0m",
- "\u001b[1m\u001b[30m| \u001b[1m\u001b[30m\u001b[41m }\u001b[0m",
- "\u001b[1m\u001b[31mmissing return statement\u001b[0m",
- ""
- ]
- }
- ],
- "source": [
- "public class ArrayListMethodsExample {\n",
- " private String manipulateList(/* You can put parameters here if you want to... */) {\n",
- " // Your code here\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",
- "}"
- ]
- },
- {
- "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": 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",
- " 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"
- ]
- },
- {
- "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": 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",
- " ArrayList grades = new ArrayList<>();\n",
- " grades.add(68.9);\n",
- " grades.add(71);\n",
- " grades.add(100);\n",
- " grades.add(80);\n",
- " for(int i = 0; i<=; i){\n",
- " if(grades.get(i)<70){\n",
- " ???\n",
- " }\n",
- " }\n",
- " System.out.println(grades);\n",
- " }\n",
- "}"
- ]
- },
- {
- "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": "code",
- "execution_count": 13,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Grand Total: 60\n"
- ]
- }
- ],
- "source": [
- "import java.util.ArrayList;\n",
- "\n",
- "public class OrderTotalCalculator {\n",
- " public static void main(String[] args) {\n",
- " // Create an ArrayList of orders\n",
- " ArrayList orders = new ArrayList<>();\n",
- " \n",
- " // Add some sample orders to the list\n",
- " orders.add(new Order(\"Product A\", 10));\n",
- " orders.add(new Order(\"Product B\", 20));\n",
- " orders.add(new Order(\"Product C\", 30));\n",
- " \n",
- " // Calculate the total cost of all orders\n",
- " int totalCost = 0;\n",
- " for (Order order : orders) {\n",
- " totalCost += order.getPrice();\n",
- " }\n",
- " \n",
- " System.out.println(\"Grand Total: \" + totalCost);\n",
- " }\n",
- "}\n",
- "\n",
- "class Order {\n",
- " private String name;\n",
- " private int price;\n",
- " \n",
- " public Order(String name, int price) {\n",
- " this.name = name;\n",
- " this.price = price;\n",
- " }\n",
- " \n",
- " public String getName() {\n",
- " return name;\n",
- " }\n",
- " \n",
- " public int getPrice() {\n",
- " return price;\n",
- " }\n",
- "}\n",
- "\n",
- "OrderTotalCalculator.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."
- ]
- },
- {
- "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:"
- ]
- },
- {
- "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:"
- ]
- },
- {
- "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`."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Hack Helper"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "public class ArrayListHacks {\n",
- " private int findSum(ArrayList values) {\n",
- " // Your code here\n",
- " return 0;\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": null,
- "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."
- ]
- }
- ],
- "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": "11.0.20.1+1-post-Ubuntu-0ubuntu122.04"
- },
- "orig_nbformat": 4
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/backup_summer_2024/2024-07-02-unit_8.ipynb b/_notebooks/CSA/units_1_to_10/backup_summer_2024/2024-07-02-unit_8.ipynb
deleted file mode 100644
index f90353aa..00000000
--- a/_notebooks/CSA/units_1_to_10/backup_summer_2024/2024-07-02-unit_8.ipynb
+++ /dev/null
@@ -1,1407 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "toc: true\n",
- "title: Unit 8 - 2D Arrays\n",
- "description: 2D Arrays Lesson\n",
- "authors: Aniket Chakradeo, Soham Kamat\n",
- "categories: [AP CSA]\n",
- "permalink: /unit8lesson\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Learning Objectives\n",
- "\n",
- "The objective of this lesson is to...\n",
- "\n",
- "- Learn about 2D arrays, their use cases, and how to create them.\n",
- "\n",
- "## Essential Knowledge\n",
- "\n",
- "College Board wants you to know...\n",
- "\n",
- "- How to declare/initialize 2D arrays.\n",
- "- How to determine their size.\n",
- "- How to access and update the values of a 2D array.\n",
- "- How to traverse/access elements of a 2D array using nested iteration statements. \n",
- "- How nested iteration statements can be used to traverse 2D arrays in “row-major order” vs “column-major order.”\n",
- "- How to create algorithms that require the use of 2D array traversals."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Warm Up\n",
- "\n",
- "Answer the following questions as a group or individually. Write down your answers in your hacks notebook.\n",
- "\n",
- "- What are 2D arrays?\n",
- "\n",
- "2D Arrays are arrays with an extra dimension. They are data structures in Java.\n",
- "\n",
- "- How are 2D arrays organized?\n",
- "\n",
- "2D arrays are organized into rows and columns in a matrix format. There are two indices, one for rows and one for columns.\n",
- "\n",
- "- What are some real-world examples of 2D arrays?\n",
- "\n",
- "Some real-world examples of 2D arrays can be spreadsheets or maybe image processing."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## The Basics/Recap\n",
- "\n",
- "2D arrays, and higher dimension arrays overall, can be thought of as just an array that's made up of other arrays or an array of arrays. One way of looking at 2D arrays is by thinking of them as a chess board. They have rows and columns, and every element is identified via row or column number or index.\n",
- "\n",
- "Below is an illustration of a 2D array:\n",
- "![2D Array Image](https://raw.githubusercontent.com/The-Code-Monkeys/Monkeys38/main/images/2dArray.png)\n",
- "\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 1) How to declare/initialize 2D arrays\n",
- "\n",
- "Initializing 2D arrays can be done in multiple different ways. Note: In Java whenever we declare an array we must specify the datatype of the elements in the array. The most common include:"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "1) Initializing and populating the array in one go:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 8,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "1 2 3 \n",
- "4 5 6 \n",
- "7 8 9 \n"
- ]
- }
- ],
- "source": [
- "public class Main {\n",
- " public static void main(String[] args) {\n",
- " int[][] Array1 = { // 2d Array of integers\n",
- " {1, 2, 3},\n",
- " {4, 5, 6},\n",
- " {7, 8, 9}\n",
- " };\n",
- "\n",
- " for (int i = 0; i < Array1.length; i++) { // Loop through the rows\n",
- " for (int j = 0; j < Array1[i].length; j++) { // Loop through the columns\n",
- " System.out.print(Array1[i][j] + \" \"); // Print out the element\n",
- " }\n",
- " System.out.println(); // Print a new line\n",
- " }\n",
- " }\n",
- "}\n",
- "\n",
- "Main.main(null)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 9,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "one two three \n",
- "four five six \n",
- "seven eight nine \n"
- ]
- }
- ],
- "source": [
- "public class Main {\n",
- " public static void main(String[] args){\n",
- " String[][] Array2 = { // 2d Array of strings\n",
- " {\"one\", \"two\", \"three\"},\n",
- " {\"four\", \"five\", \"six\"},\n",
- " {\"seven\", \"eight\", \"nine\"}\n",
- " };\n",
- " \n",
- " for (int i = 0; i < Array2.length; i++) { // Loop through the rows\n",
- " for (int j = 0; j < Array2[i].length; j++) { // Loop through the columns\n",
- " System.out.print(Array2[i][j] + \" \"); // Print out the element\n",
- " }\n",
- " System.out.println(); // Print a new line\n",
- " }\n",
- " }\n",
- "}\n",
- "\n",
- "Main.main(null)\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 10,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "1 two 3.0 \n",
- "4 five 6.0 \n",
- "7 eight 9.0 \n"
- ]
- }
- ],
- "source": [
- "public class Main {\n",
- " public static void main(String[] args){\n",
- " Object[][] Array3 = { // 2d Array of objects allows for having varying types in the same 2d array\n",
- " {1, \"two\", 3.0},\n",
- " {4, \"five\", 6.0},\n",
- " {7, \"eight\", 9.0}\n",
- " };\n",
- "\n",
- " for (int i = 0; i < Array3.length; i++) { // Loop through the rows\n",
- " for (int j = 0; j < Array3[i].length; j++) { // Loop through the columns\n",
- " System.out.print(Array3[i][j] + \" \"); // Print out the element\n",
- " }\n",
- " System.out.println(); // Print a new line\n",
- " }\n",
- " }\n",
- "} \n",
- "\n",
- "Main.main(null)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "2) Creating an empty 2D array and then assigning values to individual elements as through accessing and changing each value via their corresponding row and column index: "
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 11,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "1 2 3 \n",
- "4 5 6 \n",
- "7 8 9 \n"
- ]
- }
- ],
- "source": [
- "public class Main {\n",
- " public static void main(String[] args){\n",
- " int[][] myArray = new int[3][3]; // Defines the size of the array, think of the first number as x and the second number as y, for rows and columns.\n",
- " \n",
- " myArray[0][0] = 1; // Maps the desired value to a specific point in the array, think of this as an (x,y) coordinate.\n",
- " myArray[0][1] = 2;\n",
- " myArray[0][2] = 3;\n",
- " myArray[1][0] = 4;\n",
- " myArray[1][1] = 5;\n",
- " myArray[1][2] = 6;\n",
- " myArray[2][0] = 7;\n",
- " myArray[2][1] = 8;\n",
- " myArray[2][2] = 9;\n",
- "\n",
- " for (int i = 0; i < myArray.length; i++) { // Loop through the rows\n",
- " for (int j = 0; j < myArray[i].length; j++) { // Loop through the columns\n",
- " System.out.print(myArray[i][j] + \" \"); // Print out the element\n",
- " }\n",
- " System.out.println(); // Print a new line\n",
- " }\n",
- " }\n",
- "}\n",
- "\n",
- "Main.main(null)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "3) Using a nested loop to manually populate each element:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 12,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "0 1 2 3 \n",
- "4 5 6 7 \n",
- "8 9 10 11 \n"
- ]
- }
- ],
- "source": [
- "public class Main {\n",
- " public static void main(String[] args){\n",
- " int rows = 3; // Define number of rows and columns here as variables\n",
- " int columns = 4;\n",
- " int[][] myArray = new int[rows][columns]; // Create an array based on the values of the aforementioned variables.\n",
- " // Create a nested for loop that iterates based on the number of rows and columns.\n",
- " for (int i = 0; i < rows; i++) { \n",
- " for (int j = 0; j < columns; j++) {\n",
- " // You can assign values to each element here\n",
- " myArray[i][j] = i * columns + j;\n",
- "\n",
- " }\n",
- " }\n",
- " // Print out the array\n",
- " for (int i = 0; i < myArray.length; i++) { // Loop through the rows\n",
- " for (int j = 0; j < myArray[i].length; j++) { // Loop through the columns\n",
- " System.out.print(myArray[i][j] + \" \"); // Print out the element\n",
- " }\n",
- " System.out.println(); // Print a new line\n",
- " }\n",
- " }\n",
- "}\n",
- "\n",
- "Main.main(null)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Popcorn Hack: Create a 2D Array with random values"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 19,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "3 96 17 \n",
- "16 40 65 \n",
- "86 69 75 \n"
- ]
- }
- ],
- "source": [
- "import java.util.Random;\n",
- "\n",
- "public class Main {\n",
- " public static void main(String[] args){\n",
- " int[][] example = new int[3][3];\n",
- " Random rand = new Random();\n",
- "\n",
- " for(int i = 0; i < example.length; i++) {\n",
- " for (int j = 0; j < example[i].length; j++) {\n",
- " example[i][j] = rand.nextInt(100+1);\n",
- " System.out.print(example[i][j] + \" \");\n",
- " }\n",
- " System.out.println();\n",
- " }\n",
- " }\n",
- "\n",
- "}\n",
- "Main.main(null)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 2) Accessing and updating the values of a 2D array\n",
- "\n",
- "In order to access the value of a 2D array, you must use array indexing notation, which is as follows:\n",
- "\n",
- "```java\n",
- "// Say you have myArray:\n",
- "int[][] myArray = {\n",
- " {1, 2, 3},\n",
- " {4, 5, 6},\n",
- " {7, 8, 9}\n",
- "};\n",
- "\n",
- "// To access the third number of the third column, use array indexing notation:\n",
- "int desiredValue = myArray[2][2]; // REMEMBER BASE 0!\n",
- "\n",
- "// And print the value:\n",
- "System.out.print(desiredValue);\n",
- "```\n",
- "Assign the \"coordinate point\" of the desired value as a variable, using the \"x\" value for row number and \"y\" value for column number."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 13,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "9"
- ]
- }
- ],
- "source": [
- "// Executable Version:\n",
- "public class Main {\n",
- " public static void main(String[] args) {\n",
- " int[][] myArray = {\n",
- " {1, 2, 3},\n",
- " {4, 5, 6},\n",
- " {7, 8, 9}\n",
- " };\n",
- "\n",
- " int desiredValue = myArray[2][2];\n",
- "\n",
- " System.out.print(desiredValue);\n",
- "\n",
- " }\n",
- "}\n",
- "\n",
- "Main.main(null)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "In order to update the value of a specific point in a 2D array, assign the desired value to a specific point in the array, denoted by array indexing notation:\n",
- "\n",
- "```java\n",
- "// Say you have myArray:\n",
- "int[][] myArray = {\n",
- " {1, 2, 3},\n",
- " {4, 5, 6},\n",
- " {7, 8, 9}\n",
- "};\n",
- "\n",
- "// To change the third number of the third column, use array indexing notation:\n",
- "int desiredValue = 10; // Define what you want the new value to be.\n",
- "myArray[2][2] = desiredValue; // Use array indexing notation to insert the desired value at the specific desired point.\n",
- "\n",
- "// And print the updated value at the desired location:\n",
- "System.out.print(myArray[2][2]);\n",
- "```"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 14,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "10"
- ]
- }
- ],
- "source": [
- "// Executable Version:\n",
- "public class Main {\n",
- " public static void main(String[] args) {\n",
- " int[][] myArray = {\n",
- " {1, 2, 3},\n",
- " {4, 5, 6},\n",
- " {7, 8, 9}\n",
- " };\n",
- "\n",
- " int desiredValue = 10; \n",
- " myArray[2][2] = desiredValue; \n",
- "\n",
- " System.out.print(myArray[2][2]);\n",
- "\n",
- " }\n",
- "}\n",
- "\n",
- "Main.main(null)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Popcorn Hack: Print all the values on this 2D Array and update the last value to be 12."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 9,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "1 2 3 \n",
- "4 5 6 \n",
- "7 8 12 \n"
- ]
- }
- ],
- "source": [
- "// basic scaffolding to get you started :)\n",
- "public class Main {\n",
- " public static void main(String[] args) {\n",
- " int[][] myArray = {\n",
- " {1, 2, 3},\n",
- " {4, 5, 6},\n",
- " {7, 8, 9}\n",
- " };\n",
- " int value = 12;\n",
- " myArray[2][2] = value;\n",
- " for(int i = 0; i < myArray.length; i++) {\n",
- " for (int j = 0; j < myArray[i].length; j++) {\n",
- " System.out.print(myArray[i][j] + \" \");\n",
- " }\n",
- " System.out.println();\n",
- " }\n",
- " }\n",
- "}\n",
- "\n",
- "Main.main(null)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 3) Traversing 2D Arrays \n",
- "- When we traverse a regular array we use a singular for loop to iterate through each element in the array. However, when we have 2D array we need to use nested for loops to iterate through each element in the array. Below is the difference between the two:\n",
- "\n",
- "```java\n",
- "// Regular array traversal\n",
- "for(int i = 0; i < myArray.length; i++){\n",
- " System.out.println(myArray[i]);\n",
- "}\n",
- "\n",
- "// 2D array traversal\n",
- "for(int i = 0; i < myArray.length; i++){\n",
- " for(int j = 0; j < myArray[i].length; j++){\n",
- " System.out.println(myArray[i][j]);\n",
- " }\n",
- "}\n",
- "```"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 16,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "1D Array\n",
- "\n",
- "1 2 3 4 5 6 7 8 9 \n",
- "\n",
- "2D Array\n",
- "\n",
- "1 2 3 \n",
- "4 5 6 \n",
- "7 8 9 \n"
- ]
- }
- ],
- "source": [
- "public class Main {\n",
- " public static void main(String[] args){\n",
- " int[] myArray = {1, 2, 3, 4, 5, 6, 7, 8, 9}; // 1d array of integers\n",
- " int[][] my2dArray = { // 2d array of integers\n",
- " {1, 2, 3},\n",
- " {4, 5, 6},\n",
- " {7, 8, 9}\n",
- " };\n",
- " \n",
- " System.out.println(\"1D Array\\n\"); // Print a new line\n",
- "\n",
- " for (int i = 0; i < myArray.length; i++) { // Loop through the 1d array\n",
- " System.out.print(myArray[i] + \" \"); // Print out the element\n",
- " }\n",
- "\n",
- " System.out.println(\"\\n\\n2D Array\\n\"); // Print a new line\n",
- " \n",
- "\n",
- " for (int i = 0; i < my2dArray.length; i++) { // First traversal condition\n",
- " for (int j = 0; j < my2dArray[i].length; j++) { // Second traversal condition\n",
- " System.out.print(my2dArray[i][j] + \" \"); // Print out the element\n",
- " }\n",
- " System.out.println(); // Print a new line\n",
- " }\n",
- " }\n",
- "}\n",
- "\n",
- "Main.main(null)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Popcorn Hack: Traverse the following array and only print the values divisible by 7"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 14,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- " \n",
- "14 21 \n",
- " 28 70 \n"
- ]
- }
- ],
- "source": [
- "public class Main {\n",
- " public static void main(String[] args) {\n",
- " int[][] myArray = {\n",
- " {1, 2, 11},\n",
- " {14, 5, 21},\n",
- " {25, 28, 70}\n",
- " };\n",
- " for(int i = 0; i < myArray.length; i++) {\n",
- " for (int j = 0; j < myArray[i].length; j++) {\n",
- " if (myArray[i][j] % 7 == 0) {\n",
- " System.out.print(myArray[i][j] + \" \");\n",
- " } else {\n",
- " System.out.print(\" \");\n",
- " }\n",
- " }\n",
- " System.out.println();\n",
- " }\n",
- " }\n",
- "}\n",
- "\n",
- "Main.main(null)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Row-Major Order vs Column-Major Order\n",
- "\n",
- "### Row-Major-Order: \n",
- "- The outer loop traverses the rows and the inner loop traverses the columns or the elements within the rows. Here is an example bellow of row-major order traversals:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 18,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Row Major Order\n",
- "\n",
- "0 2 0 \n",
- "4 0 6 \n",
- "0 8 0 \n"
- ]
- }
- ],
- "source": [
- "public class rowMajorOrder {\n",
- " public static void main(String[] args){\n",
- " int[][] my2dArray = { // 2d array of integers\n",
- " {1, 2, 3},\n",
- " {4, 5, 6},\n",
- " {7, 8, 9}\n",
- " };\n",
- " \n",
- " System.out.println(\"Row Major Order\\n\"); // Print a new line\n",
- "\n",
- " for (int i = 0; i < my2dArray.length; i++) { // First traversal traverses by rows condition\n",
- "\n",
- " for (int j = 0; j < my2dArray[i].length; j++) { // Iterates through the columns\n",
- " if (my2dArray[i][j] % 2 == 0) { // If the element is even\n",
- " } else{\n",
- " my2dArray[i][j] = 0; // Otherwise set the element to 0\n",
- " }\n",
- " System.out.print(my2dArray[i][j] + \" \"); // Print out the element\n",
- " }\n",
- " System.out.println(); // Print a new line\n",
- " }\n",
- " }\n",
- "}\n",
- "\n",
- "rowMajorOrder.main(null)"
- ]
- },
- {
- "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": [
- "// Variation that only applies to forward row-wise major traversal\n",
- "\n",
- "public class rowMajorTraversalAlt{\n",
- " public static void rowMajorOrderAlt(int[][] array){\n",
- " for (int[] row: array){\n",
- " for (int element: row){\n",
- " System.out.print(element + \" \");\n",
- " }\n",
- " System.out.println();\n",
- " }\n",
- " }\n",
- "}\n",
- "\n",
- "rowMajorTraversalAlt.rowMajorOrderAlt(new int[][]{\n",
- " {1, 2, 3},\n",
- " {4, 5, 6},\n",
- " {7, 8, 9}\n",
- "});"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Column-Major-Order: \n",
- "- The outer loop will traverse through the columns and the inner loop will traverses through each element in the columns or the rows. Here is an example bellow of column-major order traversals: "
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 20,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Column Wise Traversal\n",
- "\n",
- "0 2 0 \n",
- "4 0 6 \n",
- "0 8 0 \n"
- ]
- }
- ],
- "source": [
- "public class columnWiseTraversal{\n",
- " public static void main(String[] args){\n",
- " int[][] my2dArray = { // 2d array of integers\n",
- " {1, 2, 3},\n",
- " {4, 5, 6},\n",
- " {7, 8, 9}\n",
- " };\n",
- " \n",
- " System.out.println(\"Column Wise Traversal\\n\"); // Print a new line\n",
- "\n",
- " for (int j = 0; j < my2dArray[0].length; j++) { // First traversal traverses by columns condition\n",
- "\n",
- " for (int i = 0; i < my2dArray.length; i++) { // Iterates through the rows\n",
- " if (my2dArray[j][i] % 2 == 0) { // If the element is even\n",
- " } else{\n",
- " my2dArray[j][i] = 0; // Otherwise set the element to 0\n",
- " }\n",
- " System.out.print(my2dArray[j][i] + \" \"); // Print out the element\n",
- " }\n",
- " System.out.println(); // Print a new line\n",
- " }\n",
- " }\n",
- "}\n",
- "\n",
- "columnWiseTraversal.main(null)\n",
- "\n",
- "// Both row and column wise traversals in our examples do the same thing, but in different orders. However for certain functions one may be easier to use than the other. \n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# Algoirthms 2D Array Java"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Linear search is a simple and sequential searching algorithm. It is used to find whether a particular element is present in the array or not by traversing every element in the array. While searching in the 2D array is exactly the same but here all the cells need to be traversed In this way, any element is searched in a 2D array. \n",
- "\n",
- "Below is the implementation for linear search in 2D arrays"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 16,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Element found at index: [1, 2]\n"
- ]
- }
- ],
- "source": [
- "// Linear Search in 2D arrays\n",
- "import java.util.Arrays;\n",
- " \n",
- "public class GFG {\n",
- " public static void main(String[] args)\n",
- " {\n",
- " int arr[][] = { { 3, 12, 9 },\n",
- " { 5, 2, 89 },\n",
- " { 90, 45, 22 } };\n",
- " int target = 89;\n",
- " int ans[] = linearSearch(arr, target);\n",
- " System.out.println(\"Element found at index: \"\n",
- " + Arrays.toString(ans));\n",
- " }\n",
- " \n",
- " static int[] linearSearch(int[][] arr, int target)\n",
- " {\n",
- " for (int i = 0; i < arr.length; i++) {\n",
- " for (int j = 0; j < arr[i].length; j++) {\n",
- " if (arr[i][j] == target) {\n",
- " return new int[] { i, j };\n",
- " }\n",
- " }\n",
- " }\n",
- " return new int[] { -1, -1 };\n",
- " }\n",
- "}\n",
- "GFG.main(null);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Summary:\n",
- "Linear Search involves iterating through all elements in the matrix.\n",
- "Binary Search is applicable when the matrix is sorted.\n",
- "Binary Search treats the 2D matrix as a 1D array by converting the indices.\n",
- "These searching algorithms are fundamental and widely used. Practice applying them to different scenarios to solidify your understanding. Additionally, consider exploring more advanced searching techniques for 2D arrays as you become more proficient."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 17,
- "metadata": {},
- "outputs": [],
- "source": [
- "public class Main {\n",
- " public static int[] binarySearch(int[][] matrix, int target) {\n",
- " int rows = matrix.length;\n",
- " int cols = matrix[0].length;\n",
- " int left = 0;\n",
- " int right = rows * cols - 1;\n",
- "\n",
- " while (left <= right) {\n",
- " int mid = left + (right - left) / 2;\n",
- " int midValue = matrix[mid / cols][mid % cols];\n",
- "\n",
- " if (midValue == target) {\n",
- " return new int[] {mid / cols, mid % cols};\n",
- " }\n",
- "\n",
- " if (midValue < target) {\n",
- " left = mid + 1;\n",
- " } else {\n",
- " right = mid - 1;\n",
- " }\n",
- " }\n",
- "\n",
- " return new int[] {-1, -1}; // Target not found\n",
- " }\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Binary Search in a 2D Array: \n",
- "\n",
- "Binary search is an efficient method of searching in an array. Binary search works on a sorted array. At each iteration the search space is divided in half, this is the reason why binary search is more efficient than linear search"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 18,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Element found at index: [2, 3]\n"
- ]
- }
- ],
- "source": [
- "// Binary Search on sorted 2D array\n",
- "import java.util.Arrays;\n",
- " \n",
- "class GFG {\n",
- " \n",
- " static int[] findAns(int[][] arr, int target)\n",
- " {\n",
- " int row = 0;\n",
- " int col = arr[row].length - 1;\n",
- " while (row < arr.length && col >= 0) {\n",
- " if (arr[row][col] == target) {\n",
- " return new int[] { row, col };\n",
- " }\n",
- " \n",
- " // Target lies in further row\n",
- " if (arr[row][col] < target) {\n",
- " row++;\n",
- " }\n",
- " // Target lies in previous column\n",
- " else {\n",
- " col--;\n",
- " }\n",
- " }\n",
- " return new int[] { -1, -1 };\n",
- " }\n",
- " \n",
- " // Driver Code\n",
- " public static void main(String[] args)\n",
- " {\n",
- " \n",
- " // Binary search in sorted matrix\n",
- " int arr[][] = { { 1, 2, 3, 4 },\n",
- " { 5, 6, 7, 8 },\n",
- " { 9, 10, 11, 12 } };\n",
- " int[] ans = findAns(arr, 12);\n",
- " System.out.println(\"Element found at index: \"\n",
- " + Arrays.toString(ans));\n",
- " }\n",
- "}\n",
- "GFG.main(null);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Popcorn Hack - EXTRA!\n",
- "Create a program that implements binary search on 2D Arrays."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 43,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "10 13 2 \n",
- "3 12 18 \n",
- "17 4 19 \n",
- "\n",
- "The number 17 was found at index [2, 0]\n"
- ]
- }
- ],
- "source": [
- "import java.util.Random; \n",
- "import java.util.Arrays; \n",
- "\n",
- "public class BinarySearch {\n",
- " public static void main(String[] args) {\n",
- " int[][] array = new int [3][3];\n",
- " Random rand = new Random();\n",
- "\n",
- " for (int i = 0; i < array.length; i++) {\n",
- " for (int j = 0; j < array[i].length; j++) {\n",
- " array[i][j] = rand.nextInt(20+1);\n",
- " System.out.print(array[i][j] + \" \");\n",
- " }\n",
- " System.out.println();\n",
- " }\n",
- " System.out.println();\n",
- " int target = rand.nextInt(20+1);\n",
- " int[] answer = binarySearchAlgorithm(array, target);\n",
- "\n",
- " if (Arrays.equals(answer, new int[] {-1, -1})) {\n",
- " System.out.println(\"The number \" + target + \" was not found in the 2D Array\");\n",
- " } else {\n",
- " System.out.println(\"The number \" + target + \" was found at index \" + Arrays.toString(answer));\n",
- " }\n",
- " }\n",
- " public static int[] binarySearchAlgorithm(int[][] arr, int target) {\n",
- " int rows = arr.length;\n",
- " int columns = arr[0].length;\n",
- " int left = 0;\n",
- " int right = rows * columns - 1;\n",
- " if(rows == 0) {\n",
- " return new int[] {-1, -1};\n",
- " }\n",
- "\n",
- " while(left <= right) {\n",
- " int mid = left + (right - left) / 2;\n",
- " int midvalue = arr[mid / columns][mid % columns];\n",
- "\n",
- " if (midvalue == target) {\n",
- " return new int[] {mid / columns, mid % columns};\n",
- " } else if (midvalue < target) {\n",
- " left = mid + 1;\n",
- " } else {\n",
- " right = mid - 1;\n",
- " }\n",
- " }\n",
- " return new int[] {-1, -1};\n",
- " } \n",
- "}\n",
- "BinarySearch.main(null);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# Enhanced For-Each Loop for 2D Arrays \n",
- "Since 2D arrays are really arrays of arrays you can also use a nested enhanced for-each loop to loop through all elements in an array. We loop through each of the inner arrays and loop through all the values in each inner array. Notice the type of the outer loop array variable – it is an array that will hold each row, String[] in the example below for a 2D String array. The type of the variables in the for-each loops must match the type of the array. For-each loops are much simpler since you don’t have to use the indices and the []’s, but you can only use them if you are not going to change the values in an array of primitive types since the variable val below will not change the original array.\n",
- "\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "String[][] array;\n",
- "// Nested For-each loops that traverse a 2D String array\n",
- "for (String[] innerArray : array)\n",
- "{\n",
- " for (String val : innerArray)\n",
- " {\n",
- " System.out.println(val);\n",
- " }\n",
- "}"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 2,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "69.16666666666667\n"
- ]
- }
- ],
- "source": [
- "public class Average\n",
- "{\n",
- "\n",
- " public static double getAvg(int[][] a)\n",
- " {\n",
- " double total = 0;\n",
- " for (int[] innerArray : a)\n",
- " {\n",
- " for (int val : innerArray)\n",
- " {\n",
- " total = total + val;\n",
- " }\n",
- " }\n",
- " return total / (a.length * a[0].length);\n",
- " }\n",
- "\n",
- " public static void main(String[] args)\n",
- " {\n",
- " int[][] theArray = { {80, 90, 70}, {20, 80, 75}};\n",
- " System.out.println(getAvg(theArray));\n",
- " }\n",
- "}\n",
- "\n",
- "Average.main(null);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# 4) How to create an algorithm that involves traversing a 2D Array\n",
- "\n",
- "During the APCSA AP exam, we will be required to write an algorithm for a 2D array that solves a problem discussed in the prompt. Collegeboard will give you a situation, and you will have to write an algorithm based on said situation. \n",
- "\n",
- "Here's an example of an algorithm that was needed for the real Collegeboard APCSA exam in 2022:"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "For this problem, the question asked for the student to write the `countIncreasingCols` method, which returns the number of columns in `grid` that are in increasing order. `grid` is a 2D array with randomly populated numbers."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "public int countIncreaseCols() {\n",
- " int count = 0;\n",
- " for (int j = 0; j < grid[0].length; j++) { // Iterates through columns\n",
- " boolean isIncreasing = true; \n",
- " if (grid[0].length > 1) { // Checks if there is more than one column to prevent out of bounds error\n",
- " for (int i = 1; i < grid.length; i++) { // Iterates through rows\n",
- " if (grid[i][j] <= grid[i - 1][j]) { // Checks if the current element is less than or equal to the previous element\n",
- " isIncreasing = false; // If so set isIncreasing to false and break out of loop\n",
- " break; \n",
- " }\n",
- " }\n",
- " \n",
- " if (isIncreasing) { // If the column is increasing increment count as if \n",
- " count++; // the value is not less than or equal to the previous \n",
- " // element then it must be increasing \n",
- " }\n",
- " }\n",
- " \n",
- " else if (grid[0].length == 1) { // To match the criteria of a single column being increasing\n",
- " count++;\n",
- " }\n",
- " \n",
- " else { // If there are no columns then break out of loop\n",
- " break;\n",
- " }\n",
- " }\n",
- " return count; \n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# Hacks:"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### 1) \n",
- "Initialize a 5 x 5 2D array that is populated by random values."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 45,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "60 96 57 24 41 \n",
- "66 78 43 34 19 \n",
- "93 3 44 15 14 \n",
- "37 83 22 67 84 \n",
- "79 100 96 1 90 \n"
- ]
- }
- ],
- "source": [
- "// Add the code here:\n",
- "\n",
- "public class random2DA {\n",
- " public static void main(String[] args) {\n",
- " int[][] array = new int[5][5];\n",
- " Random rand = new Random();\n",
- "\n",
- " for(int i = 0; i < array.length; i++) {\n",
- " for (int j = 0; j < array[i].length; j++) {\n",
- " array[i][j] = rand.nextInt(101);\n",
- " System.out.print(array[i][j] + \" \");\n",
- " }\n",
- " System.out.println();\n",
- " }\n",
- " }\n",
- "}\n",
- "random2DA.main(null);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### 2)\n",
- "- a) Print the values 47, 51, and 20 by accessing them in the the given two-dimensional array.\n",
- "- b) Find the values from part a) using row major and column major order and print the values in each respective order."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 49,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Row Major order:\n",
- "47 51 20 \n",
- "Column Major order:\n",
- "47 51 20 "
- ]
- }
- ],
- "source": [
- "public class Problem2\n",
- "{\n",
- " public static void main(String[] args)\n",
- " {\n",
- " int[][] arr = { {47,3,12},{51,74,20} };\n",
- "\n",
- " System.out.println(\"Row Major order:\");\n",
- " for (int i = 0; i < arr.length; i++) {\n",
- " for (int j = 0; j < arr[i].length; j++) {\n",
- " if (arr[i][j] == 47 || arr[i][j] == 51 || arr[i][j] == 20) {\n",
- " System.out.print(arr[i][j] + \" \");\n",
- " }\n",
- " }\n",
- " }\n",
- " System.out.println(\"\\nColumn Major order:\");\n",
- " for (int j = 0; j < arr[0].length; j++) {\n",
- " for (int i = 0; i < arr.length; i++) {\n",
- " if (arr[i][j] == 47 || arr[i][j] == 51 || arr[i][j] == 20) {\n",
- " System.out.print(arr[i][j] + \" \");\n",
- " }\n",
- " }\n",
- " }\n",
- " }\n",
- "}\n",
- "Problem2.main(null);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### 3) \n",
- "The following 2d array `myArray` is populated with integers 1-9. Write an algorithm thath sorts the 2D array by column and returnst the values of the array in increaing order.\n",
- "\n",
- "The expected output is:\n",
- "`1 4 7` \n",
- "`2 5 8` \n",
- "`3 6 9` \n",
- "\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 54,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "1 4 7 \n",
- "2 5 8 \n",
- "3 6 9 \n"
- ]
- }
- ],
- "source": [
- "public class Problem3 {\n",
- " public static void main(String[] args) { \n",
- " int[][] myArray = { // 2d array of integers\n",
- " {1, 2, 3},\n",
- " {4, 5, 6},\n",
- " {7, 8, 9}\n",
- " };\n",
- " int numrows = myArray.length;\n",
- " int numcols = myArray[0].length;\n",
- "\n",
- " for (int j = 0; j < numcols; j++) {\n",
- " for (int i = 0; i < numrows; i++) {\n",
- " System.out.print(myArray[i][j] + \" \");\n",
- " }\n",
- " System.out.println();\n",
- " }\n",
- " }\n",
- "}\n",
- "Problem3.main(null);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### 4) \n",
- "Replace the “ADD CODE HERE” below with the code to declare and create a 3 by 3 two-dimensional int array named table. The finished code will print the values 0 to 8."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 60,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "0 1 2 \n",
- "3 4 5 \n",
- "6 7 8 \n"
- ]
- }
- ],
- "source": [
- "public class Test1\n",
- "{\n",
- "\n",
- " public static void main(String[] args)\n",
- " {\n",
- " // ADD CODE HERE //\n",
- " int[][] table = new int[3][3];\n",
- "\n",
- " // Should print the values in table\n",
- " int count = 0;\n",
- " for (int row = 0; row < table.length; row++)\n",
- " {\n",
- " for (int col = 0; col < table.length; col++)\n",
- " {\n",
- " table[row][col] = count;\n",
- " count++;\n",
- " System.out.print(table[row][col] + \" \");\n",
- " }\n",
- " System.out.println();\n",
- " }\n",
- " }\n",
- "}\n",
- "Test1.main(null);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### 5)\n",
- "Replace the “ADD CODE HERE” below with the code to declare and initialize a two-dimensional String array called students with the names “Brice, Marvin, Anna” in the first row and “Kamal, Maria, Elissa” in the second. The finished code will print all the names in the array starting with all in the first row followed by all in the second row."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 65,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Brice Marvin Anna \n",
- "Kamal Maria Elissa \n"
- ]
- }
- ],
- "source": [
- "public class Test1\n",
- "{\n",
- " public static void main(String[] args)\n",
- " {\n",
- " // ADD CODE HERE //\n",
- " String[][] students = {\n",
- " {\"Brice\", \"Marvin\", \"Anna\"},\n",
- " {\"Kamal\", \"Maria\", \"Elissa\"}\n",
- " };\n",
- "\n",
- " // Should print the values in students in order\n",
- " for (int row = 0; row < students.length; row++)\n",
- " {\n",
- " for (int col = 0; col < students[0].length; col++)\n",
- " {\n",
- " System.out.print(students[row][col] + \" \");\n",
- " }\n",
- " System.out.println();\n",
- " }\n",
- " }\n",
- "}\n",
- "Test1.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": "17.0.8+7-Ubuntu-120.04.2"
- },
- "orig_nbformat": 4
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/backup_summer_2024/2024-07-08-unit_9.ipynb b/_notebooks/CSA/units_1_to_10/backup_summer_2024/2024-07-08-unit_9.ipynb
deleted file mode 100644
index f9f5697f..00000000
--- a/_notebooks/CSA/units_1_to_10/backup_summer_2024/2024-07-08-unit_9.ipynb
+++ /dev/null
@@ -1,1669 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "toc: true\n",
- "title: Unit 9 - Inheritance\n",
- "description: Inheritance Lesson\n",
- "authors: Aniket Chakradeo, Soham Kamat\n",
- "categories: [AP CSA]\n",
- "permalink: /unit9lesson\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 9.1 Superclasses and Subclasses\n",
- "> A hierarchy of classes is created, extending attributes into subclasses of information (ie. Automobile --> Trucks and Sedans --> Ford, BMW, Nissan, Toyota). \n",
- "\n",
- "### Pre-Requisites\n",
- "\n",
- "Before we start you need to remember what classes and methods are. Scopes of variables are also important to this section because you need to know which classes can access which variables before extending a variable across classes.\n",
- "\n",
- "#### Scope of Variables:\n",
- "\n",
- "Variables can be declared as private or public.\n",
- "\n",
- "> **Popcorn Hack:** What are scope do private and public variables allow?\n",
- "\n",
- "Answer: Private variables can only be accessed within the class while public variables can be used globally.\n",
- "\n",
- "| Private | Public |\n",
- "|-|-|\n",
- "| only directly accessible within the class they are declared | accessible anywhere inside and outside their class |\n",
- "\n",
- "These are different types of variables. Only `INSTANCE` and `STATIC` variables can be declared as private or public.\n",
- "\n",
- "| Variable Type | Definition | Scope within Class | Scope to Subclasses |\n",
- "|-|-|-|-|\n",
- "| Local Variables | variables within methods | cannot be accessed outside method | cannot be accessed outside class |\n",
- "| Instance Variables | variables within a class but not inside a method | can be accessed in entire class | can be accessed in subclasses |\n",
- "| Static Variables | variables that belong to a class, not instance | can be accessed in entire class | can be accessed in subclasses |\n",
- "| Parameter Variables | variables specific in passing values to the method | cannot be accessed outside method | do not affect inheritance |\n",
- "\n",
- "Now we can go into class hierarchies."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Class Hierarchy\n",
- "\n",
- "**Definitions**\n",
- "- Superclasses - a class that contains all the common attributes and behaviors that could be shared among other classes (a blueprint for subclasses)\n",
- "- Subclasses - extends the behaviors to is specified by a superclass; can also have additional specific attributes\n",
- "- \"Is-A\" Relationship - the relationship when a subclass extends a superclass (ie. Automobile --> Sedan; a Sedan \"is-a\" automobile)\n",
- "\n",
- "#### `extends` Keyword\n",
- "> extends the subclass from the superclass"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 1,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Toyota\n",
- "Car is starting\n",
- "Ford\n",
- "1000\n",
- "Loading cargo into the truck\n",
- "BMW\n",
- "true\n",
- "Sedan is accelerating\n"
- ]
- }
- ],
- "source": [
- "class Automobile {\n",
- " public String brand; // public instance var\n",
- " private String model; // private instance var\n",
- "\n",
- " public Automobile(String brand, String model) {\n",
- " this.brand = brand;\n",
- " this.model = model;\n",
- " }\n",
- "\n",
- " public void start() {\n",
- " System.out.println(\"Car is starting\");\n",
- " }\n",
- "}\n",
- "\n",
- "class Truck extends Automobile {\n",
- " public int cargoCapacity; // subclass specific var\n",
- "\n",
- " // instance that is specific to the Truck subclass, with vars from Automobile class\n",
- " public Truck(String brand, String model, int cargoCapacity) {\n",
- " super(brand, model); // inherited vars\n",
- " this.cargoCapacity = cargoCapacity;\n",
- " }\n",
- "\n",
- " // specific method to Truck\n",
- " public void loadCargo() {\n",
- " System.out.println(\"Loading cargo into the truck\");\n",
- " }\n",
- "}\n",
- "\n",
- "class Sedan extends Automobile {\n",
- " public boolean isLuxury; // subclass specific var\n",
- "\n",
- " // instance that is specific to the Sedan subclass, with vars from Automobile class\n",
- " public Sedan(String brand, String model, boolean isLuxury) {\n",
- " super(brand, model); // inherited vars\n",
- " this.isLuxury = isLuxury;\n",
- " }\n",
- "\n",
- " // specific method to Sedan\n",
- " public void accelerate() {\n",
- " System.out.println(\"Sedan is accelerating\");\n",
- " }\n",
- "}\n",
- "\n",
- "public class Main {\n",
- " public static void main(String[] args) {\n",
- " Automobile car = new Automobile(\"Toyota\", \"Camry\");\n",
- " Truck truck = new Truck(\"Ford\", \"F-150\", 1000);\n",
- " Sedan sedan = new Sedan(\"BMW\", \"328i\", true);\n",
- "\n",
- " // automobile methods and variables\n",
- " System.out.println(car.brand); // Accessing public variable\n",
- " // System.out.println(car.model); // compilation error because of the private var\n",
- " car.start();\n",
- "\n",
- "\n",
- " // truck methods and variables\n",
- " System.out.println(truck.brand); // inherited public var\n",
- " System.out.println(truck.cargoCapacity); // public var specific to truck\n",
- " truck.loadCargo();\n",
- "\n",
- "\n",
- " // sedan methods and variables\n",
- " System.out.println(sedan.brand); // inherited public var\n",
- " System.out.println(sedan.isLuxury); // public var specific to sedan\n",
- " sedan.accelerate();\n",
- " }\n",
- "}\n",
- "\n",
- "Main.main(null);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "This example shows how the `Automobile` class is extended twice, with the `Truck` and `Sedan` subclasses.\n",
- "\n",
- "> **Popcorn Hack:** If I were to declare a variable `color` that is `private` in the class Automobile, would I be able to extend and directly access that variable to the subclass `Truck` or `Sedan`?\n",
- "\n",
- "A: No, you would need to encapsulate the private variable as shown above, through a method in the superclass and then inherit that var with `super()`, which will be explained later."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 9.2 Writing Constructors for Subclasses\n",
- "\n",
- "### Learning Objectives\n",
- "\n",
- "- Constructors are not inherited\n",
- "- When a subclass's constructor doesn't explicitly call a superclass's constructor using `super`, Java inserts a call to the superclass's no-argument constructor.\n",
- "- The actual parameters passed in the call to the superclass constructor provide values that the constructor can use to initialize the object's instance variables.\n",
- "- Regardless of whether the superclass constructor is called implicitly or explicitly, the process of calling superclass constructors continues until the Object constructor is called. At this point, all of the constructors within the hierarchy execute beginning with the Object constructor.\n",
- "\n",
- "**Important note:** Constructors are NOT inherited by the subclass. See this in action below."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 2,
- "metadata": {},
- "outputs": [],
- "source": [
- "// TO BE INCLUDED EARLIER IN THE LESSON. IT IS NECESSARY FOR THE FUNCTIONALITY OF THIS SECTION.\n",
- "\n",
- "class Vehicle {\n",
- " public int year;\n",
- " public String manufacturer;\n",
- "\n",
- " public Vehicle(int year, String manufacturer) { // constructor for parent class\n",
- " this.year = year;\n",
- " this.manufacturer = manufacturer;\n",
- " }\n",
- "\n",
- " public Vehicle() {\n",
- " this.year = 2000;\n",
- " this.manufacturer = \"Unknown\";\n",
- " }\n",
- "\n",
- " // method to be used later\n",
- " public void drive() {\n",
- " System.out.println(\"The driver is driving the car.\");\n",
- " }\n",
- "}"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 3,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Year: 2000\n",
- "Manufacturer: Unknown\n",
- "Model: Altima\n"
- ]
- }
- ],
- "source": [
- "class Car extends Vehicle {\n",
- " public String model;\n",
- "\n",
- " public Car(String model) {\n",
- " this.model = model;\n",
- " }\n",
- "}\n",
- "\n",
- "public class VehicleDemonstration {\n",
- " public static void main(String[] args) {\n",
- " Car myCar = new Car(\"Altima\");\n",
- " System.out.println(\"Year: \" + myCar.year);\n",
- " System.out.println(\"Manufacturer: \" + myCar.manufacturer);\n",
- " System.out.println(\"Model: \" + myCar.model);\n",
- " }\n",
- "}\n",
- "\n",
- "VehicleDemonstration.main(null);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "As you can see, the output uses the no-argument construction info from the base `Vehicle` constructor.\n",
- "\n",
- "The `super` keyword can be used to change parent constructor values."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 4,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Year: 2016\n",
- "Manufacturer: Nissan\n",
- "Model: Altima\n"
- ]
- }
- ],
- "source": [
- "class NewCar extends Vehicle {\n",
- " public String model;\n",
- "\n",
- " public NewCar(int year, String manufacturer, String model) {\n",
- " super(year, manufacturer); // see the use of super here\n",
- " // what happens if you use no arguments with super()? see reminders below\n",
- " this.model = model;\n",
- " }\n",
- "}\n",
- "\n",
- "public class VehicleDemonstration2 {\n",
- " public static void main(String[] args) {\n",
- " NewCar myCar = new NewCar(2016, \"Nissan\", \"Altima\");\n",
- " System.out.println(\"Year: \" + myCar.year);\n",
- " System.out.println(\"Manufacturer: \" + myCar.manufacturer);\n",
- " System.out.println(\"Model: \" + myCar.model);\n",
- " }\n",
- "}\n",
- "\n",
- "VehicleDemonstration2.main(null);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "#### Key Reminders:\n",
- "\n",
- "1. If you do call `super()` in your constructor, it has to be the first line of the constructor .\n",
- "2. You cannot assign values to parent attributes/variables without using `super()`.\n",
- "3. If you call `super()` with no arguments, it will use the no-argument parent constructor . This also happens automatically if you don't include any `super()` call.\n",
- "\n",
- "## 9.3 Overriding Methods\n",
- "\n",
- "### Learning Objectives\n",
- "\n",
- "- Method overriding occurs when a public method in a subclass has the same method signature as a public method in the superclass.\n",
- "- Any method that is called must be defined within its own class or its superclass.\n",
- "- A subclass is usually designed to have modified (overwritten) or additional methods or instance variables.\n",
- "- A subclass will inherit all public methods from the superclass; these methods remain public in the subclass.\n",
- "\n",
- "There are three options for methods to be used by subclasses:\n",
- "\n",
- "1. Methods inherited from the parent class\n",
- "2. Unique methods written for the subclass\n",
- "3. Override parent methods to modify its implementation\n",
- "\n",
- "The first two should make sense. Let's see an example of overriding parent methods below."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 5,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "This car is driving itself!\n"
- ]
- }
- ],
- "source": [
- "public class NuroCar extends Vehicle {\n",
- " private String deliveryItem;\n",
- "\n",
- " // unique constructor\n",
- " public NuroCar(int year, String manufacturer, String deliveryItem) {\n",
- " super(year, manufacturer); // another use of super\n",
- " this.deliveryItem = deliveryItem;\n",
- " }\n",
- "\n",
- " // HERE is the overridden function\n",
- " public void drive() {\n",
- " System.out.println(\"This car is driving itself!\");\n",
- " }\n",
- "}\n",
- "\n",
- "public class VehicleDemonstration3 {\n",
- " public static void main(String[] args) {\n",
- " NuroCar pizzaCar = new NuroCar(2023, \"Nuro\", \"Pizza\");\n",
- " // here's the call to the overridden function\n",
- " pizzaCar.drive();\n",
- " }\n",
- "}\n",
- "\n",
- "VehicleDemonstration3.main(null);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "This can be very helpful if you want a certain parent method to function slightly differently for a certain subclass.\n",
- "\n",
- "#### Popcorn Hack\n",
- "\n",
- "A parent class `Animal` is often used to show how subclasses can differ from their parent classes. An `Animal` parent class is provided in the cell below. Create a subclass of a certain species that overrides a parent method and uses `super` to call to the parent's constructor while adding its own unique attributes .\n",
- "\n",
- "Hint: See Hint \n",
- "Not all animals \"run\" like the `move()` function says...
\n",
- ""
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 4,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "The cheetah is 6 years old and runs at 75 miles per hour.\n"
- ]
- }
- ],
- "source": [
- "// parent class\n",
- "public class Animal {\n",
- " public String species;\n",
- " public int milesPerHour;\n",
- "\n",
- " // no argument constructor\n",
- " public Animal() {\n",
- " this.species = \"Unknown\";\n",
- " this.milesPerHour = 10;\n",
- " }\n",
- "\n",
- " // constructor with arguments\n",
- " public Animal(String species, int milesPerHour) {\n",
- " this.species = species;\n",
- " this.milesPerHour = milesPerHour;\n",
- " }\n",
- "\n",
- " // parent method\n",
- " public void move() {\n",
- " System.out.println(\"The \" + this.species.toLowerCase() + \" runs at \" + this.milesPerHour + \" miles per hour.\");\n",
- " }\n",
- "}\n",
- "\n",
- "// your subclass goes here\n",
- "public class Cheetah extends Animal {\n",
- " private int age;\n",
- "\n",
- " public Cheetah(String species, int milesPerHour, int age) {\n",
- " super(species, milesPerHour);\n",
- " this.age = age;\n",
- " }\n",
- "\n",
- " @Override\n",
- " public void move() {\n",
- " System.out.println(\"The \" + this.species.toLowerCase() + \" is \" + this.age + \" years old and runs at \" + this.milesPerHour + \" miles per hour.\");\n",
- " }\n",
- "}\n",
- "\n",
- "public class Main {\n",
- " public static void main(String[] args) {\n",
- " Cheetah anim = new Cheetah(\"Cheetah\", 75, 6);\n",
- " anim.move();\n",
- " }\n",
- "}\n",
- "Main.main(null);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 9.4 Super Keyword"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Using the super keyword to call a superclass's method."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 6,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "BalletDancer class: \n"
- ]
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Honing my craft!\n",
- "Leaping...\n",
- "Spinning...\n"
- ]
- }
- ],
- "source": [
- "public class Performer { //superclass\n",
- " public void practice(){\n",
- " System.out.println(\"Honing my craft!\");\n",
- " }\n",
- " public void perform(){\n",
- " System.out.println(\"Performing for an audience!\");\n",
- " }\n",
- "}\n",
- "\n",
- "public class Dancer extends Performer { //subclass\n",
- " public void perform(){\n",
- " System.out.println(\"Dancing on the stage!\");\n",
- " }\n",
- "}\n",
- "\n",
- "public class BalletDancer extends Dancer { //subclass\n",
- " public void jete(){\n",
- " System.out.println(\"Leaping...\");\n",
- " }\n",
- " public void pirouette(){\n",
- " System.out.println(\"Spinning...\");\n",
- " }\n",
- " public void perform(){\n",
- " jete();\n",
- " pirouette();\n",
- " }\n",
- " public static void main(String[] args){\n",
- " BalletDancer derrick = new BalletDancer();\n",
- " derrick.practice();\n",
- " derrick.perform();\n",
- " }\n",
- "}\n",
- "\n",
- "System.out.println(\"BalletDancer class: \");\n",
- "BalletDancer.main(null);"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 9,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "BalletDancer class: \n"
- ]
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Honing my craft!\n",
- "Leaping...\n",
- "Spinning...\n"
- ]
- }
- ],
- "source": [
- "public class Performer { //superclass of Dancer class\n",
- " public void practice(){\n",
- " System.out.println(\"Honing my craft!\");\n",
- " }\n",
- " public void perform(){\n",
- " System.out.println(\"Performing for an audience!\");\n",
- " }\n",
- "}\n",
- "\n",
- "public class Dancer extends Performer { //superclass of BalletDancer class\n",
- " public void perform(){\n",
- " System.out.println(\"Dancing on the stage!\");\n",
- " }\n",
- "}\n",
- "\n",
- "public class BalletDancer extends Dancer {\n",
- " public void jete(){\n",
- " System.out.println(\"Leaping...\");\n",
- " }\n",
- " public void pirouette(){\n",
- " System.out.println(\"Spinning...\");\n",
- " }\n",
- " public void perform(){ \n",
- " // got rid of perform() because it had stack overflow error\n",
- " jete();\n",
- " pirouette();\n",
- " }\n",
- " public static void main(String[] args){\n",
- " BalletDancer derrick = new BalletDancer();\n",
- " derrick.practice();\n",
- " derrick.perform();\n",
- " }\n",
- "}\n",
- "\n",
- "System.out.println(\"BalletDancer class: \");\n",
- "BalletDancer.main(null);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Note:\n",
- "Super keyword can be placed in any order as it prints out chronologically. "
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "public void perform(){ \n",
- " super.perform();\n",
- " jete();\n",
- " pirouette();\n",
- "}"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "\"Honing my craft!\n",
- "Dancing on the stage!\n",
- "Leaping...\n",
- "Spinning...\""
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "#### However, if we were to write:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "public void perform(){ \n",
- " jete();\n",
- " pirouette();\n",
- " super.perform();\n",
- "}"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "\"Honing my craft!\n",
- "Leaping...\n",
- "Spinning...\n",
- "Dancing on the stage!\""
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### What if we use 2 super keywords?"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 5,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "BalletDancer class: \n",
- "Honing my craft!\n",
- "Performing for an audience!\n",
- "Dancing on the stage!\n",
- "Leaping...\n",
- "Spinning...\n"
- ]
- }
- ],
- "source": [
- "public class Performer { //superclass\n",
- " public void practice(){\n",
- " System.out.println(\"Honing my craft!\");\n",
- " }\n",
- " public void perform(){\n",
- " System.out.println(\"Performing for an audience!\");\n",
- " }\n",
- "}\n",
- "\n",
- "public class Dancer extends Performer { //subclass\n",
- " public void perform(){\n",
- " super.perform();\n",
- " System.out.println(\"Dancing on the stage!\");\n",
- " }\n",
- "}\n",
- "\n",
- "public class BalletDancer extends Dancer { //subclass\n",
- " public void jete(){\n",
- " System.out.println(\"Leaping...\");\n",
- " }\n",
- " public void pirouette(){\n",
- " System.out.println(\"Spinning...\");\n",
- " }\n",
- " public void perform(){\n",
- " super.perform();\n",
- " jete();\n",
- " pirouette();\n",
- " }\n",
- " public static void main(String[] args){\n",
- " BalletDancer derrick = new BalletDancer();\n",
- " derrick.practice();\n",
- " derrick.perform();\n",
- " }\n",
- "}\n",
- "\n",
- "System.out.println(\"BalletDancer class: \");\n",
- "BalletDancer.main(null);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Popcorn Hack\n",
- "Create a subclass and a superclass by calling the methods from the superclass from the subclass using the keyword super.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 7,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Watching a movie!\n",
- "My heart is beating like crazy!\n"
- ]
- }
- ],
- "source": [
- "// place code here\n",
- "public class Movie {\n",
- " public void watch() {\n",
- " System.out.println(\"Watching a movie!\");\n",
- " }\n",
- "}\n",
- "\n",
- "public class ActionMovie extends Movie{\n",
- " public void watch() {\n",
- " super.watch();\n",
- " System.out.println(\"My heart is beating like crazy!\");\n",
- " }\n",
- " public static void main(String[] args) {\n",
- " ActionMovie movie = new ActionMovie();\n",
- " movie.watch();\n",
- " }\n",
- "}\n",
- "ActionMovie.main(null);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# 9.5 Creating References Using Inheritance Hierarchies"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Inheritance Hierarchies is the idea that:\n",
- "\n",
- "- If we have a public superclass (A) that then has a public subclass (B) and that public subclass then has another public subclass (C), then the subclass C is also a subclass of the superclass A and so subclass C is extending superclass A\n",
- "\n",
- "Here is an example of this:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 13,
- "metadata": {},
- "outputs": [],
- "source": [
- "// Class Declarations:\n",
- "\n",
- "// Superclass (A)\n",
- "public class Vehicles{}\n",
- "// Subclass (B)\n",
- "public class Car extends Vehicles{}\n",
- "// Subclass (C)\n",
- "public class Sedan extends Car{}\n",
- "// Subclass (D)\n",
- "public class Truck extends Vehicles{}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Here is a diagram displaying this relationship:\n",
- "\n",
- "![Inheritance Hierarchy Example](https://raw.githubusercontent.com/JishnuS420/BlogCSA/main/images/inheritance-hierarchy-example.png)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "- This diagram shows the the vehicle superclass which then has two subclasses: Car and Truck, however, Car has another subclass called Sedan\n",
- "\n",
- "- Based on this diagram, we know that Truck has a \"is-a\" relationship with Vehicle, Car also has a \"is-a\" relationship with Vehicle, and since Car has an \"is-a\" relationship with Vehicle, so does Sedan\n",
- "\n",
- "- So Sedan also has a \"is-a\" relationship with Vehicle\n",
- "\n",
- "If we assume that all of the class contain a constructor with no arguments, this then allows for us to declare a superclass reference variable to hold a subclass object:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 14,
- "metadata": {},
- "outputs": [],
- "source": [
- "Vehicles v1 = new Truck();\n",
- "Vehicles v2 = new Car();\n",
- "\n",
- "// instead of doing\n",
- "Car v3 = new Sedan();\n",
- "// We have the option to do this instead\n",
- "Vehicles v4 = new Sedan();"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "However, it is important to remember that you can't declare a Subclass variable and put in a Superclass object"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "// don't do this\n",
- "Sedan v5 = new Vehicle();"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- ">Popcorn Hack: Using a superclass and subclasses of your choice, assuming that the classes contain a constructor with no arguments, create Class Declarations and Superclass References"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 34,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Guitar Info:\n",
- "The Yamaha costs 449.99 dollars\n",
- "The Yamaha is made of Spruce Wood\n",
- "\n",
- "Bass Guitar Info\n",
- "The Fender costs 1179.99 dollars\n",
- "The Fender is made of Alder Wood\n",
- "The Fender weighs 9 pounds\n",
- "The Fender has a Blue color\n"
- ]
- }
- ],
- "source": [
- "// show here\n",
- "public class Instrument {\n",
- " public String brand;\n",
- " public double cost;\n",
- "\n",
- " public Instrument() {\n",
- " this.brand = \"unknown\";\n",
- " this.cost = 0.0;\n",
- " }\n",
- " public Instrument(String brand, double cost) {\n",
- " this.brand = brand;\n",
- " this.cost = cost;\n",
- " }\n",
- " public void play() {\n",
- " System.out.println(\"The \" + brand + \" costs \" + cost + \" dollars\");\n",
- " }\n",
- "}\n",
- "public class Guitar extends Instrument {\n",
- " private String material;\n",
- "\n",
- " public Guitar(String brand, double cost, String material) {\n",
- " super(brand, cost);\n",
- " this.material = material;\n",
- " }\n",
- "\n",
- " @Override\n",
- " public void play() {\n",
- " super.play();\n",
- " System.out.println(\"The \" + brand + \" is made of \" + material);\n",
- " }\n",
- "}\n",
- "public class BassGuitar extends Guitar {\n",
- " private int weight;\n",
- " private String color;\n",
- "\n",
- " public BassGuitar(String brand, double cost, String material, int weight, String color) {\n",
- " super(brand, cost, material);\n",
- " this.weight = weight;\n",
- " this.color = color;\n",
- " }\n",
- "\n",
- " @Override\n",
- " public void play() {\n",
- " super.play();\n",
- " System.out.println(\"The \" + brand + \" weighs \" + weight + \" pounds\");\n",
- " System.out.println(\"The \" + brand + \" has a \" + color + \" color\");\n",
- " }\n",
- "}\n",
- "\n",
- "public class Main {\n",
- " public static void main(String[] args) {\n",
- " Instrument inst1 = new Guitar(\"Yamaha\", 449.99, \"Spruce Wood\");\n",
- " Instrument inst2 = new BassGuitar(\"Fender\", 1179.99, \"Alder Wood\", 9, \"Blue\");\n",
- "\n",
- " System.out.println(\"Guitar Info:\");\n",
- " inst1.play();\n",
- " System.out.println();\n",
- " System.out.println(\"Bass Guitar Info\");\n",
- " inst2.play();\n",
- " }\n",
- "}\n",
- "Main.main(null)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Why would we want to do this?"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "- When doing object oriented programming, we are able to create a superclass with common attributes and then have subclasses with more specific traits \n",
- "\n",
- "- By doing this, we get rid of code redundancy and it also makes the easier to reuse common aspects without needing to write them out every time while still presenting the option to override any attribute from the superclass to better represent the subclass\n",
- "\n",
- "- All the subclasses adhere to one superclass so this makes updates to code much easier and allows you to take advantage of **polymorphism** to unify the code and allow for more flexible and manageable code (more about this in 9.6)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Here is a Complete Example of the Inheritance Hierarchy from above:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 9,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Truck Information:\n",
- "Brand: Ford\n",
- "Year: 2023\n",
- "Max Load Capacity: 10.5 tons\n",
- "\n",
- "Car Information:\n",
- "Brand: Toyota\n",
- "Year: 2023\n",
- "Number of Doors: 4\n",
- "\n",
- "Sedan Information:\n",
- "Brand: Honda\n",
- "Year: 2023\n",
- "Number of Doors: 4\n",
- "Leather Seats: true\n"
- ]
- }
- ],
- "source": [
- "class Vehicle {\n",
- " private String brand; // private instance variable\n",
- " private int year; // private instance variable\n",
- "\n",
- " public Vehicle(String brand, int year) {\n",
- " this.brand = brand;\n",
- " this.year = year;\n",
- " }\n",
- "\n",
- " public void displayInfo() { // common variables for each vehicle\n",
- " System.out.println(\"Brand: \" + brand);\n",
- " System.out.println(\"Year: \" + year);\n",
- " }\n",
- "}\n",
- "\n",
- "class Truck extends Vehicle {\n",
- " // feature that only a truck can have\n",
- " private double maxLoadCapacity;\n",
- "\n",
- " public Truck(String brand, int year, double maxLoadCapacity) {\n",
- " super(brand, year); // Inherits the variables from superclass\n",
- " this.maxLoadCapacity = maxLoadCapacity;\n",
- " }\n",
- "\n",
- " @Override // Override allows for displayInfo to now also show the trait specific to the Truck while still keeping the main variables\n",
- " public void displayInfo() {\n",
- " super.displayInfo(); // Reuse the displayInfo method from the superclass\n",
- " System.out.println(\"Max Load Capacity: \" + maxLoadCapacity + \" tons\");\n",
- " }\n",
- "}\n",
- "\n",
- "class Car extends Vehicle {\n",
- " // something that cars have\n",
- " private int numberOfDoors;\n",
- "\n",
- " public Car(String brand, int year, int numberOfDoors) {\n",
- " super(brand, year);\n",
- " this.numberOfDoors = numberOfDoors;\n",
- " }\n",
- "\n",
- " @Override // Override allows for displayInfo to now also show the trait specific to the Car while still keeping the main variables\n",
- " public void displayInfo() {\n",
- " super.displayInfo(); // Reuse the displayInfo method from the superclass\n",
- " System.out.println(\"Number of Doors: \" + numberOfDoors);\n",
- " }\n",
- "}\n",
- "\n",
- "class Sedan extends Car {\n",
- " // Sedan is luxury so trait specific to sedan\n",
- " private boolean leatherSeats;\n",
- "\n",
- " public Sedan(String brand, int year, int numberOfDoors, boolean leatherSeats) {\n",
- " super(brand, year, numberOfDoors);\n",
- " this.leatherSeats = leatherSeats;\n",
- " }\n",
- "\n",
- " @Override // Override allows for displayInfo to now also show the trait specific to the Sedan while still keeping the main variables\n",
- " public void displayInfo() {\n",
- " super.displayInfo(); // Reuse the displayInfo method from the superclass\n",
- " System.out.println(\"Leather Seats: \" + leatherSeats);\n",
- " }\n",
- "}\n",
- "\n",
- "public class Main {\n",
- " public static void main(String[] args) {\n",
- " Vehicle v1 = new Truck(\"Ford\", 2023, 10.5);\n",
- " Vehicle v2 = new Car(\"Toyota\", 2023, 4);\n",
- " Vehicle v3 = new Sedan(\"Honda\", 2023, 4, true);\n",
- "\n",
- " System.out.println(\"Truck Information:\");\n",
- " v1.displayInfo();\n",
- " \n",
- " System.out.println(\"\\nCar Information:\");\n",
- " v2.displayInfo();\n",
- " \n",
- " System.out.println(\"\\nSedan Information:\");\n",
- " v3.displayInfo();\n",
- " }\n",
- "}\n",
- "Main.main(null)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- ">Popcorn Hack: In your own words describe the importance of Inheritance Hierarchies\n",
- "\n",
- "Answer: Inheritance Hierarchies are important because they enable the reuse of common attributes or behaviors and also gets rid of code redundancy. They also allow the updating of code to be much easier."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# 9.6 Polymorphism\n",
- "\n",
- "## Learning Objectives\n",
- "MOD-3.D : Call methods in an inheritance relationship. \n",
- "MOD-3.D.1 : Utilize the Object class through inheritance. \n",
- "MOD-3.D.2 : At compile time, methods in or inherited by the declared type determine the correctness of a non-static method call. \n",
- "MOD-3.D.3 : At run-time, the method in the actual object type is executed for a non-static method call. \n",
- "\n",
- "## What is Polymorphism?\n",
- "**Polymorphism** is a greek word meaning many-formed (poly=many, morph=form). In the context of programming, Polymorphic behavior is defined as being able to reference objects of different types at different points during compilation. \n",
- "\n",
- "One example of Java polymorphism, is our ability to store references to objects instantiated from any class AND its *subclasses* in a variable. Another example is for methods, where we override the behavior of a method in a subclass such that it differs from the parent class. We successfully perform polymorphism when we override non-static methods and execute them from the correct, corresponding class at runtime. \n",
- "\n",
- "Here is a simple example of polymorphism:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 17,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Drawing a circle\n",
- "Drawing a rectangle\n"
- ]
- }
- ],
- "source": [
- "// This is our Parent class\n",
- "class Shape {\n",
- " public void draw() {\n",
- " System.out.println(\"Drawing a shape\");\n",
- " }\n",
- "}\n",
- "\n",
- "// Subclass 1\n",
- "class Circle extends Shape {\n",
- " @Override\n",
- " public void draw() {\n",
- " System.out.println(\"Drawing a circle\");\n",
- " }\n",
- "}\n",
- "\n",
- "// Subclass 2\n",
- "class Rectangle extends Shape {\n",
- " @Override\n",
- " public void draw() {\n",
- " System.out.println(\"Drawing a rectangle\");\n",
- " }\n",
- "}\n",
- "\n",
- "public class Main {\n",
- " public static void main(String[] args) {\n",
- " \n",
- " // Here we have reference variables circle and rectangle defined with static type \"Shape\"\n",
- " Shape circle = new Circle(); // Circle has dynamic type \"Circle\"\n",
- " Shape rectangle = new Rectangle(); // Rectangle has dynamic type \"Rectangle\"\n",
- " \n",
- " // Calling the draw() method\n",
- " circle.draw(); // Output: Drawing a circle\n",
- " rectangle.draw(); // Output: Drawing a rectangle\n",
- " }\n",
- "}\n",
- "\n",
- "Main.main(null);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Even though the circle and rectangle have identical data-types, the compiler knows to call the correct method at run-time. We have successfully performed polymorphism"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Popcorn hack\n",
- "1. Create any example of polymorphism, perferably with a class from your project, with corresponding methods and attributes as well."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 20,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "What is the capital of France?\n",
- "1. Paris\n",
- "2. Berlin\n",
- "3. Madrid\n",
- "4. Rome\n",
- "Is the Earth round?\n",
- "Which planet is known as the Red Planet?\n",
- "1. Mars\n",
- "2. Venus\n",
- "3. Jupiter\n",
- "4. Saturn\n"
- ]
- }
- ],
- "source": [
- "// Program your code here\n",
- "class Question {\n",
- " private String questionText;\n",
- "\n",
- " public Question(String questionText) {\n",
- " this.questionText = questionText;\n",
- " }\n",
- "\n",
- " public void display() {\n",
- " System.out.println(questionText);\n",
- " }\n",
- "\n",
- " public boolean checkAnswer(String userAnswer) {\n",
- " return false;\n",
- " }\n",
- "}\n",
- "\n",
- "class MultipleChoiceQuestion extends Question {\n",
- " private String[] choices;\n",
- " private int correctChoiceIndex;\n",
- "\n",
- " public MultipleChoiceQuestion(String questionText, String[] choices, int correctChoiceIndex) {\n",
- " super(questionText);\n",
- " this.choices = choices;\n",
- " this.correctChoiceIndex = correctChoiceIndex;\n",
- " }\n",
- "\n",
- " @Override\n",
- " public void display() {\n",
- " super.display();\n",
- " for (int i = 0; i < choices.length; i++) {\n",
- " System.out.println((i + 1) + \". \" + choices[i]);\n",
- " }\n",
- " }\n",
- "\n",
- " @Override\n",
- " public boolean checkAnswer(String userAnswer) {\n",
- " int userChoice = Integer.parseInt(userAnswer);\n",
- " return userChoice == (correctChoiceIndex + 1);\n",
- " }\n",
- "}\n",
- "\n",
- "class TrueFalseQuestion extends Question {\n",
- " private boolean correctAnswer;\n",
- "\n",
- " public TrueFalseQuestion(String questionText, boolean correctAnswer) {\n",
- " super(questionText);\n",
- " this.correctAnswer = correctAnswer;\n",
- " }\n",
- "\n",
- " @Override\n",
- " public boolean checkAnswer(String userAnswer) {\n",
- " return userAnswer.equalsIgnoreCase(Boolean.toString(correctAnswer));\n",
- " }\n",
- "}\n",
- "\n",
- "public class Main {\n",
- " public static void main(String[] args) {\n",
- " Question[] questions = new Question[3];\n",
- " questions[0] = new MultipleChoiceQuestion(\"What is the capital of France?\",\n",
- " new String[]{\"Paris\", \"Berlin\", \"Madrid\", \"Rome\"}, 0);\n",
- " questions[1] = new TrueFalseQuestion(\"Is the Earth round?\", true);\n",
- " questions[2] = new MultipleChoiceQuestion(\"Which planet is known as the Red Planet?\",\n",
- " new String[]{\"Mars\", \"Venus\", \"Jupiter\", \"Saturn\"}, 0);\n",
- "\n",
- " for (Question question : questions) {\n",
- " question.display();\n",
- " }\n",
- " }\n",
- "}\n",
- "Main.main(null);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Static and Dynamic types\n",
- "Typically in Java, a reference variable storing an object instantiated from a child class can only store other objects of that class. If we try to store an object of another class, we'd get an error i.e. \n",
- "\n",
- "```java\n",
- "Integer myNumber = new Integer(6); // Instantiates an Integer object\n",
- "System.out.println(myNumber); // Would print Integer type 6 normally\n",
- "myNumber = new Double(6.1); // Compile error occurs, incompatible types\n",
- "System.out.println(myNumber); // This line is not reached\n",
- "``` \n",
- "\n",
- "But what if we want want a reference variable to store objects of other classes? We get an error"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Popcorn Hack\n",
- "1. Given these lines of code, identify the static and dynamic variables in each scenario"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "Animal myPet = new Dog();\n",
- "Object1 thing = new Object2();\n",
- "Vehicle myRide = new Helicopter();"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Answers\n",
- "Static Variables: `Animal`, `Object1`, `Vehicle`\n",
- "\n",
- "Dynamic Variables: `Dog`, `Object2`, `Helicopter`"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Compile-time vs Runtime methods\n",
- "Sometimes, when we perform polymorphism, we have to be careful to distinguish between our **compile time** and **run-time** methods. When we instantiate a dynamic variable that is of *a different type* from our static variable, our program at run time will attempt to search for the methods and attributes in the superclass, NOT the child class that we created. Although the compiled program will still output the correct outputs of the method in the child class, it will not be able to find a method that exists in the child class but not in the parent class. \n",
- "\n",
- "To resolve this issue, we need use **Down-casting**.\n",
- " - **Downcasting**: Essentially telling the compiler to refer to a variable's subclass (the programmer specifies this), instead of the static type. We are telling the compiler to search our dynamic type for the methods and attributes that we want to access.\n",
- "\n",
- "Below is an example of compile versus run-time methods and downcasting that I used in our group's project."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 18,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "GraphNode[value=1,edges={2=7, 3=2, 4=10}]\n",
- "GraphNode[value=1,edges={2=7, 3=2, 4=10, 5=6}]\n"
- ]
- }
- ],
- "source": [
- "import java.util.HashMap;\n",
- "// This is our parent class for all child classes that make up a graph\n",
- "public class GraphObject {\n",
- " private int value;\n",
- "\n",
- " // constructor\n",
- " public GraphObject(int value) {\n",
- " this.value = value;\n",
- " }\n",
- "\n",
- " // getter method\n",
- " public int getValue() {\n",
- " return this.value;\n",
- " }\n",
- "\n",
- " // setter method\n",
- " public void setValue(int value) {\n",
- " this.value = value;\n",
- " }\n",
- "\n",
- " // Method overloading to print object to terminal\n",
- " @Override\n",
- " public String toString() {\n",
- " return Integer.toString(this.value);\n",
- " }\n",
- "}\n",
- "\n",
- "// This is our child class. Represents a vertex or a node in a graph\n",
- "public class GraphNode extends GraphObject {\n",
- " private HashMap edges; // Hashmap of destination vertices and weights of paths \n",
- "\n",
- " // Constructor of child class\n",
- " public GraphNode(int value, HashMap edges){\n",
- " super(value); // super keyword to run constructor of parent class, which sets the value of the node\n",
- " this.edges = edges; // adds any needed edges\n",
- " }\n",
- "\n",
- " public HashMap getEdges() {\n",
- " return this.edges;\n",
- " }\n",
- "\n",
- " public void addEdge(int targetId, int weight) {\n",
- " this.edges.put(targetId, weight);\n",
- " }\n",
- "\n",
- " public void removeEdge(int targetId) {\n",
- " this.edges.remove(targetId);\n",
- " }\n",
- " \n",
- " // Overloading the toString method of the parent class, using super to get the output of the parent class\n",
- " @Override\n",
- " public String toString() {\n",
- " return \"GraphNode[value=\" + super.toString() + \",edges=\" + this.edges + \"]\";\n",
- " }\n",
- "} \n",
- "HashMap node1Connections = new HashMap();\n",
- "node1Connections.put(2, 7);\n",
- "node1Connections.put(3, 2);\n",
- "node1Connections.put(4, 10);\n",
- "GraphObject node1 = new GraphNode(1, node1Connections);\n",
- "System.out.println(node1.toString());\n",
- "((GraphNode)node1).addEdge(5,6); // Here, we downcast node1, which is a GraphObject, to what it references, which is GraphNode\n",
- "// node1.addEdge(5,6); // This wouldn't work as the compiler attempts to find addEdge() in GraphObject, which it can't, throwing an error \n",
- "System.out.println(node1.toString());"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# Popcorn Hacks\n",
- "1. Define each of the following terms in your own words\n",
- " - **Downcasting** - Casting an object reference from a superclass to a subclass.\n",
- " - **Static Type** - A variable that cannot change during the program's execution.\n",
- " - **Dynamic Type** - A variable that can be changed during the program's execution.\n",
- " - **Polymorphism** - Allows objects of different classes to be treated as objects of common superclass.\n",
- " - **Compile-time method** - A method that is determined and bound at compile time.\n",
- " - **Run-time method** - Method that is determined and bound at runtime."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# 9.7 Object Superclass"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "- The Object class is the superclass of all other classes as well as data types and is a part of the java.lang package\n",
- "\n",
- "- If a parent class doesn't specify by using the `extends` keyword, the class will inherit from the Object \n",
- "\n",
- "- `String toString()` and `boolean equals(object other)` are the most frequently used and subclasses of Object override the equals and toString methods by using class-specific implementations\n",
- "\n",
- "Normally when you use the `toString` method without overriding it, it returns a hash code value as seen in the example below:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 24,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "REPL.$JShell$63E$Person@2376aa49\n"
- ]
- }
- ],
- "source": [
- "class Person {\n",
- " private String name;\n",
- " private int age;\n",
- "\n",
- " public Person(String name, int age) {\n",
- " this.name = name;\n",
- " this.age = age;\n",
- " }\n",
- "}\n",
- "\n",
- "public class ToStringNoOverride {\n",
- " public static void main(String[] args) {\n",
- " Person person = new Person(\"Alice\", 25);\n",
- " // When you print this out, it will return the hash code since its using the default method for toString\n",
- " System.out.println(person);\n",
- " }\n",
- "}\n",
- "ToStringNoOverride.main(null)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "However, we can fix this by creating a new method by **overriding** the normal `toString` method and building our own representation of the object"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 26,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Person Name: Alice\n",
- "Person Age: 25\n"
- ]
- }
- ],
- "source": [
- "class Person {\n",
- " private String name;\n",
- " private int age;\n",
- "\n",
- " public Person(String name, int age) {\n",
- " this.name = name;\n",
- " this.age = age;\n",
- " }\n",
- "\n",
- " @Override\n",
- " public String toString() { // We override the toString method here\n",
- " return \"Person Name: \" + name + \"\\nPerson Age: \" + age; // We then add our own custom string representation\n",
- " }\n",
- "}\n",
- "\n",
- "public class ToStringOverride {\n",
- " public static void main(String[] args) {\n",
- " Person person = new Person(\"Alice\", 25);\n",
- "\n",
- " // When you print the person object, it calls the overridden toString method we made\n",
- " System.out.println(person);\n",
- " }\n",
- "}\n",
- "ToStringOverride.main(null)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Now, we want to compare 2 people by using `boolean equals(Object other)` and determine if they are the same"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 27,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Person 1 Age equals Person 2 Age: false\n"
- ]
- }
- ],
- "source": [
- "class Person {\n",
- " private String name;\n",
- " private int age;\n",
- "\n",
- " public Person(String name, int age) {\n",
- " this.name = name;\n",
- " this.age = age;\n",
- " }\n",
- "\n",
- " @Override\n",
- " public String toString() {\n",
- " return \"Person Name: \" + name + \"\\nPerson Age: \" + age;\n",
- " }\n",
- "}\n",
- "\n",
- "public class EqualsNoOverride {\n",
- " public static void main(String[] args) {\n",
- " Person person1 = new Person(\"Alice\", 25);\n",
- " Person person2 = new Person(\"Bryce\", 25);\n",
- "\n",
- " System.out.println(\"Person 1 Age equals Person 2 Age: \" + person1.equals(person2)); // use the equals method to compare the two people\n",
- " }\n",
- "}\n",
- "EqualsNoOverride.main(null)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "False is returned when you use the `boolean equals(Object other)` because the parameters is of Type Object superclass is unable to detect them since the Object class saves them under two different memory addresses and to fix this, we have to make an override method for this.\n",
- "\n",
- "To do this, we use `instanceof` and casting"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 28,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Person 1 Age equals Person 2 Age: true\n"
- ]
- }
- ],
- "source": [
- "class Person {\n",
- " private String name;\n",
- " private int age;\n",
- "\n",
- " public Person(String name, int age) {\n",
- " this.name = name;\n",
- " this.age = age;\n",
- " }\n",
- "\n",
- " @Override // We override the equals method\n",
- " public boolean equals(Object other) {\n",
- " if (!(other instanceof Person)) // Using instanceof, we are making sure that the we compare objects of the same class\n",
- " return false;\n",
- " Person that = (Person) other; // Here we perform casting to make sure that other is converted to Person\n",
- " return this.age == that.age;\n",
- " }\n",
- "\n",
- " @Override\n",
- " public String toString() {\n",
- " return \"Person Name: \" + name + \"\\nPerson Age: \" + age;\n",
- " }\n",
- "}\n",
- "\n",
- "public class EqualsOverride {\n",
- " public static void main(String[] args) {\n",
- " Person person1 = new Person(\"Alice\", 25);\n",
- " Person person2 = new Person(\"Bryce\", 25);\n",
- "\n",
- " System.out.println(\"Person 1 Age equals Person 2 Age: \" + person1.equals(person2));\n",
- " }\n",
- "}\n",
- "EqualsOverride.main(null)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Hacks\n",
- "\n",
- "Create a superclass with at least 2 subclasses based on your own topic.\n",
- "\n",
- "- Create a DrawIO diagram for your structure and label them with superclasses and subclasses\n",
- "- Create a superclass on your own topic\n",
- "- Create at least two subclasses\n",
- "- Each class must create at least two methods, one private and public variable, and examples of local, static, instance, and parameter variables\n",
- "- Override at least one method\n",
- "- Use the `super` keyword at least once"
- ]
- }
- ],
- "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": "17.0.8+7-Ubuntu-120.04.2"
- },
- "orig_nbformat": 4
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/backup_summer_2024/units_1_to_10_examples/2024-06-24-unit_2_examples.ipynb b/_notebooks/CSA/units_1_to_10/backup_summer_2024/units_1_to_10_examples/2024-06-24-unit_2_examples.ipynb
deleted file mode 100644
index 894efc61..00000000
--- a/_notebooks/CSA/units_1_to_10/backup_summer_2024/units_1_to_10_examples/2024-06-24-unit_2_examples.ipynb
+++ /dev/null
@@ -1,145 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "toc: true\n",
- "title: Unit 2 - Using Objects Examples\n",
- "description: Using Objects Examples\n",
- "authors: Aniket Chakradeo, Soham Kamat\n",
- "menu: nav/CSA_Units/csa_unit2.html\n",
- "type: ccc\n",
- "permalink: /unit2lessonexamples\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Simple Object Creation and Method Invocation Example"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "// Define a class named Car\n",
- "class Car {\n",
- " // Attributes of the Car class\n",
- " String make;\n",
- " String model;\n",
- " int year;\n",
- "\n",
- " // Constructor for initializing Car objects\n",
- " Car(String make, String model, int year) {\n",
- " this.make = make;\n",
- " this.model = model;\n",
- " this.year = year;\n",
- " }\n",
- "\n",
- " // Method to display car details\n",
- " void displayDetails() {\n",
- " System.out.println(\"Car Make: \" + make);\n",
- " System.out.println(\"Car Model: \" + model);\n",
- " System.out.println(\"Car Year: \" + year);\n",
- " }\n",
- "}\n",
- "\n",
- "public class Main {\n",
- " public static void main(String[] args) {\n",
- " // Create a Car object using the constructor\n",
- " Car myCar = new Car(\"Toyota\", \"Corolla\", 2020);\n",
- "\n",
- " // Call the method to display car details\n",
- " myCar.displayDetails();\n",
- " }\n",
- "}\n",
- "\n",
- "Main.main(null);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Object Interaction and Passing Objects as Arguments Example"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "// Define a class named Rectangle\n",
- "class Rectangle {\n",
- " // Attributes of the Rectangle class\n",
- " double length;\n",
- " double width;\n",
- "\n",
- " // Constructor to initialize Rectangle objects\n",
- " Rectangle(double length, double width) {\n",
- " this.length = length;\n",
- " this.width = width;\n",
- " }\n",
- "\n",
- " // Method to calculate the area of the rectangle\n",
- " double calculateArea() {\n",
- " return length * width;\n",
- " }\n",
- "}\n",
- "\n",
- "// Define a class named AreaCalculator\n",
- "class AreaCalculator {\n",
- " // Method to calculate and display the area of a Rectangle object\n",
- " void printArea(Rectangle rect) {\n",
- " double area = rect.calculateArea();\n",
- " System.out.println(\"Area of the rectangle: \" + area);\n",
- " }\n",
- "}\n",
- "\n",
- "public class Main {\n",
- " public static void main(String[] args) {\n",
- " // Create a Rectangle object\n",
- " Rectangle myRectangle = new Rectangle(5.0, 3.5);\n",
- "\n",
- " // Create an AreaCalculator object\n",
- " AreaCalculator calculator = new AreaCalculator();\n",
- "\n",
- " // Pass the Rectangle object to the printArea method\n",
- " calculator.printArea(myRectangle);\n",
- " }\n",
- "}\n",
- "\n",
- "Main.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": "19.0.2+7-44"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/backup_summer_2024/units_1_to_10_examples/2024-06-24-unit_3_examples.ipynb b/_notebooks/CSA/units_1_to_10/backup_summer_2024/units_1_to_10_examples/2024-06-24-unit_3_examples.ipynb
deleted file mode 100644
index da17dd92..00000000
--- a/_notebooks/CSA/units_1_to_10/backup_summer_2024/units_1_to_10_examples/2024-06-24-unit_3_examples.ipynb
+++ /dev/null
@@ -1,115 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "toc: true\n",
- "title: Unit 3 - Boolean Expressions and if Statements Examples\n",
- "description: Boolean Expressions and if Statements Examples\n",
- "authors: Aniket Chakradeo, Soham Kamat\n",
- "menu: nav/CSA_Units/csa_unit3.html\n",
- "type: ccc\n",
- "permalink: /unit3lessonexamples\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Simple if Statement with Boolean Expression Example"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "public class Main {\n",
- " public static void main(String[] args) {\n",
- " int age = 18;\n",
- " \n",
- " // Check if age is greater than or equal to 18\n",
- " if (age >= 18) {\n",
- " System.out.println(\"You are eligible to vote.\");\n",
- " } else {\n",
- " System.out.println(\"You are not eligible to vote.\");\n",
- " }\n",
- " }\n",
- "}\n",
- "\n",
- "Main.main(null);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Nested if Statements with Complex Boolean Expressions Example"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "public class Main {\n",
- " public static void main(String[] args) {\n",
- " int score = 85;\n",
- " boolean hasGoodAttendance = true;\n",
- "\n",
- " // Check if score is greater than or equal to 90\n",
- " if (score >= 90) {\n",
- " System.out.println(\"Grade: A\");\n",
- " } \n",
- " // Check if score is between 80 and 89 inclusive\n",
- " else if (score >= 80 && score < 90) {\n",
- " // Check for good attendance\n",
- " if (hasGoodAttendance) {\n",
- " System.out.println(\"Grade: B+\");\n",
- " } else {\n",
- " System.out.println(\"Grade: B\");\n",
- " }\n",
- " } \n",
- " // Check if score is between 70 and 79 inclusive\n",
- " else if (score >= 70 && score < 80) {\n",
- " System.out.println(\"Grade: C\");\n",
- " } \n",
- " // If score is below 70\n",
- " else {\n",
- " System.out.println(\"Grade: F\");\n",
- " }\n",
- " }\n",
- "}\n",
- "\n",
- "Main.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": "19.0.2+7-44"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/backup_summer_2024/units_1_to_10_examples/2024-06-24-unit_4_examples.ipynb b/_notebooks/CSA/units_1_to_10/backup_summer_2024/units_1_to_10_examples/2024-06-24-unit_4_examples.ipynb
deleted file mode 100644
index 2e848c97..00000000
--- a/_notebooks/CSA/units_1_to_10/backup_summer_2024/units_1_to_10_examples/2024-06-24-unit_4_examples.ipynb
+++ /dev/null
@@ -1,137 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "toc: true\n",
- "title: Unit 4 - Iterations Examples\n",
- "description: Iteration Examples\n",
- "authors: Aniket Chakradeo, Soham Kamat\n",
- "menu: nav/CSA_Units/csa_unit4.html\n",
- "type: ccc\n",
- "permalink: /unit4lessonexamples\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Iterating with a `for` Loop Example"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "public class Main {\n",
- " public static void main(String[] args) {\n",
- " // An array of integers\n",
- " int[] numbers = {12, 7, 19, 4, 21, 8, 14};\n",
- "\n",
- " // Use a for loop to iterate over the array\n",
- " for (int i = 0; i < numbers.length; i++) {\n",
- " int number = numbers[i];\n",
- "\n",
- " // Check if the number is even or odd\n",
- " if (number % 2 == 0) {\n",
- " System.out.println(\"Number \" + number + \" is even.\");\n",
- " } else {\n",
- " System.out.println(\"Number \" + number + \" is odd.\");\n",
- " }\n",
- "\n",
- " // Additional check for numbers greater than 10\n",
- " if (number > 10) {\n",
- " System.out.println(\"Number \" + number + \" is greater than 10.\");\n",
- " } else {\n",
- " System.out.println(\"Number \" + number + \" is less than or equal to 10.\");\n",
- " }\n",
- "\n",
- " // Separator for clarity in the output\n",
- " System.out.println(\"-----------------------\");\n",
- " }\n",
- " }\n",
- "}\n",
- "\n",
- "Main.main(null);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Refrence Types Example"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "public class Main {\n",
- " public static void main(String[] args) {\n",
- " Scanner scanner = new Scanner(System.in);\n",
- " int sum = 0;\n",
- " int count = 0;\n",
- "\n",
- " // Continue to ask the user for input until they enter a negative number\n",
- " while (true) {\n",
- " System.out.print(\"Enter a positive number (or a negative number to stop): \");\n",
- " int number = scanner.nextInt();\n",
- "\n",
- " // Check if the entered number is negative\n",
- " if (number < 0) {\n",
- " break; // Exit the loop\n",
- " }\n",
- "\n",
- " // Accumulate the sum\n",
- " sum += number;\n",
- " count++;\n",
- "\n",
- " // Print the current total\n",
- " System.out.println(\"Current total sum: \" + sum);\n",
- " }\n",
- "\n",
- " // Check if any numbers were entered\n",
- " if (count > 0) {\n",
- " System.out.println(\"You entered \" + count + \" numbers. Final sum is: \" + sum);\n",
- " } else {\n",
- " System.out.println(\"No positive numbers were entered.\");\n",
- " }\n",
- "\n",
- " scanner.close(); // Close the scanner to prevent resource leaks\n",
- " }\n",
- "}\n",
- "\n",
- "Main.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": "19.0.2+7-44"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/backup_summer_2024/units_1_to_10_examples/2024-06-24-unit_5_examples.ipynb b/_notebooks/CSA/units_1_to_10/backup_summer_2024/units_1_to_10_examples/2024-06-24-unit_5_examples.ipynb
deleted file mode 100644
index 54d5f158..00000000
--- a/_notebooks/CSA/units_1_to_10/backup_summer_2024/units_1_to_10_examples/2024-06-24-unit_5_examples.ipynb
+++ /dev/null
@@ -1,162 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "toc: true\n",
- "title: Unit 5 - Writing Classes Examples\n",
- "description: Writing Classes Examples\n",
- "authors: Aniket Chakradeo, Soham Kamat\n",
- "menu: nav/CSA_Units/csa_unit5.html\n",
- "type: ccc\n",
- "permalink: /unit5lessonexamples\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Primitive Types Example"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "// Define a class named Person\n",
- "class Person {\n",
- " // Attributes of the Person class\n",
- " String name;\n",
- " int age;\n",
- " String address;\n",
- "\n",
- " // Constructor to initialize Person objects\n",
- " Person(String name, int age, String address) {\n",
- " this.name = name;\n",
- " this.age = age;\n",
- " this.address = address;\n",
- " }\n",
- "\n",
- " // Method to display the details of the person\n",
- " void displayDetails() {\n",
- " System.out.println(\"Name: \" + name);\n",
- " System.out.println(\"Age: \" + age);\n",
- " System.out.println(\"Address: \" + address);\n",
- " }\n",
- "\n",
- " // Method to calculate the birth year based on age\n",
- " int calculateBirthYear() {\n",
- " int currentYear = 2024;\n",
- " return currentYear - age;\n",
- " }\n",
- "}\n",
- "\n",
- "public class Main {\n",
- " public static void main(String[] args) {\n",
- " // Create an object of the Person class\n",
- " Person person1 = new Person(\"Alice\", 30, \"123 Main St, Springfield\");\n",
- "\n",
- " // Call methods on the object\n",
- " person1.displayDetails();\n",
- " int birthYear = person1.calculateBirthYear();\n",
- " System.out.println(\"Birth Year: \" + birthYear);\n",
- " }\n",
- "}\n",
- "\n",
- "Main.main(null);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Refrence Types Example"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "// Base class Animal\n",
- "class Animal {\n",
- " // Attribute of the Animal class\n",
- " String name;\n",
- "\n",
- " // Constructor to initialize Animal objects\n",
- " Animal(String name) {\n",
- " this.name = name;\n",
- " }\n",
- "\n",
- " // Method to make the animal speak\n",
- " void speak() {\n",
- " System.out.println(name + \" makes a sound.\");\n",
- " }\n",
- "}\n",
- "\n",
- "// Subclass Dog that inherits from Animal\n",
- "class Dog extends Animal {\n",
- "\n",
- " // Constructor to initialize Dog objects\n",
- " Dog(String name) {\n",
- " super(name); // Call the constructor of the superclass\n",
- " }\n",
- "\n",
- " // Overridden method to make the dog speak\n",
- " @Override\n",
- " void speak() {\n",
- " System.out.println(name + \" barks.\");\n",
- " }\n",
- "\n",
- " // Method specific to the Dog class\n",
- " void fetch() {\n",
- " System.out.println(name + \" is fetching the ball!\");\n",
- " }\n",
- "}\n",
- "\n",
- "public class Main {\n",
- " public static void main(String[] args) {\n",
- " // Create an object of the Animal class\n",
- " Animal genericAnimal = new Animal(\"Generic Animal\");\n",
- " genericAnimal.speak(); // Output: Generic Animal makes a sound.\n",
- "\n",
- " // Create an object of the Dog class\n",
- " Dog dog = new Dog(\"Buddy\");\n",
- " dog.speak(); // Output: Buddy barks.\n",
- " dog.fetch(); // Output: Buddy is fetching the ball!\n",
- " }\n",
- "}\n",
- "\n",
- "Main.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": "19.0.2+7-44"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_01/Teacher/2024-06-23-unit_1._intro.ipynb b/_notebooks/CSA/units_1_to_10/unit_01/Teacher/2024-06-23-unit_1._intro.ipynb
deleted file mode 100644
index 9152b013..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_01/Teacher/2024-06-23-unit_1._intro.ipynb
+++ /dev/null
@@ -1,76 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "toc: true\n",
- "title: Unit 1 - Primitive & Reference Types\n",
- "description: A Unit of documents that overview Primitive & Reference Types in Java\n",
- "courses: { csa: {week: 1} }\n",
- "type: ccc\n",
- "categories: [AP CSA]\n",
- "menu: nav/CSA_Units/csa_unit1.html\n",
- "author: Aniket Chakradeo, Soham Kamat\n",
- "permalink: /csa/unit1/intro\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Data Types\n",
- "\n",
- "Data types in Java are categorized as either **primitive** or **reference**.\n",
- "\n",
- "A **type** is a set of values (e.g., integers, floats, strings, etc.). The **type** determines how data is stored in memory and how a set of operators (e.g., +, -, *, /, etc.) will work with them."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "\n",
- "### Resources\n",
- "The sources for Java are vast. \n",
- "\n",
- "Here are AP Specific Resources\n",
- "\n",
- "- [AP CSA Unit 1](https://apclassroom.collegeboard.org/8/home?unit=1)\n",
- "- [Quizlet](https://quizlet.com/421606237/ap-computer-science-unit-1-primitive-types-flash-cards/)\n",
- "\n",
- "\n",
- "Or you can Google \"Java Data Types\". Here are some in order recommended sites.\n",
- "\n",
- "- [W3 Schools](https://www.w3schools.com/java/java_data_types.asp)\n",
- "- [GeeksForGeeks](https://www.geeksforgeeks.org/data-types-in-java/)\n",
- "- [JavaTpoint](https://www.javatpoint.com/java-data-types)\n",
- "- [Oracle Java Documentation](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html)\n"
- ]
- }
- ],
- "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": "19.0.2+7-44"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_01/Teacher/2024-06-24-unit_1_primatives.ipynb b/_notebooks/CSA/units_1_to_10/unit_01/Teacher/2024-06-24-unit_1_primatives.ipynb
deleted file mode 100644
index 2e6f0ec1..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_01/Teacher/2024-06-24-unit_1_primatives.ipynb
+++ /dev/null
@@ -1,167 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "toc: true\n",
- "title: Unit 1 - Primitive Types\n",
- "categories: [CSA-Prep]\n",
- "menu: nav/CSA_Units/csa_unit1.html\n",
- "authors: Aniket Chakradeo, Soham Kamat\n",
- "permalink: /csa/unit1/primitives\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Primitive Data Types\n",
- "A primitive data type specifies the **size and type of information**. Primitive types are the simplest type of variables in Java. They simply store a small amount of data, according to the type. They are not associated with a class.\n",
- "\n",
- "### The 3 Primitive Data Types for College Board\n",
- "\n",
- "There are eight primitive data types in Java, but only these 3 are used in AP CSA:\n",
- "\n",
- "| Data Type | Description |\n",
- "|-|-|\n",
- "| int | Stores whole numbers from -2,147,483,648 to 2,147,483,647 |\n",
- "| double | Stores decimal numbers. Sufficient for storing 15 decimal digits |\n",
- "| boolean | Stores true or false values |\n",
- "\n",
- "To declare a variable, you write:\n",
- "`Type VariableName = Value;`\n",
- "\n",
- "For example:\n",
- "`int count = 0;`\n",
- "\n",
- "### Variable Terms and Conventions\n",
- "\n",
- "These are important items to remember with regards to Java and the College Board.\n",
- "\n",
- "- A `variable name` is often referred to as the `variable identifier` in Java.\n",
- "- A `variable name` follows camel case conventions in Java (e.g., firstName).\n",
- "- A `class name`, which is a Data Type, follows Pascal case (e.g., BankAccount)."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## The 8 Primitive Data Types\n",
- "\n",
- "Here is the complete list of primitive types in Java:\n",
- "\n",
- "- **byte**: An 8-bit signed two's complement integer.\n",
- "- **short**: A 16-bit signed two's complement integer.\n",
- "- **int**: A 32-bit signed two's complement integer.\n",
- "- **long**: A 64-bit signed two's complement integer.\n",
- "- **float**: A single-precision 32-bit IEEE 754 floating point.\n",
- "- **double**: A double-precision 64-bit IEEE 754 floating point.\n",
- "- **boolean**: Stores either `true` or `false`.\n",
- "- **char**: Stores a single 16-bit Unicode character."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Popcorn Hack: Greatest Value Terms\n",
- "\n",
- "`Primitive Data types have constraints` The program shows the constraints of Integers and Doubles. Define the following terms...\n",
- "\n",
- "- **constraints**:\n",
- "- **overflow**:\n",
- "- **underflow**"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class GreatestValue {\n",
- " public static void main(String[] args) {\n",
- " System.out.println(\"Max Integer: \" + Integer.MAX_VALUE);\n",
- " System.out.println(\"Min Integer: \" + Integer.MIN_VALUE);\n",
- " System.out.println(\"Max Double: \" + Double.MAX_VALUE);\n",
- " System.out.println(\"Min Double: \" + Double.MIN_VALUE);\n",
- "\n",
- " // Integer Show Overflow\n",
- " int i = Integer.MAX_VALUE;\n",
- " i++;\n",
- " System.out.println(\"Integer Max + 1, Overflow: \" + i);\n",
- "\n",
- " // Integer Show Underflow\n",
- " int j = Integer.MIN_VALUE;\n",
- " j--;\n",
- " System.out.println(\"Integer Min - 1, Underflow: \" + j);\n",
- "\n",
- " // Integer Max + Min\n",
- " int k = Integer.MAX_VALUE + Integer.MIN_VALUE;\n",
- " System.out.println(\"Integer Max + Min: \" + k);\n",
- "\n",
- " }\n",
- "}\n",
- "GreatestValue.main(null);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Popcorn Hack: Fill in Data Type \n",
- "The code below is broken....\n",
- "\n",
- "- Fill in the blank, replace the underbars with the correct type.\n",
- "- Output the contents to the Jupyter Terminal"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "___ zero = 0; //Whole number\n",
- "___ pi = 3.14159; //Decimal values. Floating point numbers.\n",
- "___ iAmTakingCSA = true; //Stores a true of false binary value\n",
- "___ myProjectedGrad = 'A'; //Single character\n",
- "___ iLoveCodeCodeCoding = \"Yes\"; //String of characters"
- ]
- }
- ],
- "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": "17.0.12+0"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_01/Teacher/2024-06-24-unit_1_reference.ipynb b/_notebooks/CSA/units_1_to_10/unit_01/Teacher/2024-06-24-unit_1_reference.ipynb
deleted file mode 100644
index 0dbc39d9..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_01/Teacher/2024-06-24-unit_1_reference.ipynb
+++ /dev/null
@@ -1,93 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "toc: true\n",
- "title: Unit 1 - Reference Types\n",
- "description: An overview of Reference Types\n",
- "menu: nav/CSA_Units/csa_unit1.html\n",
- "authors: Aniket Chakradeo, Soham Kamat\n",
- "permalink: /csa/unit1/reference\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Refrence Types\n",
- "\n",
- "Reference types in Java include classes, arrays, and interfaces. Unlike primitive types, reference types store addresses (references) to objects rather than the objects themselves.\n",
- "\n",
- "### Classes\n",
- "- Create complex data structures by grouping variables and methods.\n",
- "\n",
- "Example:\n",
- "```java\n",
- "class Person {\n",
- " String name;\n",
- " int age;\n",
- "}\n",
- "Person person = new Person(); // `person` reference in stack, `Person` object in heap\n",
- "```\n",
- "### Arrays\n",
- "- Collections of variables of the same type.\n",
- "\n",
- "Example:\n",
- "```java\n",
- "int[] numbers = new int[5]; // `numbers` reference in stack, array in heap\n",
- "```\n",
- "\n",
- "### Popcorn Hack"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "public class Main {\n",
- " public static void main(String[] args) {\n",
- " // Create a reference type variable of type String\n",
- " ______ myString = \"Hello, World!\";\n",
- " \n",
- " // Create a reference type variable of type Array\n",
- " ______ myArray = new int[] {1, 2, 3, 4, 5};\n",
- "\n",
- " // Print the values\n",
- " System.out.println(myString);\n",
- " System.out.println(Arrays.toString(myArray));\n",
- " }\n",
- "}\n",
- "\n",
- "Main.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": "19.0.2+7-44"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_01/Teacher/2024-06-24-unit_1_stack_heap.ipynb b/_notebooks/CSA/units_1_to_10/unit_01/Teacher/2024-06-24-unit_1_stack_heap.ipynb
deleted file mode 100644
index f23fee9e..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_01/Teacher/2024-06-24-unit_1_stack_heap.ipynb
+++ /dev/null
@@ -1,245 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "toc: true\n",
- "title: Unit 1 - Stack & Heap Memory \n",
- "description: An overview of stack and heap memory in Java\n",
- "authors: Aniket Chakradeo, Soham Kamat\n",
- "menu: nav/CSA_Units/csa_unit1.html\n",
- "permalink: /csa/unit1/stack_heap\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Memory Allocation: Stack and Heap\n",
- "\n",
- "In Java, memory allocation for variables occurs in two main areas: the stack and the heap."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Stack Memory\n",
- "\n",
- "Stack memory is a region of memory that stores temporary variables created by each function (including the main function). It is managed by the execution stack and follows a last-in-first-out (LIFO) order.\n",
- "\n",
- "- Stores primitive data types and references to objects.\n",
- "- Memory is allocated in a last-in-first-out (LIFO) manner.\n",
- "- Each thread has its own stack, ensuring thread safety.\n",
- "\n",
- "Example:\n",
- "```java\n",
- "int number = 100; // Stored in the stack\n",
- "```\n",
- "\n",
- "\n",
- "#### Stack Variables Tips\n",
- "\n",
- "College Board often asks questions about stack usage.\n",
- "\n",
- "- Since primitives are always on the stack, they point directly to the content. This is best observed in a debugger.\n",
- "- A reference type contains an address to the content on the stack.\n",
- "- Passing a stack variable to a method creates a copy of the content of that variable.\n",
- "- Changes to the content of a primitive type will not return back to the method caller; this is called pass-by-value.\n",
- "- Since a reference type contains an address to the heap, the reference is copied when calling a method. This is called pass-by-reference, as data type changes are then performed according to the reference.\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Heap Memory\n",
- "\n",
- "Heap memory is a region of memory used for dynamic memory allocation. It is managed by Java's memory management system.\n",
- "\n",
- "- Used for storing objects and arrays.\n",
- "- Shared among all threads, requiring synchronization for thread safety.\n",
- "- Managed by the garbage collector, which reclaims memory when objects are no longer in use.\n",
- "\n",
- "Example:\n",
- "```java\n",
- "// Long form showing new\n",
- "String message = new String(\"Hello\");\n",
- "\n",
- "// Short form Java performs new find the scenes\n",
- "String message = \"Hello\";\n",
- "```\n",
- "\n",
- "### Heap Variables Tips\n",
- "\n",
- "- Heap variables stay alive as long as a stack variable points to them.\n",
- "- By nature, all reference data types refer to an address on the stack but change content on the heap.\n",
- "- Objects created in the heap are globally accessible and can be shared among multiple methods, this creates concurrency issues when programming.\n",
- "- The garbage collector automatically reclaims memory from objects that are no longer referenced, helping to prevent memory leaks."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Popcorn Hack: literal vs input\n",
- "\n",
- "A value that is directly in code is called a literal. Often developers will say this value is hard coded value.\n",
- "- Literal: In source code representation of a fixed value, e.g. 17. A hard coded number.\n",
- "- String Literal: In sourced code set of letters within quotes, e.g. \"blue\", A hard coded string.\n",
- "\n",
- "Q1: Define some literal data.\n",
- "Q2: Obtain that data from input versus hard coded."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "// Hard code literal values\n",
- "\n",
- "int literalAge = 17;\n",
- "String literalFavoriteColor = \"blue\";"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "// Input your age\n",
- "Scanner scanObj = new Scanner(System.in); // Create a Scanner object\n",
- "System.out.println(\"Enter age\");\n",
- "int inputAge = scanObj.nextInt(); // Read user input\n",
- "System.out.println(\"My Age is: \" + inputAge); // Output user input"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Popcorn Hack: pass-by-value, pass-by-reference\n",
- "For College Articulation in Data Structures and College Board AP Exam you will need to understand pass-by-value and pass-br-reference. \n",
- "\n",
- "- If you pass primitives to a method they WILL NOT change the callers value.\n",
- "- If you wrap the primitive in a refrence type, in the example below using a class, then you can change the original.\n",
- "\n",
- "Q1: Describe approache difference between IntByValue and IntByReference.\n",
- "Q2: Try to make a changeInt method that change would persist after it is called. Be careful, this will require a change in approach. "
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class IntByValue {\n",
- " \n",
- " public static void changeInt(int n) {\n",
- " System.out.println(\"In changeInt method\");\n",
- " System.out.println(\"\\tBefore n += 10: n = \" + n); // prints 5\n",
- " n = n += 10;\n",
- " System.out.println(\"\\tAfter n += 10: n = \" + n); // prints 10\n",
- " }\n",
- "\n",
- " public static void main(String[] args) {\n",
- " int n = 5;\n",
- " System.out.println(\"Main method before changeInt(n): n = \" + n); // prints 5\n",
- " changeInt(n);\n",
- " System.out.println(\"Main method after changeInt(n): n = \" + n); // still prints 5\n",
- " }\n",
- "}\n",
- "IntByValue.main(null);"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class IntByReference {\n",
- " private int value;\n",
- "\n",
- " public IntByReference(Integer value) {\n",
- " this.value = value;\n",
- " }\n",
- "\n",
- " public String toString() {\n",
- " return (String.format(\"%d\", this.value));\n",
- " }\n",
- "\n",
- " public void swapToLowHighOrder(IntByReference i) {\n",
- " if (this.value > i.value) {\n",
- " int tmp = this.value;\n",
- " this.value = i.value;\n",
- " i.value = tmp;\n",
- " }\n",
- " }\n",
- "\n",
- " public static void swapper(int n0, int n1) {\n",
- " IntByReference a = new IntByReference(n0);\n",
- " IntByReference b = new IntByReference(n1);\n",
- " System.out.println(\"Before: \" + a + \" \" + b);\n",
- " a.swapToLowHighOrder(b); // conditionally build swap method to change values of a, b\n",
- " System.out.println(\"After: \" + a + \" \" + b);\n",
- " System.out.println();\n",
- " }\n",
- "\n",
- " public static void main(String[] ags) {\n",
- " IntByReference.swapper(21, 16);\n",
- " IntByReference.swapper(16, 21);\n",
- " IntByReference.swapper(16, -1);\n",
- " }\n",
- "\n",
- "}\n",
- "IntByReference.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": "17.0.12+0"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_01/Teacher/2024-07-01-unit_1_examples.ipynb b/_notebooks/CSA/units_1_to_10/unit_01/Teacher/2024-07-01-unit_1_examples.ipynb
deleted file mode 100644
index 273bdf83..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_01/Teacher/2024-07-01-unit_1_examples.ipynb
+++ /dev/null
@@ -1,620 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "toc: true\n",
- "title: Unit 1 - Primitive & Reference Types Examples\n",
- "description: Primitive & Reference Types Examples\n",
- "authors: Aniket Chakradeo, Soham Kamat\n",
- "menu: nav/CSA_Units/csa_unit1.html\n",
- "type: ccc\n",
- "permalink: /unit1lessonexamples\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Primitive Data Types\n",
- "In your personal blog you should have a comprehensive example that help you recall Primitive Data Types."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### All Primitives Demo\n",
- "\n",
- "The **class PrivitiveTypes** shows an assignment and output of each of the Java primitive types."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class PrimitiveTypes {\n",
- " public static void main(String[] args) {\n",
- " // Declare and initialize variables of different primitive types\n",
- " byte myByte = 10; // 8-bit integer\n",
- " short myShort = 32000; // 16-bit integer\n",
- " int myInt = 123456; // 32-bit integer\n",
- " long myLong = 123456789L; // 64-bit integer\n",
- "\n",
- " float myFloat = 3.14f; // 32-bit floating-point\n",
- " double myDouble = 3.14159; // 64-bit floating-point\n",
- "\n",
- " char myChar = 'A'; // 16-bit Unicode character\n",
- " boolean myBoolean = true; // true or false\n",
- "\n",
- " // Perform some operations\n",
- " int sum = myInt + 1000;\n",
- " float division = myFloat / 2;\n",
- " boolean isEqual = myByte == 10;\n",
- "\n",
- " // Print the results\n",
- " System.out.println(\"Byte value: \" + myByte);\n",
- " System.out.println(\"Short value: \" + myShort);\n",
- " System.out.println(\"Int value: \" + myInt);\n",
- " System.out.println(\"Long value: \" + myLong);\n",
- " System.out.println(\"Float value: \" + myFloat);\n",
- " System.out.println(\"Double value: \" + myDouble);\n",
- " System.out.println(\"Char value: \" + myChar);\n",
- " System.out.println(\"Boolean value: \" + myBoolean);\n",
- "\n",
- " System.out.println(\"Sum of myInt and 1000: \" + sum);\n",
- " System.out.println(\"Division of myFloat by 2: \" + division);\n",
- " System.out.println(\"Is myByte equal to 10? \" + isEqual);\n",
- " }\n",
- "}\n",
- "\n",
- "PrimitiveTypes.main(null);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Overflow and Underflow\n",
- "\n",
- "In Java, by nature of using strongly typed definitions, the developer needs to be aware of the limits of numeric data. The **class OverFlow** demonstrates the constraints of **int** and **double** addition, and introduces the terms **overflow** and **underflow**."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "import java.text.DecimalFormat;\n",
- "\n",
- "public class OverFlow {\n",
- " public static void main(String[] args) {\n",
- " DecimalFormat df = new DecimalFormat(\"#,###\");\n",
- " DecimalFormat dfDouble = new DecimalFormat(\"#,###.################\");\n",
- "\n",
- " System.out.println(\"Max Integer: \" + Integer.MAX_VALUE);\n",
- " System.out.println(\"Min Integer: \" + Integer.MIN_VALUE);\n",
- " System.out.println(\"Max Double: \" + dfDouble.format(Double.MAX_VALUE));\n",
- " System.out.println(\"Min Double: \" + Double.MIN_VALUE);\n",
- "\n",
- " // Integer Show Overflow\n",
- " int i = Integer.MAX_VALUE;\n",
- " i++;\n",
- " System.out.println(\"Overflow error (flips negative), Integer Max + 1: \" + df.format(i));\n",
- " // Integer Show Underflow\n",
- " int j = Integer.MIN_VALUE;\n",
- " j--;\n",
- " System.out.println(\"Underflow error (flips positive), Integer Min - 1: \" + df.format(j));\n",
- "\n",
- " // Double Show Double Handling Integer.MAX_Value + 1\n",
- " double d = Integer.MAX_VALUE + 1.0;\n",
- " System.out.println(\"Double Handling Integer Max + 1: \" + dfDouble.format(d));\n",
- " // Double Show Double Handling Integer.MIN_Value - 1\n",
- " double e = Integer.MIN_VALUE - 1.0;\n",
- " System.out.println(\"Double Handling Integer Min - 1: \" + dfDouble.format(e));\n",
- "\n",
- " // Integer Max + Min\n",
- " int k = Integer.MAX_VALUE + Integer.MIN_VALUE;\n",
- " System.out.println(\"Integer Max + Min, shows Min is greater: \" + df.format(k));\n",
- " }\n",
- "}\n",
- "\n",
- "OverFlow.main(null);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Casting\n",
- "\n",
- "In some numeric operations, it may be more logical to change the type.\n",
- "\n",
- "1. **Widening**: This is the process of converting a smaller data type to a larger data type. For example, in division, where two integers (int) produce a real number (double).\n",
- "2. **Narrowing**: This is the process of converting a larger data type to a smaller data type, such as truncating a double to an int."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class Casting {\n",
- " public static void main(String[] args) {\n",
- "\n",
- " // Implicit casting (widening)\n",
- " int num1 = 5;\n",
- " int num2 = 2;\n",
- " System.out.println(\"Integer math: \" + num1 / num2);\n",
- " // to widen one or the other must be a double\n",
- " System.out.println(\"Cast math to Double: \" + (double) num1 / num2);\n",
- "\n",
- " // Explicit casting (narrowing)\n",
- " double rounding = 0.1;\n",
- " double test1 = 90.0;\n",
- " double test2 = 89.5;\n",
- " double test3 = 90.4;\n",
- " double average = (test1 + test2 + test3) / 3;\n",
- " // to narrow all must be casted to int\n",
- " double averageTruncated = (int) average;\n",
- " // to simplify narrow, cast after all of the math operations\n",
- " double averageRounded = (int) (average + rounding);\n",
- " System.out.println(\"Double average: \" + average);\n",
- " System.out.println(\"Cast average to int, result is truncated: \" + averageTruncated);\n",
- " System.out.println(\"Cast average to int, result is truncated after rounding adjust: \" + averageRounded);\n",
- " }\n",
- "}\n",
- "Casting.main(null);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### ArrayLists and Wrapper Classes\n",
- "\n",
- "In the context of College Board, this Teacher believes that ArrayLists and Wrapper classes go together in learning and discussion.\n",
- "\n",
- "A key use of Wrapper Classes is with `ArrayList`, which only accepts reference types. This allows primitives to be used within `ArrayList` through their Wrapper Classes, enabling dynamic resizing and access to built-in methods like streams for sum and average calculations.\n",
- "\n",
- "Additionally, Wrapper Classes in Java allow primitive types to behave like reference types, providing useful methods and constants such as `MIN_VALUE` and `MAX_VALUE`. They enable transformations between primitives and strings, like converting an `int` to a `String` and vice versa.\n",
- "\n",
- "In the following examples, the first example goes through the language elements of `Wrapper Classes` culminating with `ArrayList`. The second example puts these elements together in a more practical application, demonstrating the value of using `Wrapper Classes` and `ArrayList` to simplify code and perform calculations."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class StudentWrapper {\n",
- " int age; // Primitive data type, int\n",
- " Integer ageWrapper; // Wrapper class for Integer\n",
- " int[] testScores; // Array of type int\n",
- " Integer[] testScoresWrapper; // Array of Wrapper class for Integer \n",
- " ArrayList testScoresList; // ArrayList of Wrapper class for Integer, int is not allowed\n",
- " double averageScore; // Primitive data type, double for calculated average\n",
- "\n",
- " // Method to calculate average score from an array of integers\n",
- " public static double calculateAverage(int[] scores) {\n",
- " int total = 0;\n",
- " // Enhanced for loop to calculate total\n",
- " for (int score : scores) {\n",
- " total += score;\n",
- " }\n",
- " // Cast to widden to double\n",
- " return (double) total / scores.length;\n",
- " }\n",
- "\n",
- " // Method to convert int array to Integer array\n",
- " public static Integer[] convertToIntegerArray(int[] scores) {\n",
- " // Allocate heap memory for Integer array based on length of int array, fixed size\n",
- " Integer[] integerArray = new Integer[scores.length];\n",
- " // Conventional loop to set elements from int array to Integer array\n",
- " for (int i = 0; i < scores.length; i++) {\n",
- " // Set values in an Array only work with an index\n",
- " integerArray[i] = scores[i];\n",
- " }\n",
- " return integerArray;\n",
- " }\n",
- "\n",
- " // Method to convert Integer array to ArrayList\n",
- " public static ArrayList convertToArrayList(Integer[] scores) {\n",
- " // Allocate heap memory for ArrayList, dynamic size\n",
- " ArrayList arrayList = new ArrayList<>();\n",
- " // Enhanced for loop to add elements from Integer array to ArrayList\n",
- " for (Integer score : scores) {\n",
- " // Add values dynamically to an ArrayList \n",
- " arrayList.add(score);\n",
- " }\n",
- " return arrayList;\n",
- " }\n",
- "\n",
- " public static void main(String[] args) {\n",
- " // Simulate receiving input data as strings, e.g., from user input \n",
- " String ageString = \"17\";\n",
- " String testScoresString = \"85, 90, 78, 92\";\n",
- "\n",
- " // Create an instance of Student class, in heap memory\n",
- " StudentWrapper student = new StudentWrapper();\n",
- "\n",
- " // Set and convert age using wrapper class method (static)\n",
- " student.ageWrapper = Integer.parseInt(ageString);\n",
- " student.age = student.ageWrapper;\n",
- " System.out.println(\"Student Age: \" + student.age);\n",
- " System.out.println(\"Student Age (Wrapper): \" + student.ageWrapper);\n",
- "\n",
- " // Set test scores from input string, notice String.split() method\n",
- " String[] testScoresArray = testScoresString.split(\", \");\n",
- " // Allocate heap memory for test scores array based on length of input string\n",
- " student.testScores = new int[testScoresArray.length];\n",
- " // Conventional loop to set elements from input string to test scores array\n",
- " for (int i = 0; i < testScoresArray.length; i++) {\n",
- " // Set values in an Array only work with an index, requiring conventional loop\n",
- " // Integer.parseInt() method converts\n",
- " student.testScores[i] = Integer.parseInt(testScoresArray[i]);\n",
- " }\n",
- " // java.util.Arrays.toString() method converts array to string for printing in one line\n",
- " System.out.println(\"Student Test Scores: \" + java.util.Arrays.toString(student.testScores));\n",
- "\n",
- " // Calculate average score, using class Student defined static method\n",
- " student.averageScore = calculateAverage(student.testScores);\n",
- " System.out.println(\"Student Average Score: \" + student.averageScore);\n",
- "\n",
- " // Convert int array to Integer array, using class Student defined static method\n",
- " student.testScoresWrapper = convertToIntegerArray(student.testScores);\n",
- " System.out.println(\"Student Test Scores (Wrapper): \" + java.util.Arrays.toString(student.testScoresWrapper));\n",
- "\n",
- " // Convert Integer array to ArrayList, using class Student defined static method\n",
- " student.testScoresList = convertToArrayList(student.testScoresWrapper);\n",
- " System.out.println(\"Student Test Scores (ArrayList): \" + student.testScoresList);\n",
- "\n",
- " // Add a new test score ArrayList \n",
- " student.testScoresList.add(88); // Notice dynmic sizing of an ArrayList\n",
- " System.out.println(\"Updated Student Test Scores (ArrayList): \" + student.testScoresList);\n",
- " System.out.println(\"Updated Student Average Score (ArrayList): \" + student.testScoresList.stream().mapToInt(Integer::intValue).average().orElse(0.0));\n",
- "\n",
- " // Convert ArrayList back to int array for recalculating average, using original claculateAverage method\n",
- " student.testScores = student.testScoresList.stream().mapToInt(Integer::intValue).toArray();\n",
- " student.averageScore = calculateAverage(student.testScores);\n",
- " System.out.println(\"Updated Student Average Score: \" + student.averageScore);\n",
- "\n",
- " }\n",
- "}\n",
- "StudentWrapper.main(null);"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "import java.util.ArrayList;\n",
- "import java.util.Arrays;\n",
- "\n",
- "public class StudentGradeCalculator {\n",
- " int age; // Primitive data type, int\n",
- " ArrayList testScoresList; // ArrayList of Wrapper class for Integer\n",
- "\n",
- " // Constructor to initialize age and test scores\n",
- " public StudentGradeCalculator(int age, String testScoresString) {\n",
- " this.age = age;\n",
- " this.testScoresList = new ArrayList<>();\n",
- "\n",
- " // Split input string and convert to integer values\n",
- " String[] testScoresArray = testScoresString.split(\", \");\n",
- "\n",
- " // Add integer values to ArrayList\n",
- " for (String score : testScoresArray) {\n",
- " // Add integer values to ArrayList, if not an integer, set to minimum of 55 percent\n",
- " this.testScoresList.add(score.matches(\"\\\\d+\") ? Integer.parseInt(score) : 55);\n",
- " }\n",
- " }\n",
- "\n",
- " // Method to calculate average score using College Board method \n",
- " public double calculateAverage() {\n",
- " int total = 0;\n",
- " for (int score : testScoresList) {\n",
- " total += score;\n",
- " }\n",
- " return (double) total / testScoresList.size();\n",
- " }\n",
- "\n",
- " // Method to calculate average score using Java 8 Stream API\n",
- " public double calculateAverageStream() {\n",
- " return testScoresList.stream().mapToInt(Integer::intValue).average().orElse(0.0);\n",
- " }\n",
- "\n",
- " // Override toString method to display student details\n",
- " @Override\n",
- " public String toString() {\n",
- " return \"Age: \" + age + \", Test Scores: \" + testScoresList + \", Average Score: \" + calculateAverage() + \", Average Score (Stream): \" + calculateAverageStream();\n",
- " }\n",
- "\n",
- " public static void main(String[] args) {\n",
- " // Initialize students with ages and test scores\n",
- " StudentGradeCalculator john = new StudentGradeCalculator(17, \"85, A, 78, 92\");\n",
- " StudentGradeCalculator anita = new StudentGradeCalculator(16, \"88, 86, 90, 85\");\n",
- " StudentGradeCalculator jamal = new StudentGradeCalculator(18, \"92, 81, 79, 95\");\n",
- "\n",
- " // Output student details\n",
- " System.out.println(\"John's Details: \" + john);\n",
- " System.out.println(\"Anita's Details: \" + anita);\n",
- " System.out.println(\"Jamal's Details: \" + jamal);\n",
- " }\n",
- "}\n",
- "StudentGradeCalculator.main(null);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Refrence Types Examples\n",
- "In your Personal Blog you should create a class that captures all the key reference type in Java that are required for College Board. "
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Class Reference Type\n",
- "The **class Person** illustrates the basics of a **Java class**. When a **Person person** object is created, it is stored on the heap, and it contains data for the name and age. This object is a reference type, meaning that the variable `person` holds a reference (or address) to the memory location where the actual `Person` object is stored, rather than the object itself.\n",
- "\n",
- "Key Points:\n",
- "1. Instance Variables: Attributes of the class that hold data.\n",
- "2. Constructor: Initializes the instance variables.\n",
- "3. Methods: Define behaviors for the class.\n",
- "4. **Reference Type**: The variable holds a reference to the memory location of the object on the heap."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class Person {\n",
- " // Fields (attributes) of the Person class\n",
- " String name;\n",
- " int age;\n",
- "\n",
- " // Constructor to initialize the Person object\n",
- " Person(String name, int age) {\n",
- " this.name = name;\n",
- " this.age = age;\n",
- " }\n",
- "\n",
- " // Method to introduce the person\n",
- " void introduce() {\n",
- " System.out.println(\"Hello, my name is \" + name + \" and I am \" + age + \" years old.\");\n",
- " }\n",
- "\n",
- " // Method to simulate having a birthday\n",
- " void haveBirthday() {\n",
- " age++;\n",
- " System.out.println(\"Happy Birthday! I am now \" + age + \" years old.\");\n",
- " }\n",
- "\n",
- " public static void main(String[] args) {\n",
- " // Create an instance of the Person class (a custom reference type)\n",
- " Person person = new Person(\"John\", 25);\n",
- "\n",
- " // Call methods on the Person object\n",
- " person.introduce();\n",
- " person.haveBirthday();\n",
- " }\n",
- "}\n",
- "Person.main(null);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Array Reference Types\n",
- "The **class ArrayReferenceTypes** demonstrates the usage of arrays, which are reference types in Java. This class includes examples of a single-dimensional array of integers (`int[]`) and a two-dimensional array of strings (`String[][]`). Both arrays are initialized with hard-coded literals.\n",
- "\n",
- "Key Points:\n",
- "1. Single-Dimensional Array: Demonstrates the use of int[] with hard-coded literals.\n",
- "2. Two-Dimensional Array: Demonstrates the use of String[][] with hard-coded literals.\n",
- "3. Enhanced For-Loop: Used for iterating over the single-dimensional array.\n",
- "4. Classic For-Loop: Used for iterating over the two-dimensional array with i and j indices.\n",
- "5. **Reference Type**: Arrays are reference types, meaning the variable holds a reference to the memory location of the array data."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class ArrayReferenceTypes {\n",
- " public static void main(String[] args) {\n",
- " // Create and initialize an array of integers\n",
- " int[] numbers = {1, 2, 3, 4, 5};\n",
- "\n",
- " // Print the contents of the integer array\n",
- " System.out.println(\"Array contents:\");\n",
- " for (int number : numbers) {\n",
- " System.out.println(number);\n",
- " }\n",
- "\n",
- " // Create and initialize a 2D array of strings\n",
- " String[][] matrix = {\n",
- " {\"A1\", \"B1\", \"C1\"},\n",
- " {\"A2\", \"B2\", \"C2\"},\n",
- " {\"A3\", \"B3\", \"C3\"}\n",
- " };\n",
- "\n",
- " // Print the contents of the 2D string array\n",
- " System.out.println(\"2D array contents:\");\n",
- " for (int i = 0; i < matrix.length; i++) {\n",
- " for (int j = 0; j < matrix[i].length; j++) {\n",
- " System.out.print(matrix[i][j] + \" \");\n",
- " }\n",
- " System.out.println();\n",
- " }\n",
- " }\n",
- "}\n",
- "ArrayReferenceTypes.main(null);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Enums (Project-based Learning Topic)\n",
- "Enums in Java, similar to those in the 'C' language, are a special reference data type that enables a variable to be a set of predefined constants. They are useful for representing fixed sets of related constants, such as days of the week, months of the year, etc.\n",
- "\n",
- "Enums can be used in assignments, conditional checks (if, switch), and iterations (for, while), making them versatile for various programming scenarios.\n",
- "\n",
- "Similarity to Classes:\n",
- "- Fields and Methods: Enums can have fields and methods just like classes.\n",
- "- Constructors: Enums can have constructor-like methods to initialize their fields, similar to class constructors.\n",
- "- Encapsulation: Enums encapsulate data (fields) and behavior (methods) just like classes.\n",
- "\n",
- "In this example, we are setting constants and descriptions to represent educational units and questions for the APCSA curriculum."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class APCSACurriculum { \n",
- " // Enum to represent educational units\n",
- " enum Units {\n",
- " // Each enum constant is initialized with a description and is associated with a getter method\n",
- " UNIT_1(\"Primitive Types—You’ll learn the fundamentals of Java, a programming language, as well as other foundational concepts for coding.\"),\n",
- " UNIT_2(\"Using Objects—You’ll explore reference data as a way to represent real-world objects in a digital world and discover methods to perform more complex operations.\"),\n",
- " UNIT_3(\"Boolean Expressions and if Statements—You’ll delve into the building blocks of algorithms and focus on using conditional statements to solve problems and control results.\"),\n",
- " UNIT_4(\"Iteration—You’ll learn about iteration, another building block of algorithms that are for repetition.\"),\n",
- " UNIT_5(\"Writing Classes—You’ll explore how real-world interactions can be expressed digitally by organizing behaviors and attributes into classes, and you’ll examine the legal and ethical implications of computer programming.\"),\n",
- " UNIT_6(\"Array—You’ll learn techniques and standard algorithms to work with collections of related data, known as data structures.\"),\n",
- " UNIT_7(\"ArrayList—You’ll delve deeper into data sets, exploring ArrayList objects for larger amounts of data, as well as the privacy concerns related to personal data storage.\"),\n",
- " UNIT_8(\"2D Array—Now that you’ve explored 1D arrays, you’ll branch out into 2D arrays and experiment with data sets represented in a table.\"),\n",
- " UNIT_9(\"Inheritance—You’ll learn how to manipulate programming without altering existing code by using subclasses to create a hierarchy.\"),\n",
- " UNIT_10(\"Recursion—You’ll work on solving larger problems by solving smaller, simpler versions of the same problem using recursive methods.\");\n",
- "\n",
- " // Private field to hold the description of each unit\n",
- " private final String description;\n",
- "\n",
- " // Constructor-like method to initialize the description field\n",
- " Units(String description) {\n",
- " this.description = description;\n",
- " }\n",
- "\n",
- " // Getter method to retrieve the description\n",
- " public String getDescription() {\n",
- " return description;\n",
- " }\n",
- " }\n",
- "\n",
- " // Enum to represent Free Response Questions (FRQs)\n",
- " enum FRQs {\n",
- " // Each enum constant is initialized with a description and is associated with a getter method\n",
- " QUESTION_1(\"Methods and Control Structures—You’ll be asked to write program code to create objects of a class and call methods, and satisfy method specifications using expressions, conditional statements, and iterative statements.\"),\n",
- " QUESTION_2(\"Classes—You’ll be asked to write program code to define a new type by creating a class and satisfy method specifications using expressions, conditional statements, and iterative statements.\"),\n",
- " QUESTION_3(\"Array/ArrayList—You’ll be asked to write program code to satisfy method specifications and create, traverse, and manipulate elements in 1D array or ArrayList objects.\"),\n",
- " QUESTION_4(\"2D Array—You’ll be asked to write program code to satisfy method specifications and create, traverse, and manipulate elements in 2D array objects.\");\n",
- "\n",
- " // Private field to hold the description of each question\n",
- " private final String description;\n",
- "\n",
- " // Constructor-like method to initialize the description field\n",
- " FRQs(String description) {\n",
- " this.description = description;\n",
- " }\n",
- "\n",
- " // Getter method to retrieve the description\n",
- " public String getDescription() {\n",
- " return description;\n",
- " }\n",
- " }\n",
- "\n",
- " public static void main(String[] args) {\n",
- " System.out.println(\"AP Computer Science A Curriculum and FRQ Topics:\");\n",
- "\n",
- " // Accessing enum values for Units\n",
- " System.out.println(\"Units:\");\n",
- " for (Units unit : Units.values()) {\n",
- " System.out.println(\"\\t\" + unit + \": \" + unit.getDescription());\n",
- " }\n",
- "\n",
- " System.out.println(\"FRQ types:\");\n",
- " // Accessing enum values for FRQs\n",
- " for (FRQs frq : FRQs.values()) {\n",
- " System.out.println(\"\\t\" + frq + \": \" + frq.getDescription());\n",
- " }\n",
- " }\n",
- "}\n",
- "APCSACurriculum.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": "11.0.24+8-post-Ubuntu-1ubuntu322.04"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_01/Teacher/2024-07-13-unit_1_quiz.ipynb b/_notebooks/CSA/units_1_to_10/unit_01/Teacher/2024-07-13-unit_1_quiz.ipynb
deleted file mode 100644
index 5de51f6f..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_01/Teacher/2024-07-13-unit_1_quiz.ipynb
+++ /dev/null
@@ -1,195 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "title: Quiz Questions for APCSA Unit 1\n",
- "description: Questions and Code Cells for the Quiz on Unit 1\n",
- "categories: [CSA-Quiz]\n",
- "permalink: /csa/units/quiz1\n",
- "menu: nav/CSA_Units/csa_unit1.html\n",
- "author: Soham Kamat & Aniket Chakradeo\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Unit 1: Primitive Types"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Question 1\n",
- "\n",
- "Which of the following is a valid declaration of a variable of type int in Java? \n",
- "a) int 123variable; \n",
- "b) int variable123; \n",
- "c) int variable#123; \n",
- "d) int variable 123;\n",
- "\n",
- "Answer: b) int variable123;\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "// Q1 Hack: Define variables according to Java naming conventions.\n",
- "// For instance, is it snake_case, camelCase, or PascalCase?\n",
- "\n",
- "int variable123 = 123;\n",
- "System.out.println(variable123);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Question 2\n",
- "\n",
- "What is the value of the following expression in Java: 5 / 2? \n",
- "a) 2.5 \n",
- "b) 3 \n",
- "c) 2 \n",
- "d) 2.0\n",
- "\n",
- "Answer: c) 2\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "// Q2.1 Hack: Show in code difference between integer and floating point division.\n",
- "// Q2.2 Hack: Show in code the differnt number types in Java and how they behave.\n",
- "// Behave means definition and assignment."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "### Question 3\n",
- "\n",
- "Which primitive type is used to represent a single character in Java? \n",
- "a) char \n",
- "b) String \n",
- "c) int \n",
- "d) byte\n",
- "\n",
- "Answer: a) char"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "// Q3.1 Hack: Show in code all the the non-number Java primitive data types and how they behave.\n",
- "// Q3.2 Hack: Show in code the String data type and how it behaves."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Question 4\n",
- "\n",
- "Answer the following questions based on the code cell:\n",
- "* a) What kind of types are person1 and person2? \n",
- "* Answer: \n",
- "* b) Do person1 and person3 point to the same value in memory?\n",
- "* Answer:\n",
- "* c) Is the integer \"number\" stored in the heap or in the stack?\n",
- "* Answer:\n",
- "* d) Is the value that \"person1\" points to stored in the heap or in the stack?\n",
- "* Answer: "
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "public class Person {\n",
- " String name;\n",
- " int age;\n",
- " int height;\n",
- " String job;\n",
- "\n",
- " public Person(String name, int age, int height, String job) {\n",
- " this.name = name;\n",
- " this.age = age;\n",
- " this.height = height;\n",
- " this.job = job;\n",
- " }\n",
- "}\n",
- "\n",
- "public static void main(String[] args) {\n",
- " Person person1 = new Person(\"Carl\", 25, 165, \"Construction Worker\");\n",
- " Person person2 = new Person(\"Adam\", 29, 160, \"Truck Driver\");\n",
- " Person person3 = person1;\n",
- " int number = 16;\n",
- " System.out.println(number);\n",
- "}\n",
- "main(null); // This is required in Jupiter Notebook to run the main method."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Question 5 \n",
- "\n",
- "(a) Define primitive types and reference types in Java. The application is for banking, where you need to represent customer information.\n",
- "\n",
- "(b) Add comments for primitive types and reference types. In terms of memory allocation, discuss concepts like instance, stack, and heap where it adds value.\n",
- "\n",
- "(c) To assist in requirements, here are some required elements:\n",
- "- Create multiple customers from the `public class Account`.\n",
- "- Consider key class variables that a Bank may require: `name`, `balance`, `accountNumber`.\n",
- "- Create a two argument constructor using `name` and `balance`.\n",
- "- Consider in constructor how you will create a unique account number using `static int lastAccountNumber`\n",
- "- Define a method `calculateInterest` that works with getting and setting `double balance` using `private static double interestRate`."
- ]
- }
- ],
- "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": "17.0.12+0"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_02/Period3/2024-09-12-Unit_2_HW.ipynb b/_notebooks/CSA/units_1_to_10/unit_02/Period3/2024-09-12-Unit_2_HW.ipynb
deleted file mode 100644
index e5641770..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_02/Period3/2024-09-12-Unit_2_HW.ipynb
+++ /dev/null
@@ -1,120 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "title: Unit 2 — Recap & Homework\n",
- "description: A recap of everything we covered today.\n",
- "type: collab\n",
- "toc: true\n",
- "permalink: /csa/unit2/period3/homework/\n",
- "menu: nav/CSA_Units/unit2/period3.html\n",
- "comments: true\n",
- "author: Aadit Mathur, Eric Yu, Shuban Pal, Rahul Verma\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "source": [
- "# Homework\n",
- "Now, it's time to practice! The following problem will incorporate the following concepts:\n",
- "- Classes\n",
- " - Constructors\n",
- "- Methods\n",
- " - Void methods\n",
- " - Non-void methods\n",
- "- Math class\n",
- "- `Integer` and `Double` wrapper classes\n",
- "- String methods"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "public class Circle {\n",
- " // 1. Class variable: radius (double)\n",
- "\n",
- " // 2. Make a constructor that takes in the radius as a parameter, and sets the radius property\n",
- "\n",
- " // 3. cirumference() method: Calculate and return the circumference\n",
- "\n",
- " // 4. area() method: Calculate and return the area, use Math.pow()\n",
- "}\n",
- "\n",
- "public class Student {\n",
- " // 1. Class variables: name (String) and grade (Integer)\n",
- "\n",
- " // 2. Constructor to initialize name and grade\n",
- "\n",
- " // 3. nameLength() method: Return the length of the student's name\n",
- "\n",
- " // 4. getGradeAsDouble() method: Return the grade as the Double wrapper type\n",
- "\n",
- " // 5. getScaledGrade() method: Return grade divided by 2\n",
- "}\n",
- "\n",
- "public class Main {\n",
- " public static void main(String[] args) {\n",
- " // Testing the Circle class\n",
- " Circle circle1 = new Circle(5.0);\n",
- " Circle circle2 = new Circle(7.0);\n",
- "\n",
- " System.out.println(\"Circle 1:\");\n",
- " System.out.println(\"Radius: \" + circle1.radius);\n",
- " System.out.println(\"Circumference: \" + circle1.circumference());\n",
- " System.out.println(\"Area: \" + circle1.area());\n",
- "\n",
- " System.out.println(\"\\nCircle 2:\");\n",
- " System.out.println(\"Radius: \" + circle2.radius);\n",
- " System.out.println(\"Circumference: \" + circle2.circumference());\n",
- " System.out.println(\"Area: \" + circle2.area());\n",
- "\n",
- " // Testing the Student class\n",
- " Student student1 = new Student(\"Aadit\", 75);\n",
- " Student student2 = new Student(\"Emily\", 45);\n",
- "\n",
- " System.out.println(\"\\nStudent 1:\");\n",
- " System.out.println(\"Name: \" + student1.name);\n",
- " System.out.println(\"Name Length: \" + student1.nameLength());\n",
- " System.out.println(\"Grade: \" + student1.getGradeAsDouble());\n",
- " System.out.println(\"Scaled Grade: \" + student1.getScaledGrade());\n",
- "\n",
- " System.out.println(\"\\nStudent 2:\");\n",
- " System.out.println(\"Name: \" + student2.name);\n",
- " System.out.println(\"Name Length: \" + student2.nameLength());\n",
- " System.out.println(\"Grade: \" + student2.getGradeAsDouble());\n",
- " System.out.println(\"Scaled Grade: \" + student2.getScaledGrade());\n",
- " }\n",
- "}"
- ]
- }
- ],
- "metadata": {
- "kernelspec": {
- "display_name": "java (IJava/j!)",
- "language": "java",
- "name": "jbang-ijava"
- },
- "language_info": {
- "name": "java"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_02/Period3/2024-09-12-Unit_2_home.ipynb b/_notebooks/CSA/units_1_to_10/unit_02/Period3/2024-09-12-Unit_2_home.ipynb
deleted file mode 100644
index f4af7984..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_02/Period3/2024-09-12-Unit_2_home.ipynb
+++ /dev/null
@@ -1,71 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "title: Unit 2 — Using Objects\n",
- "description: The homepage for unit 2.\n",
- "type: collab\n",
- "toc: true\n",
- "permalink: /csa/unit2/period3/home/\n",
- "menu: nav/CSA_Units/unit2/period3.html\n",
- "comments: true\n",
- "courses: { csa: {week: 5} }\n",
- "type: ccc\n",
- "categories: [AP CSA]\n",
- "author: Aadit Mathur, Eric Yu, Shuban Pal, Rahul Verma\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# Unit 2 - Using Objects\n",
- "\n",
- "This is one of the **most important** concepts in Java. Buckle up and pay attention!\n",
- "\n",
- "\n",
- "## Learning Goals\n",
- "- Understand classes and objects as a concept\n",
- " - Learn about attributes and methods\n",
- "- Learn about the String class and its methods\n",
- "- Learn about the wrapper classes for primitives\n",
- "- Learn about the Math module\n",
- "\n",
- "## Demos\n",
- "- Book (what are objects?)\n",
- "- Rubiks cube (methods and classes)\n",
- "- Box (autoboxing/unboxing)\n",
- "\n",
- "## In-Class Activities\n",
- "- Method golf (method signatures)\n",
- "- Shooting hoops (MC practice)\n",
- "\n",
- "## Resources\n",
- "- [Programiz](https://www.programiz.com/java-programming/class-objects)\n",
- " - Brief overview\n",
- "- W3Schools [objects](https://www.w3schools.com/java/java_classes.asp), [strings](https://www.w3schools.com/java/java_strings.asp), and [math](https://www.w3schools.com/java/java_math.asp)\n",
- " - More detailed explanations\n",
- "- [AP Classroom](https://apclassroom.collegeboard.org/)\n",
- " - Everything needed for the AP exam in this unit\n",
- "- Official documentation for [objects](https://docs.oracle.com/javase/8/docs/api/java/util/Objects.html), [strings](https://docs.oracle.com/en/java/javase/22/docs/api/java.base/java/lang/String.html), and [math](https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html)\n",
- " - Very detailed\n"
- ]
- }
- ],
- "metadata": {
- "language_info": {
- "name": "python"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_02/Period3/2024-09-12-Unit_2_part1.ipynb b/_notebooks/CSA/units_1_to_10/unit_02/Period3/2024-09-12-Unit_2_part1.ipynb
deleted file mode 100644
index 848aafdf..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_02/Period3/2024-09-12-Unit_2_part1.ipynb
+++ /dev/null
@@ -1,305 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "title: Unit 2 — Objects & Void Methods\n",
- "description: An introduction to objects and void methods.\n",
- "type: collab\n",
- "toc: true\n",
- "permalink: /csa/unit2/period3/part1/\n",
- "menu: nav/CSA_Units/unit2/period3.html\n",
- "comments: true\n",
- "author: Aadit Mathur, Eric Yu, Shuban Pal, Rahul Verma\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# Objects"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## What are objects?\n",
- "\n",
- "Brief note: The text here is useful for following along and reviewing after the lesson. However, for the best experience, I'd recommend you simply pay attention to the presentation and run the code as you go.\n",
- "\n",
- "Let's say we have a book. This book has several properties, such as a title, author, and publisher. We can represent this with a few variables in our code.\n",
- "\n",
- " \n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "class Main {\n",
- " public static void main(String[] args) {\n",
- " String title = \"The Guide to Failure\";\n",
- " String author = \"Aadit Mathur\";\n",
- " String publisher = \"The Crusaders of FreeBSD\";\n",
- " String content = \"...\";\n",
- "\n",
- " System.out.println(\"The title of the book is \" + title);\n",
- " System.out.println(\"The author of the book is \" + author);\n",
- " System.out.println(\"The publisher of the book is \" + publisher);\n",
- " }\n",
- "}\n",
- "\n",
- "Main.main(new String[]{});"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "That's all well and dandy, until we want to add another book."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "class Main {\n",
- " public static void main(String[] args) {\n",
- " String book1_title = \"The Guide to Failure\";\n",
- " String book1_author = \"Aadit Mathur\";\n",
- " String book1_publisher = \"The Crusaders of FreeBSD\";\n",
- " String book1_content = \"...\"; // placeholder\n",
- "\n",
- " System.out.println(\"The title of the book is \" + book1_title);\n",
- " System.out.println(\"The author of \" + book1_title + \" is \" + book1_author);\n",
- " System.out.println(\"The publisher of \" + book1_title + \" is \" + book1_publisher);\n",
- "\n",
- " String book2_title = \"The Tragedy of Mr. Mortensen, Teacher of A101\";\n",
- " String book2_author = \"Shuban Pal\";\n",
- " String book2_publisher = \"The Crusaders of FreeBSD\";\n",
- " String book2_content = \"...\";\n",
- "\n",
- " System.out.println(\"The title of the book is \" + book2_title);\n",
- " System.out.println(\"The author of \" + book2_title + \" is \" + book2_author);\n",
- " System.out.println(\"The publisher of \" + book2_title + \" is \" + book2_publisher);\n",
- " }\n",
- "}\n",
- "\n",
- "Main.main(new String[]{});"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Within a second, our simple program has turned into a mess. Also, although we named our variables in a wway that allows us to see that theyre related, it would be nice if we could group these attributes together.\n",
- "\n",
- "### Introducing... classes! ✨\n",
- "Classes are a way for us to logically group these attributes and behaviors together. 😋"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "class Book {\n",
- " public String title;\n",
- " public String author;\n",
- " public String publisher;\n",
- " public String content;\n",
- " public int pages;\n",
- "\n",
- " public Book(String title, String author, String publisher, String content, int pages) {\n",
- " this.title = title;\n",
- " this.author = author;\n",
- " this.publisher = publisher;\n",
- " this.content = content;\n",
- " this.pages = pages;\n",
- " }\n",
- "\n",
- " public Book(String title, String author, String publisher, String content) {\n",
- " this.title = title;\n",
- " this.author = author;\n",
- " this.publisher = publisher;\n",
- " this.content = content;\n",
- " this.pages = 0;\n",
- " }\n",
- "}\n",
- "\n",
- "class Main {\n",
- " public static void main(String[] args) {\n",
- " Book book1 = new Book(\"The Guide to Failure\", \"Aadit Mathur\", \"Crusaders of FreeBSD\", \"...\", 50);\n",
- " \n",
- " System.out.println(\"The title of the book is \" + book1.title);\n",
- " System.out.println(\"The author of \" + book1.title + \" is \" + book1.author);\n",
- " System.out.println(\"The publisher of \" + book1.title + \" is \" + book1.publisher);\n",
- " \n",
- " Book book2 = new Book(\n",
- " \"The Tragedy of Mr. Mortensen, Teacher of A101\",\n",
- " \"Shuban Pal\",\n",
- " \"Crusaders of FreeBSD\",\n",
- " \"...\"\n",
- " );\n",
- "\n",
- " System.out.println(\"The title of the book is \" + book2.title);\n",
- " System.out.println(\"The author of \" + book2.title + \" is \" + book2.author);\n",
- " System.out.println(\"The publisher of \" + book2.title + \" is \" + book2.publisher);\n",
- " }\n",
- "}\n",
- "\n",
- "Main.main(new String[]{});"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "There are a few things to note here:\n",
- "- **Classes as Blueprints**: The class, Book, acts as a blueprint for creating objects, such as our book, \"The Guide to Failure\"\n",
- "- **Objects**: These are different `Book`s made using our \"blueprint\"\n",
- " - Each of these books (i.e. the things made using our class) are usually called \"instances\" of the class\n",
- "- **Types**: The `Book` class is a type that can be used like something such as a `String`\n",
- "- **The `new` Keyword**: This allows us to create an object of type `Book`\n",
- "- **Constructors**: When we make a `new Book()`, the arguments passed in are matched to the correct constructor, a special function which creates a new instance\n",
- "- **Class-wide variables**: These variables can be accessed with the dot operator\n",
- "- **Dot operator**: Allows us to access class variables\n",
- "- **The `this` Keyword**: Allows us to access class variables from inside the class\n",
- "\n",
- "As you can see, classes allows us to create repeated objects without wasting so many lines of code! In the grand scheme of software development, this greatly helps simplify our code. Even if right now it may seem useless, it is extremely important in the long run.\n",
- "\n",
- "![image](https://github.com/user-attachments/assets/c1b8a119-2ed3-408c-81ec-b4124c3e8cff)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## PRACTICE: Objects\n",
- "Now, we'll see if you understand the concept of classes and objects.\n",
- "\n",
- "Try and create a class in the following code space to represent a dog."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "class Dog {\n",
- " ...\n",
- "}\n",
- "\n",
- "public class Main {\n",
- " public static void main(String[] args) {\n",
- " Dog myDog = new Dog(\"Shelby\", \"Golden Retriever\", 5); // name, breed, age\n",
- " myDog.bark(); // should print \"Woof!\"\n",
- " }\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Non-Void Methods\n",
- "Objects can group attributes together, but they can also group together behaviors. Let's see an example."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "class Book {\n",
- " public String title;\n",
- " public String author;\n",
- " public String publisher;\n",
- " public String content;\n",
- " public int pages;\n",
- "\n",
- " public Book(String title, String author, String publisher, String content, int pages) {\n",
- " this.title = title;\n",
- " this.author = author;\n",
- " this.publisher = publisher;\n",
- " this.content = content;\n",
- " this.pages = pages;\n",
- " }\n",
- "\n",
- " public Book(String title, String author, String publisher, String content) {\n",
- " this.title = title;\n",
- " this.author = author;\n",
- " this.publisher = publisher;\n",
- " this.content = content;\n",
- " this.pages = 0;\n",
- " }\n",
- "\n",
- " public void printInformation() {\n",
- " System.out.println(\"The book \\\"\" + this.title + \"\\\", written by \" + this.author + \" and published by \" + this.publisher + \" has \" + Integer.toString(this.pages) + \" pages.\");\n",
- " }\n",
- " \n",
- " public void printPage(int page, int charactersPerPage) {\n",
- " page -= 1;\n",
- " String pageContent = this.content.substring(charactersPerPage * page, charactersPerPage * (page+1));\n",
- " System.out.println(pageContent);\n",
- " }\n",
- "}\n",
- "\n",
- "public class Main {\n",
- " public static void main(String[] args) {\n",
- " Book myFaveBook = new Book(\n",
- " \"The Tragedy of Mr. Mortensen, Teacher of A101\",\n",
- " \"Shuban Pal\",\n",
- " \"Crusaders of FreeBSD\",\n",
- " \"A child is a monkey in its mother's eye. Yet that child dreams of going on a wild journey, far beyond her reach.\"\n",
- " 5\n",
- " );\n",
- " \n",
- " myFaveBook.printPage(1, 18);\n",
- " myFaveBook.printInformation();\n",
- " }\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Here, we were able to make our code much more readable. In addition, if we have more books in the future, it's likely that we'll reuse these functions. 😮 💨 😮 💨 😮 💨\n",
- "\n",
- "\n",
- "**Void Methods** are functions in classes which have no return value.\n",
- "\n",
- "❓ What is a return value? That's a surprise tool we'll save for later! 🤫🤫🤫"
- ]
- }
- ],
- "metadata": {
- "kernelspec": {
- "display_name": "java (IJava/j!)",
- "language": "java",
- "name": "jbang-ijava"
- },
- "language_info": {
- "name": "java"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_02/Period3/2024-09-12-Unit_2_part2.ipynb b/_notebooks/CSA/units_1_to_10/unit_02/Period3/2024-09-12-Unit_2_part2.ipynb
deleted file mode 100644
index 55728583..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_02/Period3/2024-09-12-Unit_2_part2.ipynb
+++ /dev/null
@@ -1,396 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "title: Unit 2 — Methods\n",
- "description: A more in-depth explanation of methods.\n",
- "type: collab\n",
- "toc: true\n",
- "permalink: /csa/unit2/period3/part2/\n",
- "menu: nav/CSA_Units/unit2/period3.html\n",
- "comments: true\n",
- "author: Aadit Mathur, Eric Yu, Shuban Pal, Rahul Verma\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Section 2.4: Calling a Void Method with Parameters\n",
- "\n",
- "### Small Recap: Methods in Python vs Java \n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "python"
- }
- },
- "outputs": [],
- "source": [
- "class Animal:\n",
- " def __init__(self, group):\n",
- " self.group = group\n",
- "\n",
- " def getInfo(self):\n",
- " if self.group == \"bird\":\n",
- " print(\"Birds: Have feathers, lay eggs, (most) can fly.\")\n",
- " elif self.group == \"mammal\":\n",
- " print(\"Mammals: Mammals are known for their big brains.\")\n",
- " elif self.group == \"fish\":\n",
- " print(\"Fish: Fish have gills to breathe underwater.\")\n",
- " elif self.group == \"reptile\":\n",
- " print(\"Reptiles: Reptiles are cold-blooded.\")\n",
- " elif self.group == \"amphibian\":\n",
- " print(\"Amphibian: Amphibians are ectothermic.\")\n",
- " else:\n",
- " print(\"Unknown animal group.\")\n",
- "\n",
- "# Example usage:\n",
- "shark = Animal(group=\"fish\")\n",
- "shark.getInfo()"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "class Animal {\n",
- " private String group;\n",
- "\n",
- " // Constructor to initialize the group\n",
- " public Animal(String group) {\n",
- " this.group = group;\n",
- " }\n",
- "\n",
- " // Method to print group information\n",
- " public void getInfo() {\n",
- " if (group.equals(\"bird\")) {\n",
- " System.out.println(\"Birds: Have feathers, lay eggs, (most) can fly.\");\n",
- " } else if (group.equals(\"mammal\")) {\n",
- " System.out.println(\"Mammals: Mammals are known for their big brains.\");\n",
- " } else if (group.equals(\"fish\")) {\n",
- " System.out.println(\"Fish: Fish have gills to breathe underwater.\");\n",
- " } else if (group.equals(\"reptile\")) {\n",
- " System.out.println(\"Reptiles: Reptiles are cold-blooded.\");\n",
- " } else if (group.equals(\"amphibian\")) {\n",
- " System.out.println(\"Amphibians: Amphibians are ectothermic.\");\n",
- " } else {\n",
- " System.out.println(\"Unknown group.\");\n",
- " }\n",
- " }\n",
- "\n",
- " public static void main(String[] args) {\n",
- " // Example usage\n",
- " Animal shark = new Animal(\"fish\");\n",
- " shark.getInfo();\n",
- " }\n",
- "}\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "- Python 🐍: Here, the method is `getInfo()` and it is provided by the `Animal` class. Whenever a new `Animal` class is declared, the `getInfo()` method can be used upon itself to get the info of the new class based on its group.\n",
- "\n",
- "- Java ☕: Here, the method is also `getInfo()` which is also provided by the animal class. This time, the Animal class can be initialized via `constructors`\n",
- "\n",
- "\n",
- "### Method Signatures\n",
- "\n",
- "A method signature is basically the piece of code which lists how the method should act before specific code is given to the method. \n",
- "\n",
- "For example, for the `main` function the signature states that the method is a `public` method, the method is a `static` method, the method returns a `void` type, and it takes in the argument `args[]` as a `String` type.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class Main {\n",
- " public static void main(String args[]) {\n",
- " System.out.println(\"📝 Main method is executed, method has nothing to return.\");\n",
- " }\n",
- "}\n",
- "\n",
- "Main.main(new String[]{});"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "In the code above, the method signature is `public static void main(String args[])` which is the standard way to write main methods in java. Here is an anatomy of each piece:\n",
- "\n",
- "- `public` ➡️ Make sure the method can be used outside of the `Main` class\n",
- "- `static` ➡️ Make sure the method is a feature packaged into the class and does not work based off of an instance of that class\n",
- "- `void` ➡️ The return type. If the method is set to return nothing, void must be the return type.\n",
- "- `name(type arg1, type argn)` ➡️ The name of the method. **Methods can be named!** The elements listed inside the parentheses next to the name of the method are parameters. They are the values which the method takes in. If the method is set to take no parameters, the parenthesis can be left empty (e.g. `name()`).\n",
- "\n",
- " \n",
- "\n",
- "- 👁️ Visibility Modifiers: `public` or `private`\n",
- "- 🔀 Optional: `static` or blank\n",
- "- 📩 Return Type: `void`, `int`, `char`, `double`, `String`, or any other datatype\n",
- "- 🔤 Name: Anything!\n",
- "- 📃 Parameter(s): A list of values that will be passed into the method in `type name` format\n",
- "\n",
- "### Method Parameters\n",
- "\n",
- "The Methodical Methods of the Java Method Parameter:\n",
- "- 1️⃣ RULE 1 - Parameters MUST be passed in order\n",
- "- 2️⃣ RULE 2 - Parameters MUST be separated by comma\n",
- "- 3️⃣ RULE 3 - Parameters MUST include a datatype specification and a name\n",
- "- 3️⃣ RULE 4 - Parameters MUST be referenced by their names inside the method\n",
- "\n",
- "**🤮🤢🗑️😭1️⃣ BAD 1️⃣😭🗑️🤢🤮**\n",
- "\n",
- "```java\n",
- "public static void funny_method(int funny_number, String funny_string) {\n",
- " System.out.println(funny_number);\n",
- " System.out.println(funny_string);\n",
- "}\n",
- "\n",
- "funny_method(\"cat\", 1);\n",
- "```\n",
- "\n",
- " \n",
- " \n",
- "\n",
- "**🤑💸🪙😎5️⃣ GOOD 5️⃣😎🪙💸🤑**\n",
- "\n",
- "```java\n",
- "// Initiate method\n",
- "public static void funny_method(int funny_number, String funny_string) {\n",
- " System.out.println(funny_number);\n",
- " System.out.println(funny_string);\n",
- "}\n",
- "\n",
- "// Call method\n",
- "funny_method(1, \"cat\");\n",
- "```\n",
- "\n",
- "### Method Overload\n",
- "\n",
- "Method overload occurs when a method has the same name but different parameters. \n",
- "\n",
- "For method overloading purposes, the method signature does NOT include the return type.\n",
- "\n",
- "Imagine you have a method called `printTwoNumbers()` and you had 3 implementations of it as shown below."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public void printTwoNumbers() {\n",
- " System.out.println(1);\n",
- " System.out.println(1);\n",
- "}\n",
- "\n",
- "public void printTwoNumbers(int number) {\n",
- " System.out.println(number);\n",
- " System.out.println(number);\n",
- "}\n",
- "\n",
- "public void printTwoNumbers(int number1, number2) {\n",
- " System.out.println(number1);\n",
- " System.out.println(number2);\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "For each of the 3 method calls below, what would happen?\n",
- "\n",
- "- Method call 1: `printTwoNumbers(2);`\n",
- "- Method call 2: `printTwoNumbers();`\n",
- "- Method call 3: `printTwoNumbers(5, 6);`\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "printTwoNumbers(2);\n",
- "printTwoNumbers();`\n",
- "printTwoNumbers(5, 6);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "When `printTwoNumbers(2)` was called, compiler started looking for a signature which had the name `printTwoNumbers` which took 1 parameter and as an int. \n",
- "\n",
- "When `printTwoNumbers()` was called, compiler started looking for a signature which had the name `printTwoNumbers` which took no parameters at all. \n",
- "\n",
- "When `printTwoNumbers(2)` was called, compiler started looking for a signature which had the name `printTwoNumbers` which took 2 parameter and both as an ints. "
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Section 2.5: Calling a Non-Void\n",
- "\n",
- "### What is a Non-Void Method?\n",
- "\n",
- "A non-void method is a method which has a defined return type. This return type is stated in the function's signature. As a recap from earlier, we made a bullet list of every component inside of a method's signature. Here is a recap of the return type segment of a method's signature.\n",
- "\n",
- "📩 Return Type: `void`, `int`, `char`, `double`, `String`, or any other datatype\n",
- "\n",
- "Here is a list of signatures. For each signature, you must be able to tell whether the method corresponding to that signature will be a non-void method or not.\n",
- "\n",
- "1. `public static int function_1(String string)`\n",
- "2. `private static void function_2(int number)`\n",
- "3. `public double function_3(int number)`\n",
- "4. `private void function_4(double funnyDouble)`\n",
- "5. `private int function_5(double notFunnyDouble)`\n",
- "6. `public void function_6(char funnyChar)`"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class MathMachine {\n",
- " private static boolean isEven(int num) {\n",
- " if (num%2 == 0) {\n",
- " return true;\n",
- " } else {\n",
- " return false;\n",
- " }\n",
- " }\n",
- "\n",
- " public static void getEvenOrOdd(int num) {\n",
- " if (isEven(num) == true) {\n",
- " System.out.println(\"Number is even\");\n",
- " } else {\n",
- " System.out.println(\"Number is odd\");\n",
- " }\n",
- " }\n",
- "}\n",
- "\n",
- "MathMachine.getEvenOrOdd(2);\n",
- "MathMachine.getEvenOrOdd(3);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "In the example above, the class `isEven` is a Non-Void method while `getEvenOrOdd` is not. \n",
- "\n",
- "In a Non-Void method, there is always a type to be returned. This value is essentually what calling the method will equal to based on the parameter it is called upon.\n",
- "\n",
- "In the case of `isEven`, the return type was a boolean or a datatype which stores either true or false. \n",
- "\n",
- "Accordingly, whenever `isEven` was called as a method, its assignment would be to whatever value was returned based on its parameter."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Calling Non-Void Methods\n",
- "\n",
- "Calling a Non-Void method is the same as calling a void method, except a return value is produced and assigned to the call. \n",
- "\n",
- "Due to this sort of structure, non-void methods are classically used when comparing return values. For example, in the case of `isEven`:\n",
- "\n",
- "```java\n",
- "private static boolean isEven(int num) {\n",
- " if (num%2 == 0) {\n",
- " return true;\n",
- " } else {\n",
- " return false;\n",
- " }\n",
- "}\n",
- "```\n",
- "\n",
- "The return type is a boolean. \n",
- "\n",
- "So whenever `isEven(n)` is referenced, where n is an integer, the value of `isEven(n)` gets assigned to either true or false based on the value of n or any underlying logic inside the method. \n",
- "\n",
- "That is why in the code below, `isEven(n)` can be compared directly to a tangiable boolean value.\n",
- "\n",
- "```java\n",
- "public static void getEvenOrOdd(int num) {\n",
- " if (isEven(num) == true) {\n",
- " System.out.println(\"Number is even\");\n",
- " } else {\n",
- " System.out.println(\"Number is odd\");\n",
- " }\n",
- "}\n",
- "```\n",
- "\n",
- "## PRACTICE Calling Methods: Method Golf 😋\n",
- "\n",
- "⛳ Link to Method Golf: https://shuban-789.github.io/Shuban-CSA/2024/09/18/method-golf.html"
- ]
- }
- ],
- "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": "11.0.24+8-post-Ubuntu-1ubuntu322.04"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_02/Period3/2024-09-13-Unit_2_part3.ipynb b/_notebooks/CSA/units_1_to_10/unit_02/Period3/2024-09-13-Unit_2_part3.ipynb
deleted file mode 100644
index 691a0d71..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_02/Period3/2024-09-13-Unit_2_part3.ipynb
+++ /dev/null
@@ -1,492 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "title: Unit 2 — String Objects\n",
- "description: An explanation of how String objects work.\n",
- "type: collab\n",
- "toc: true\n",
- "permalink: /csa/unit2/period3/part3/\n",
- "menu: nav/CSA_Units/unit2/period3.html\n",
- "comments: true\n",
- "author: Aadit Mathur, Eric Yu, Shuban Pal, Rahul Verma\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "vscode": {
- "languageId": "plaintext"
- }
- },
- "source": [
- "# String Objects - Concatenation, Literals, and More\n",
- "\n",
- "## Creating Strings:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class StringObjects\n",
- "{\n",
- " public static void main(String[] args)\n",
- " {\n",
- " String name1 = \"Skibidi\";\n",
- " String name2 = new String(\"Sigma\");\n",
- " String name3 = new String(name1);\n",
- "\n",
- " System.out.println(name1);\n",
- " System.out.println(name2);\n",
- " System.out.println(name3);\n",
- " }\n",
- "}\n",
- "\n",
- "StringObjects.main(null);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "\n",
- "## 📝 Three Ways to Create a String: Let's Break it Down!\n",
- "\n",
- "---\n",
- "\n",
- "#### **First Option:**\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "String name1 = \"Skibidi\";"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "This method of creating a string consists of the following three parts: \n",
- "\n",
- "1. Class Name — Defines the type of variable (String, Integer, Array, etc.)\n",
- "\n",
- "2. Variable Name — The name assigned to the variable. This is how the variable will be referenced in the rest of the program. \n",
- "\n",
- "3. String Value — The actual value you'd like to assign to the variable\n",
- "\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### **Second Option:**"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "String name2 = new String(\"Sigma\");"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "\n",
- "This method is similar to option one but consists of a few extra components (indicated in pink coloring below):\n",
- "\n",
- "1. Class Name — Again, defines the type of the variable (String, Integers, Arrays, etc.)\n",
- "\n",
- "2. Variable Name — How the variable will be referenced in the rest of the program\n",
- "\n",
- "3. new — A Java keyword which is used to explicitly instantiate a new object.\n",
- "\n",
- "4. Class Name (Part 2) — The 'new' key word must be followed with the class name of the object being created (in this case, String)\n",
- "\n",
- "5. String Value — The actual value you'd like to assign to this variable\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "\n",
- "### **Third Option:**"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "String string1 = \"YIPEE\"\n",
- "String name2 = new String(string1);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Finally, a string can be created using the value of another, existing string object. The components needed for this declaration are as follows:\n",
- "\n",
- "1. Class Name — Again, type of variable will it be? (String, Integers, Arrays, etc.)\n",
- "\n",
- "2. Variable Name — The name of the variable\n",
- "\n",
- "3. Java Keyword 'new' — The new keyword in Java is used to explicitly create a new object.\n",
- "\n",
- "4. Class Name (Part 2) — As indicated before, the new keyword has to be followed with the class name of the object being created.\n",
- "\n",
- "5. Variable Name (Part 2) — The name of the variable whose value you want the new variable to take on. \n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "**Importantly**, regardless of which creation method you choose, String objects are immutable. This means that every time you attempt to change the value of some string variable, under the hood, a *new* string object is created with the updated value, and your variable name is used to reference this new object."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 📝 What is concatentation?\n",
- "\n",
- "Concatenation allows you to add strings together.\n",
- "\n",
- "There are two primary ways to combine strings. Assume `a`, `b`, and `c` are previously created string variables. \n",
- "\n",
- "- `a += b` : Appends the string value stored in `b` to the string value stored in `a`. In the processs, `a` is redefined to equal this newly appended string. \n",
- "- `c = a + b` : Joins the string values of `a` and `b` together, but doesn't redefine either `a` or `b`. Instead, the resultant value is assigned to `c`. "
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class Concatentations\n",
- "{\n",
- " public static void main(String[] args)\n",
- " {\n",
- " String name1 = \"Skibidi\";\n",
- " String name2 = new String(\"Sigma\");\n",
- " String name3 = new String(name1);\n",
- "\n",
- " int number1 = 1;\n",
- " int number2 = 2;\n",
- " String combine = name1 + \"\" + number1;\n",
- " name1 += number2; \n",
- "\n",
- " System.out.println(name1); \n",
- " System.out.println(combine);\n",
- " }\n",
- "}\n",
- "\n",
- "Concatentations.main(null);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Let's do an exercise for practice! What will the following code segment print?"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class Concatentations\n",
- "{\n",
- " public static void main(String[] args)\n",
- " {\n",
- " String name1 = \"Skibidi\";\n",
- " String name2 = new String(\"Sigma\");\n",
- " String name3 = new String(name1);\n",
- "\n",
- " name1 += \"!!\"\n",
- " String mystery = name1 + name2 + name3\n",
- "\n",
- " System.out.println(mystery);\n",
- " }\n",
- "}\n",
- "\n",
- "// Uncomment the following method call to run the code and check your answer!\n",
- "// Concatentations.main(null);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 📝 Backwards and Forwards Slashes\n",
- "\n",
- "In Java, there are a few characters with pre-assigned purposes. Backwards and forwards slashes are such characters, and they can be easy to mix up, so it's important to pay close attention to them!\n",
- "\n",
- "`\\`: Starts escape sequences. In other words, it can allow you to add special characters to your string.\n",
- "`/`: Usually used as a division operator. Two forward slashes indicate the beginning of a comment.\n",
- "\n",
- "\n",
- "### Backslashes\n",
- "\n",
- "`\\\"` = \"Escapes\" the quote, allowing for you to have quotes within a string without ending the string\n",
- "\n",
- "`\\\\` = Indicates a literal backslash in the string.\n",
- "\n",
- "`\\n` = A newline character\n",
- "\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class SlashDemo {\n",
- " public static void main(String[] args) {\n",
- " // Using backslashes for escape sequences:\n",
- " System.out.println(\"This is a double quote: \\\"\"); // Prints a double quote\n",
- " System.out.println(\"This is a backslash: \\\\\"); // Prints a backslash\n",
- " System.out.println(\"This prints on a new line:\\nSecond line starts here\");\n",
- "\n",
- " // Using forward slashes for division and comments:\n",
- " int a = 10;\n",
- " int b = 2;\n",
- " int result = a / b; // Division operation\n",
- "\n",
- " System.out.println(\"Result of 10 / 2 is: \" + result); // Prints the result of the division\n",
- " }\n",
- "}\n",
- "\n",
- "SlashDemo.main(null)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 📝 String methods\n",
- "The following are some important methods that can be used on String objects. \n",
- "\n",
- "| Method | Description |\n",
- "|-----------------------------------------|---------------------------------------------------------------------------------------------------------|\n",
- "| `String(String str)` | Creates a new `String` object with the same sequence of characters as the specified string `str` |\n",
- "| `int length()` | The number of characters in the `String` object |\n",
- "| `String substring(int from, int to)` | Returns the substring beginning at index from and ending at index to - 1. In other words, the start is inclusive and the end is exclusive. |\n",
- "| `String substring(int from)` | Returns `substring(from, length())` |\n",
- "| `int indexOf(String str)` | Returns the index of the first occurrence of `str`; returns `-1` if not found |\n",
- "| `boolean equals(String other)` | Returns `true` if the calling string is equal to `other`; returns `false` otherwise |\n",
- "| `int compareTo(String other)` | Returns a value < 0 if the calling string is alphanumerically less than other; returns 0 if it is equal to other; returns a value > 0 if it is alphanumerically greater than other. |\n",
- "\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class StringMethodDemo {\n",
- " public static void main(String[] args) {\n",
- " String wordOfDay = new String(\"Skibidi\");\n",
- "\n",
- " System.out.print(\"Characters in the word 'Skibidi' — \");\n",
- " System.out.println(wordOfDay.length());\n",
- "\n",
- " System.out.println(\"\\nThis should return -1, since there is no n in the string\");\n",
- " System.out.println(wordOfDay.lastIndexOf(\"n\"));\n",
- "\n",
- " System.out.println(\"\\nThis should display the index of d (5)\");\n",
- " System.out.println(wordOfDay.lastIndexOf(\"d\"));\n",
- " \n",
- " // NOTE: Start is inclusive, end is exclusive\n",
- " System.out.println(\"\\nThis should display the letters between the 2nd and 6th\");\n",
- " System.out.println(word.substring(2,6));\n",
- " }\n",
- "}\n",
- "\n",
- "StringMethodDemo.main(null)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "source": [
- "**Brief Aside**: Substring, like python slicing has the first index be inclusive and the last one be exclusive.\n",
- "\n",
- " "
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "source": [
- "Quick, let's do an exercise for practice! What will the following code segment return?"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class SubstringOfDemo {\n",
- " public static void main(String[] args) {\n",
- " String word = new String(\"skibidi\");\n",
- "\n",
- " System.out.println(\"\\nWhat is printed if we only pass one parameter into the substring method?\");\n",
- " System.out.println(word.substring(2));\n",
- " }\n",
- "}\n",
- "\n",
- "// Uncomment the following method call to run the code and check your answer!\n",
- "// SubstringOfDemo.main(null)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class CompareToDemo {\n",
- " public static void main(String[] args) {\n",
- " String word = new String(\"skibidi\");\n",
- " String word2 = new String(\"skibidi1\");\n",
- " String word3 = new String(\"skibidi\");\n",
- "\n",
- " System.out.println(\"\\nIf word is < word2, a negative value will be printed. If they are equal, 0 will be printed, and if word > word2, a positive value is printed\");\n",
- " System.out.println(word.compareTo(word2));\n",
- "\n",
- " System.out.println(\"\\nComparison between word and word3\");\n",
- " System.out.println(word.compareTo(word3));\n",
- " }\n",
- "}\n",
- "\n",
- "CompareToDemo.main(null)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class EqualToDemo {\n",
- " public static void main(String[] args) {\n",
- " String word = new String(\"skibidi\");\n",
- " String word2 = new String(\"skibidi1\");\n",
- " String word3 = new String(\"skibidi\");\n",
- "\n",
- " System.out.println(\"\\nThis displays if word1 = word2, if false it returns false, if true it returns true\");\n",
- " System.out.println(word.equals((word2)));\n",
- "\n",
- " System.out.println(\"\\nThis displays if word1 = word3, if false it returns false, if true it returns true\");\n",
- " System.out.println(word.equals((word3)));\n",
- " }\n",
- "}\n",
- "\n",
- "EqualToDemo.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": "11.0.24+8-post-Ubuntu-1ubuntu322.04"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_02/Period3/2024-09-16-Unit_2_part4.ipynb b/_notebooks/CSA/units_1_to_10/unit_02/Period3/2024-09-16-Unit_2_part4.ipynb
deleted file mode 100644
index a7e26541..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_02/Period3/2024-09-16-Unit_2_part4.ipynb
+++ /dev/null
@@ -1,310 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "title: Unit 2 — Wrapper Classes & Math Module\n",
- "description: An introduction to what wrapper classes and the Math module are.\n",
- "type: collab\n",
- "toc: true\n",
- "permalink: /csa/unit2/period3/part4/\n",
- "menu: nav/CSA_Units/unit2/period3.html\n",
- "comments: true\n",
- "author: Aadit Mathur, Eric Yu, Shuban Pal, Rahul Verma\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# Lesson 2.8: Wrapper Classes! 🍫\n",
- "\n",
- "## Introduction\n",
- "\n",
- "By now, you should be used to working with different variables and data types in Java. Some of you may have asked a question regarding why the data type String has a capital S, while int is not capitalized.\n",
- "\n",
- "The answer is: String is a reference type, while int is a primitive type.\n",
- "\n",
- "Primitive types are the mosic basic data types in Java, and they always represent single values. On the other hand, Reference types are used to store objects and can have a variety of things stored.\n",
- "\n",
- "## Important Wrapper Classes 🔢🔠\n",
- "- `Integer` for `int`\n",
- "- `Double` for `double`\n",
- "\n",
- "These classes are part of the `java.lang` package, so you don't need to import them explicitly. Additionally, there are more wrapper classes, but these are the two that are required by College Board.\n",
- "\n",
- "But let's back off real quick. What is a Wrapper class?\n",
- "\n",
- "Answer: A wrapper class allows you to use primitive data types.\n",
- "\n",
- "### Integer Wrapper Class 🔢\n",
- "The `Integer` class wraps a value of the primitive type `int` in an object.\n",
- "\n",
- " \n",
- "\n",
- "#### Methods & Constants\n",
- "1. Constructor: `Integer (int value)`: Constructs a new `Integer` object representing the specified `int` value.\n",
- "2. `Integer.MIN_VALUE` and `Integer.MAX_VALUE` returns the minimum/maximum value that an `int` can hold. Going beyound these borders will lead to overflow.\n",
- "3. `int intValue()`: Returns the value of the `Integer` as an `int`\n",
- "\n",
- "Let's take a look at an example:\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "public class Main {\n",
- " public static void main(String[] args){\n",
- " Integer num1 = new Integer(5); // Constructor usage \n",
- "\n",
- " System.out.println(\"num1 = \" + num1);\n",
- " System.out.println(\"num2 = \" + num2);\n",
- " System.out.println(\"Maximum value of Integer: \" + Integer.MAX_VALUE);\n",
- " System.out.println(\"Minimum value of Integer: \" + Integer.MIN_VALUE);\n",
- " System.out.println(\"num1 as int: \" + num1.intValue());\n",
- " }\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Double Wrapper Class 📦\n",
- "\n",
- "The `Double` class wraps a value of the primitive type `double` in an object.\n",
- "\n",
- "#### Important Methods\n",
- "1. Constructor: `Double(double value)`: Constructs a new `Double` object representing the specified `double` value.\n",
- "2. `double doubleValue()`: Returns the value of the `Double` as a `double`\n",
- "\n",
- "Let's take a look at another example."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "public class Main {\n",
- " public static void main(String[] args){\n",
- " Double pi = new Double(3.14159); \n",
- " Double e = Double.valueOf(2.71828);\n",
- "\n",
- " System.out.println(\"pi = \" + pi);\n",
- " System.out.println(\"e = \" + e);\n",
- " System.out.println(\"pi as double: \" + pi.doubleValue());\n",
- " }\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Autoboxing and Unboxing\n",
- "\n",
- "Java gives you automatic conversion between primitive types and their respective wrapper classes\n",
- "\n",
- "- Autoboxing: Primitive Value ➡️ Wrapper Object\n",
- "- Unboxing: Wrapper object ➡️ Primitive Value\n",
- "\n",
- "![model](https://i.postimg.cc/tgH0s2JS/Screenshot-2024-09-24-002832.png)\n",
- "\n",
- "Let's take a look at a short example."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "public class BoxDemo {\n",
- " public static void demo(String[] args) {\n",
- " Integer wrapped = 100; // Autoboxing\n",
- " int unwrapped = wrapped; // Unboxing\n",
- "\n",
- " System.out.println(\"📦wrapped = \" + wrapped);\n",
- " System.out.println(\"unwrapped = \" + unwrapped);\n",
- " }\n",
- "}\n",
- "\n",
- "BoxDemo.demo(new String[]{});"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# Practice Exercises\n",
- "\n",
- "Fix the code below!"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 5,
- "metadata": {},
- "outputs": [],
- "source": [
- "public class Main {\n",
- " public static void main(String[] args) {\n",
- " integer num1 = 50;\n",
- " Integer num2 = new Integer(75);\n",
- " \n",
- " Double d1 = 3.14;\n",
- " double d2 = new Double(2.718);\n",
- " \n",
- " System.out.println(\"Sum of integers: \" + (num1 + num2));\n",
- " System.out.println(\"Product of doubles: \" + (d1 * d2));\n",
- " }\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Now, complete the exercise below without any extra help."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 6,
- "metadata": {},
- "outputs": [],
- "source": [
- "public class Main {\n",
- " public static void main(String[] args) {\n",
- " // TODO: Create an Integer object using autoboxing\n",
- " \n",
- " // TODO: Create a double primitive from a Double object (unboxing)\n",
- " \n",
- " // TODO: Print both values\n",
- " }\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# 2.9: Using the Math Module 📝\n",
- "\n",
- "Have you ever been stuck in your Calculus or Physics class because your calculator died?\n",
- "\n",
- " \n",
- "\n",
- "You can use the Java math module to help you 😁!\n",
- "\n",
- "## Introduction\n",
- "The Java math module is a package that comes with `java.lang.Math`. All it's methods are static.\n",
- "\n",
- "This is more straightforward than wrapper classes, but still important to know.\n",
- "\n",
- "## Useful Methods\n",
- "1. `static int abs(int x)`: Returns the absolute value of an `int`\n",
- "2. `static double abs(double x)`: Returns the absolute value of a `double`\n",
- "3. `static double pow(double base, double exponent)`: Returns the value of the first value raised to the power of the second value\n",
- "4. `static double sqrt(double x)`: Returns the (positive) square root of a double value\n",
- "5. `static double random()`: Returns a `double` greater than or equal to 0.0 and less than 1.0\n",
- "\n",
- "Let's take a look at a code example using all of these!"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 7,
- "metadata": {},
- "outputs": [],
- "source": [
- "public class Main {\n",
- " public static void main(String[] args) {\n",
- " // abs() method for int and double\n",
- " int intNumber = -5;\n",
- " double doubleNumber = -10.5;\n",
- " System.out.println(\"Absolute value of \" + intNumber + \" is: \" + Math.abs(intNumber));\n",
- " System.out.println(\"Absolute value of \" + doubleNumber + \" is: \" + Math.abs(doubleNumber));\n",
- "\n",
- " // pow() method\n",
- " double base = 2.0;\n",
- " double exponent = 3.0;\n",
- " System.out.println(base + \" raised to the power of \" + exponent + \" is: \" + Math.pow(base, exponent));\n",
- "\n",
- " // sqrt() method\n",
- " double number = 16.0;\n",
- " System.out.println(\"Square root of \" + number + \" is: \" + Math.sqrt(number));\n",
- "\n",
- " // random() method\n",
- " System.out.println(\"A random number between 0.0 and 1.0: \" + Math.random());\n",
- " }\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## PRACTICE\n",
- "\n",
- "Let's try a practice! Fill in the function below, `randomize`, following the steps below:\n",
- "\n",
- "1. Take the absolute value of both numbers\n",
- "2. Return a random number in between those two numbers, inclusive"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "import java.util.*;\n",
- "public class Main {\n",
- " public double randomize(double a, double b){\n",
- " // TODO: Enter code here! Don't forget a return statement\n",
- " }\n",
- " public static void main(String[] args) {\n",
- " Scanner scan = new Scanner(System.in);\n",
- " double a = scan.nextDouble();\n",
- " double b = scan.nextDouble();\n",
- "\n",
- " System.out.println(randomize(a, b));\n",
- " }\n",
- "}\n",
- "\n",
- "// The error will be returned below in the code cell"
- ]
- }
- ],
- "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": "17.0.12+7-Ubuntu-1ubuntu222.04"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_03/Period1/2024-09-12-U3-0-intro.ipynb b/_notebooks/CSA/units_1_to_10/unit_03/Period1/2024-09-12-U3-0-intro.ipynb
deleted file mode 100644
index fb0f1f67..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_03/Period1/2024-09-12-U3-0-intro.ipynb
+++ /dev/null
@@ -1,130 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "comments: true\n",
- "title: Unit 3 - Boolean P1 \n",
- "description: Unit 3 Team Teach\n",
- "categories: [AP CSA]\n",
- "courses: {'csa': {'week': 5}}\n",
- "type: ccc\n",
- "menu: nav/CSA_Units/csa_unit3_p1.html\n",
- "permalink: /csa/unit3-p1/intro\n",
- "author: Alisha Hussain, Anika Bhatnagar, Kayden Le, Sharon Kodali\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## About Unit 3: Booleans\n",
- "\n",
- "- Learning Targets:\n",
- " - Boolean logic is a fundamental concept in computer science that deals with the manipulation and evaluation of true or false values\n",
- " - Named after the mathematician George Boole, who developed the algebraic system of logic in the 19th century\n",
- " - Boolean expressions are used to make decisions and control the flow of a program based on certain conditions\n",
- "\n",
- "- Why is it important:\n",
- " - Boolean logic is essential for implementing conditional statements, loops, and other control structures in programming\n",
- " - Allows programmers to create complex decision-making processes and algorithms\n",
- " - Understanding boolean logic is crucial for writing efficient and effective code in various programming languages, including Java\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "vscode": {
- "languageId": "html"
- }
- },
- "source": [
- "### Boolean Table \n",
- "\n",
- "\n",
- "\n",
- "
\n",
- "\n",
- ""
- ]
- }
- ],
- "metadata": {
- "kernelspec": {
- "display_name": "venv",
- "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.12.5"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_03/Period1/2024-09-12-U3-1-Boolean.ipynb b/_notebooks/CSA/units_1_to_10/unit_03/Period1/2024-09-12-U3-1-Boolean.ipynb
deleted file mode 100644
index 174413de..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_03/Period1/2024-09-12-U3-1-Boolean.ipynb
+++ /dev/null
@@ -1,152 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "comments: true\n",
- "title: Unit 3 Boolean Expressions - 3.1\n",
- "description: Unit 3 Team Teach\n",
- "categories: [AP CSA]\n",
- "menu: nav/CSA_Units/csa_unit3_p1.html\n",
- "permalink: /csa/unit3-p1/unit3-1\n",
- "author: Alisha Hussain, Anika Bhatnagar, Kayden Le, Sharon Kodali\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# 3.1 Boolean Expressions\n",
- "\n",
- " \n",
- "\n",
- "## Java's relational operators\n",
- "\n",
- "- equal to: ==\n",
- "- not equal to: !=\n",
- "- less than: <\n",
- "- greater than: >\n",
- "- less than or equal to: <=\n",
- "- greater than or equal to >="
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Hack! \n",
- "\n",
- "```\n",
- "int myAge = 15;\n",
- "int otherAge = 45; \n",
- "```\n",
- "using these integers, determine weather the following statements are True or False\n",
- "\n",
- " \n",
- "\n",
- "## Strings"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## popcorn hack \n",
- "whats wrong with this code? (below)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 1,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [
- {
- "ename": "CompilationException",
- "evalue": "",
- "output_type": "error",
- "traceback": [
- "\u001b[1m\u001b[30m| \u001b[1m\u001b[30mString myName = \u001b[0m\u001b[1m\u001b[30m\u001b[41mAlisha\u001b[0m\u001b[1m\u001b[30m;\u001b[0m",
- "\u001b[1m\u001b[31mcannot find symbol\u001b[0m",
- "\u001b[1m\u001b[31m symbol: variable Alisha\u001b[0m",
- ""
- ]
- }
- ],
- "source": [
- "\n",
- "String myName = Alisha;\n",
- "\n",
- "myName != Anika;\n",
- "myName == Alisha ;"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "comparison of string objects should be done using String methods, NOT integer methods. \n",
- "\n",
- "- .equal\n",
- "- compare to"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "String myName = \"Alisha\";\n",
- "boolean areNamesEqual = myName.equals(\"Alisha\"); \n",
- "\n",
- "if (areNamesEqual) {\n",
- " System.out.println(\"True\");\n",
- "} else {\n",
- " System.out.println(\"False\");\n",
- "}\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### homework question\n",
- " \n",
- "what is the precondition for num?"
- ]
- }
- ],
- "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": "17.0.12+8-LTS-286"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_03/Period1/2024-09-15-unit3_teamteach_3.2.ipynb b/_notebooks/CSA/units_1_to_10/unit_03/Period1/2024-09-15-unit3_teamteach_3.2.ipynb
deleted file mode 100644
index d29d9d6f..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_03/Period1/2024-09-15-unit3_teamteach_3.2.ipynb
+++ /dev/null
@@ -1,105 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "title: Unit 3 Team Teach - 3.2\n",
- "description: Unit 3 Team Teach\n",
- "comments: true\n",
- "menu: nav/CSA_Units/csa_unit3_p1.html\n",
- "permalink: /csa/unit3-p1/unit3-2\n",
- "author: Alisha Hussain, Anika Bhatnagar, Kayden Le, Sharon Kodali\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# 3.2 If Statements and Control Flow\n",
- " \n",
- "\n",
- " \n",
- " \n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### popcorn hack\n",
- "create test cases that do not satisy the condition above. you can copy/paste the code into the new code cell"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 1,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public static void main(String[] args) {\n",
- " int myAge = 16;\n",
- " System.out.println(\"Current age: \" + myAge);\n",
- " \n",
- " if (myAge >= 16) {\n",
- " System.out.println(\"You can start learning to drive!\");\n",
- " }\n",
- "\n",
- " System.out.println(\"On your next birthday, you will be \" + (myAge + 1) + \" years old!\");\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "If statements can be used to create chatbots \n",
- "--> Magpie Lab\n",
- " \n",
- "\n",
- " \n",
- "\n",
- "- the user’s input affects the flow of the program"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": []
- }
- ],
- "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": "17.0.12+8-LTS-286"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_03/Period1/2024-09-15-unit3_teamteach_3.3.ipynb b/_notebooks/CSA/units_1_to_10/unit_03/Period1/2024-09-15-unit3_teamteach_3.3.ipynb
deleted file mode 100644
index db15f296..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_03/Period1/2024-09-15-unit3_teamteach_3.3.ipynb
+++ /dev/null
@@ -1,123 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "title: Unit 3 Team Teach - 3.3\n",
- "description: Unit 3 Team Teach\n",
- "comments: true\n",
- "menu: nav/CSA_Units/csa_unit3_p1.html\n",
- "permalink: /csa/unit3-p1/unit3-3\n",
- "author: Alisha Hussain, Anika Bhatnagar, Kayden Le, Sharon Kodali\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# 3.3 If Else Statements\n",
- "\n",
- " \n",
- "## Purpose of Else Statements\n",
- "Else statements: Handles what happens when the if condition is false.\n",
- "Structure of If-Else:\n",
- "- If statement with a condition.\n",
- "- Else statement without a condition.\n",
- "- Both parts have code blocks surrounded by {}.\n",
- "\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# don't forget the brackets "
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 3,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [
- {
- "ename": "CompilationException",
- "evalue": "",
- "output_type": "error",
- "traceback": [
- "\u001b[1m\u001b[30m| \u001b[1m\u001b[30m \u001b[0m\u001b[1m\u001b[30m\u001b[41mconsole\u001b[0m\u001b[1m\u001b[30m.log(\"x is greater than 10\");\u001b[0m",
- "\u001b[1m\u001b[31mcannot find symbol\u001b[0m",
- "\u001b[1m\u001b[31m symbol: variable console\u001b[0m",
- "",
- "\u001b[1m\u001b[30m| \u001b[1m\u001b[30m \u001b[0m\u001b[1m\u001b[30m\u001b[41mconsole\u001b[0m\u001b[1m\u001b[30m.log(\"This code when the condition is true\");\u001b[0m",
- "\u001b[1m\u001b[31mcannot find symbol\u001b[0m",
- "\u001b[1m\u001b[31m symbol: variable console\u001b[0m",
- "",
- "\u001b[1m\u001b[30m| \u001b[1m\u001b[30m \u001b[0m\u001b[1m\u001b[30m\u001b[41mconsole\u001b[0m\u001b[1m\u001b[30m.log(\"x is 10 or less\");\u001b[0m",
- "\u001b[1m\u001b[31mcannot find symbol\u001b[0m",
- "\u001b[1m\u001b[31m symbol: variable console\u001b[0m",
- "",
- "\u001b[1m\u001b[30m| \u001b[1m\u001b[30m \u001b[0m\u001b[1m\u001b[30m\u001b[41mconsole\u001b[0m\u001b[1m\u001b[30m.log(\"This code runs when the condition is false\");\u001b[0m",
- "\u001b[1m\u001b[31mcannot find symbol\u001b[0m",
- "\u001b[1m\u001b[31m symbol: variable console\u001b[0m",
- ""
- ]
- }
- ],
- "source": [
- "int x = 20;\n",
- "if (x > 10) {\n",
- "\n",
- " console.log(\"x is greater than 10\");\n",
- " console.log(\"This code when the condition is true\");\n",
- " } else {\n",
- " \n",
- " console.log(\"x is 10 or less\");\n",
- " console.log(\"This code runs when the condition is false\");\n",
- "}\n",
- "// Without brackets:\n",
- " \n",
- " console.log(\"x is greater than 10\");\n",
- " console.log(\"this code will always run\");"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- " \n",
- "\n",
- "1. Based on this code, if you were younger than 16 what would it print out?\n",
- "2. Write your own if else statement"
- ]
- }
- ],
- "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": "17.0.12+0"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_03/Period1/2024-09-15-unit3_teamteach_3.4.ipynb b/_notebooks/CSA/units_1_to_10/unit_03/Period1/2024-09-15-unit3_teamteach_3.4.ipynb
deleted file mode 100644
index 741f6f37..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_03/Period1/2024-09-15-unit3_teamteach_3.4.ipynb
+++ /dev/null
@@ -1,53 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "title: Unit 3 Team Teach - 3.4\n",
- "description: Unit 3 Team Teach\n",
- "comments: true\n",
- "menu: nav/CSA_Units/csa_unit3_p1.html\n",
- "permalink: /csa/unit3-p1/unit3-4\n",
- "author: Alisha Hussain, Anika Bhatnagar, Kayden Le, Sharon Kodali\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# 3.4 Else If Statements \n",
- "Else If Statements: Used when you have multiple conditions that need to be checked sequentially.\n",
- "\n",
- "Flow of Execution: Each condition is evaluated in the order written. The first true condition's code runs, and the rest are skipped.\n",
- "\n",
- "Structure:\n",
- "\n",
- "- Start with a single if statement.\n",
- "- Follow with as many else if statements as needed.\n",
- "- Optionally end with one else to handle any remaining cases.\n",
- "Key Concept: The order of conditions matters. More specific conditions should come before broader ones to ensure accurate results.\n",
- "\n",
- " \n",
- "\n",
- "1. If I was 19 what would it print out? \n",
- "2. If I was 13 what would it print out? \n",
- "3. Create your if statement with one else if condition."
- ]
- }
- ],
- "metadata": {
- "language_info": {
- "name": "python"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_03/Period1/2024-09-15-unit3_teamteach_3.5.ipynb b/_notebooks/CSA/units_1_to_10/unit_03/Period1/2024-09-15-unit3_teamteach_3.5.ipynb
deleted file mode 100644
index c3e44e19..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_03/Period1/2024-09-15-unit3_teamteach_3.5.ipynb
+++ /dev/null
@@ -1,226 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "title: Unit 3 Team Teach - 3.5 Compound Booleans \n",
- "description: Unit 3 Team Teach\n",
- "comments: true\n",
- "menu: nav/CSA_Units/csa_unit3_p1.html\n",
- "permalink: /csa/unit3-p1/unit3-5\n",
- "author: Alisha Hussain, Anika Bhatnagar, Kayden Le, Sharon Kodali\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# 3.5 Compund Boolean expressions \n",
- "## Nested conditional statements \n",
- "\n",
- " \n",
- "\n",
- "definition: if statements within other if statements "
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class Main {\n",
- " public static void main(String[] args) {\n",
- " int age = 20;\n",
- " boolean isStudent = true;\n",
- "\n",
- " // Outer if-else block\n",
- " if (age >= 18) {\n",
- " // Nested if-else block inside the first condition\n",
- " if (isStudent) {\n",
- " System.out.println(\"You are an adult and a student.\");\n",
- " } else {\n",
- " System.out.println(\"You are an adult.\");\n",
- " }\n",
- " } else {\n",
- " System.out.println(\"You are not an adult.\");\n",
- " }\n",
- " }\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# Simple Example of a Nested Conditional Statement\n",
- "\n",
- "Let's look at a **very basic** example of a nested conditional statement using `if-else` blocks. \n",
- "\n",
- "### Scenario:\n",
- "We want to check if a person is an adult and, if they are, we want to know if they are also a student."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# Compound Conditional Statement\n",
- "\n",
- "A **compound conditional statement** is when two or more conditions are combined into a single `if` statement using **logical operators** like `&&` (AND), `||` (OR), or `!` (NOT). This allows us to check multiple conditions at once without needing to nest `if` statements.\n",
- "\n",
- "### Logical Operators:\n",
- "- `&&` (AND): True if **both** conditions are true.\n",
- "- `||` (OR): True if **at least one** condition is true.\n",
- "- `!` (NOT): Reverses the result of a condition (true becomes false, and false becomes true).\n",
- "\n",
- "### Example of a Compound Conditional Statement\n",
- "\n",
- "Let's say we want to check if a person is an **adult** and **a student** at the same time. Instead of using a nested `if` statement, we can use a compound conditional statement."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class Main {\n",
- " public static void main(String[] args) {\n",
- " int age = 20;\n",
- " boolean isStudent = true;\n",
- "\n",
- " // Compound conditional using && (AND)\n",
- " if (age >= 18 && isStudent) {\n",
- " System.out.println(\"You are an adult and a student.\");\n",
- " } else {\n",
- " System.out.println(\"Either you are not an adult, or you are not a student.\");\n",
- " }\n",
- " }\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### common mistake: Dangling else \n",
- " - Java does not care about indentation\n",
- " - else always belongs to the CLOSEST if\n",
- " - curly braces can be use to format else so it belongs to the FIRST 'if'\n",
- "\n",
- "### Popcorn hack\n",
- "- explain the purpose of this algorithm, and what each if condition is used for\n",
- "- what would be output if input is \n",
- " - age 20\n",
- " - anual income 1500\n",
- " - student status: yes"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "function checkMembershipEligibility() {\n",
- " // Get user input\n",
- " let age = parseInt(prompt(\"Enter your age:\")); // Age input\n",
- " let income = parseFloat(prompt(\"Enter your annual income:\")); // Annual income input\n",
- " let isStudent = prompt(\"Are you a student? (yes/no):\").toLowerCase() === 'yes'; // Student status input\n",
- "\n",
- " // Initialize an empty array to hold results\n",
- " let results = [];\n",
- "\n",
- " // Check eligibility for different memberships\n",
- "\n",
- " // Basic Membership\n",
- " if (age >= 18 && income >= 20000) {\n",
- " results.push(\"You qualify for Basic Membership.\");\n",
- " }\n",
- "\n",
- " // Premium Membership\n",
- " if (age >= 25 && income >= 50000) {\n",
- " results.push(\"You qualify for Premium Membership.\");\n",
- " }\n",
- "\n",
- " // Student Discount\n",
- " if (isStudent) {\n",
- " results.push(\"You are eligible for a Student Discount.\");\n",
- " }\n",
- "\n",
- " // Senior Discount\n",
- " if (age >= 65) {\n",
- " results.push(\"You qualify for a Senior Discount.\");\n",
- " }\n",
- "\n",
- " // If no eligibility, provide a default message\n",
- " if (results.length === 0) {\n",
- " results.push(\"You do not qualify for any memberships or discounts.\");\n",
- " }\n",
- "\n",
- " // Output all results\n",
- " results.forEach(result => console.log(result));\n",
- "}\n",
- "\n",
- "// Call the function to execute\n",
- "checkMembershipEligibility();"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Popcorn Hack #2\n",
- "- Write a program that checks if a person can get a discount based on their age and student status. You can define your own discount criteria! Use compound conditionals to determine the output."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class Main {\n",
- " public static void main(String[] args) {\n",
- " int age = 30; // Change this value for testing\n",
- " boolean isStudent = true; // Change this value for testing\n",
- "\n",
- " // Your compound conditional logic here\n",
- " }\n",
- "}"
- ]
- }
- ],
- "metadata": {
- "language_info": {
- "name": "python"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_03/Period1/2024-09-15-unit3_teamteach_3.6.ipynb b/_notebooks/CSA/units_1_to_10/unit_03/Period1/2024-09-15-unit3_teamteach_3.6.ipynb
deleted file mode 100644
index 3b2852fb..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_03/Period1/2024-09-15-unit3_teamteach_3.6.ipynb
+++ /dev/null
@@ -1,108 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {},
- "source": [
- "---\n",
- "layout: post\n",
- "title: Unit 3 Team Teach - 3.6 Equivalent Booleans \n",
- "description: Unit 3 Team Teach\n",
- "comments: true\n",
- "menu: nav/CSA_Units/csa_unit3_p1.html\n",
- "permalink: /csa/unit3-p1/unit3-6\n",
- "author: Alisha Hussain, Anika Bhatnagar, Kayden Le, Sharon Kodali\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 3.6 Equivalent Boolean Expressions \n",
- "- There are multiple ways to represent the same boolean expression. To show that the are the same expression, wither prove that they can be simplified to the same expression using boolean properties and identitied or prove that they can be the same in all cases. \n",
- "- Using De Morgan's Law to compare and contrast equivalent Boolean expressions "
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Logical operators reminder \n",
- "\n",
- "- **`&&` (AND)**: \n",
- " - Returns `true` only if both conditions are true.\n",
- " - Example: `(condition1 && condition2)` is true if both `condition1` and `condition2` are true.\n",
- "\n",
- "- **`||` (OR)**: \n",
- " - Returns `true` if at least one of the conditions is true.\n",
- " - Example: `(condition1 || condition2)` is true if either `condition1` or `condition2` (or both) are true.\n",
- "\n",
- "- **`!` (NOT)**: \n",
- " - Negates the value of a condition; returns `true` if the condition is false, and vice versa.\n",
- " - Example: `!(condition)` is true if `condition` is false.\n",
- " "
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# De Morgans Law \n",
- "\n",
- " \n",
- "\n",
- " "
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "#### Distributing a \"not\" with a Boolean expression 'flips' the relationsal operator to the opposite relational operator\n",
- "- ex: !(x > 0) is equivalent to (x<= 0)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Popcorn Hack \n",
- "\n",
- "### Challenge Questions\n",
- "\n",
- "1. **What is `!(x == 0)` equivalent to?**\n",
- " - Apply De Morgan's Law to find an equivalent expression.\n",
- "\n",
- "2. **Negate the expression `(x < -5 || x > 10)`.**\n",
- " - Use De Morgan's Law to rewrite this expression in a different form."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Truth Tables \n",
- "- evaluate and shoe equivalency in Boolean expressions \n",
- "- see al the possible outcomes that we will have. \n",
- "\n",
- " "
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- " "
- ]
- }
- ],
- "metadata": {
- "language_info": {
- "name": "python"
- },
- "orig_nbformat": 4
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_03/Period1/2024-09-15-unit3_teamteach_3.7.ipynb b/_notebooks/CSA/units_1_to_10/unit_03/Period1/2024-09-15-unit3_teamteach_3.7.ipynb
deleted file mode 100644
index 66530071..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_03/Period1/2024-09-15-unit3_teamteach_3.7.ipynb
+++ /dev/null
@@ -1,218 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "title: Unit 3 Team Teach - 3.7 Comparing Objects\n",
- "description: Unit 3 Team Teach\n",
- "comments: true\n",
- "menu: nav/CSA_Units/csa_unit3_p1.html\n",
- "permalink: /csa/unit3-p1/unit3-7\n",
- "author: Alisha Hussain, Anika Bhatnagar, Kayden Le, Sharon Kodali\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# 3.7 Comparing Objects\n",
- " \n",
- "## short-circuited evaluation: \n",
- "expression can be determined by only looking at the first operand. "
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "function isEven(num) {\n",
- " return num % 2 === 0;\n",
- "}\n",
- "\n",
- "function isPositive(num) {\n",
- " return num > 0;\n",
- "}\n",
- "\n",
- "let number = 10;\n",
- "\n",
- "// Short-circuit with &&\n",
- "if (isEven(number) && isPositive(number)) {\n",
- " console.log(number + \" is even and positive.\");\n",
- "} else {\n",
- " console.log(number + \" does not meet the criteria.\");\n",
- "}\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Short-Circuit Behavior:\n",
- "- && (Logical AND): The expression isEven(number) && isPositive(number) is evaluated.\n",
- " - JavaScript first evaluates isEven(number). - If this returns false, the whole expression will short-circuit, and isPositive(number) will not be evaluated.\n",
- "- If isEven(number) is true, then isPositive(number) is evaluated."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Comparing Objects\n",
- "\n",
- "In java there are two different methods to compare objects but there is a difference between the == operator and the equals() method."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "## == operator\n",
- "\n",
- "This operator verifies if two references refer to the same object in memory, without evaluating the objects' values or attributes."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "Integer num1 = 100;\n",
- "Integer num2 = 100;\n",
- "Integer num3 = num1;\n",
- "Integer num4 = new Integer(100);\n",
- "\n",
- "System.out.println(num1 == num3); // true (same reference)\n",
- "System.out.println(num1 == num2); // true (cached integers between -128 and 127)\n",
- "System.out.println(num1 == num4); // false (different references)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "This compares the integer as num1 == num3 because they both equal the same integer so it's true. num1 == num2 because when they are both assigned the value 100 they point to the same reference so they become true. num1 == num4 even though they have the same values they are different because it's a new integer so it becomes false because they don't have the same reference point."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## equals() method\n",
- "\n",
- "This method checks the values or attributes of two objects. In custom classes, it is commonly overridden to offer a meaningful comparison based on the class's specific attributes. It focuses on value rather reference points."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "Integer num1 = 100;\n",
- "Integer num2 = 100;\n",
- "Integer num3 = new Integer(100);\n",
- "\n",
- "System.out.println(num1.equals(num2)); // true (same value)\n",
- "System.out.println(num1.equals(num3)); // true (same value)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "This compares the values by their objects, not their references. num1.equals(num2) checks if the values are the same between the 2 but since they both have a value of 100 they are equal so it becomes true. This ignores if the objects have the same or different reference point. num1.euals(num3) even though it has a new integer and it's different from num1 they are still the same because they have the same value so it makes it true."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Popcorn hack\n",
- "Would the sharons house and my house be the same?"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "class House {\n",
- " private String color;\n",
- " private int size;\n",
- "\n",
- " public House(String color, int size) {\n",
- " this.color = color;\n",
- " this.size = size;\n",
- " }\n",
- "\n",
- " // Override equals method to compare House objects by content\n",
- " @Override\n",
- " public boolean equals(Object obj) {\n",
- " if (this == obj) return true; // Check if same object reference\n",
- " if (obj == null || getClass() != obj.getClass()) return false; // Check if same class\n",
- " House house = (House) obj;\n",
- " return size == house.size && color.equals(house.color); // Compare attributes\n",
- " }\n",
- "}\n",
- "\n",
- "public class Main {\n",
- " public static void main(String[] args) {\n",
- " House myHouse = new House(\"green\", 150);\n",
- " House anikasHouse = new House(\"green\", 150);\n",
- " House sharonsHouse = new House(\"green\", 150);\n",
- "\n",
- " // Correct comparison using equals()\n",
- " System.out.println(myHouse.equals(sharonsHouse)); // This should return true\n",
- " }\n",
- "}\n"
- ]
- }
- ],
- "metadata": {
- "language_info": {
- "name": "python"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_03/Period1/2024-09-16-unit_teamteach_hw.ipynb b/_notebooks/CSA/units_1_to_10/unit_03/Period1/2024-09-16-unit_teamteach_hw.ipynb
deleted file mode 100644
index 348fd7f3..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_03/Period1/2024-09-16-unit_teamteach_hw.ipynb
+++ /dev/null
@@ -1,136 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "comments: true\n",
- "title: Unit 3 Boolean - Homework\n",
- "description: Unit 3 Team Teach\n",
- "permalink: /csa/unit3-p1/unit3-8hw\n",
- "menu: nav/CSA_Units/csa_unit3_p1.html\n",
- "author: Alisha Hussain, Anika Bhatnagar, Kayden Le, Sharon Kodali\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# Homework: Membership Recommendation System\n",
- "\n",
- "## Problem Overview\n",
- "\n",
- "You are building a membership recommendation system for a fictional company called **\"Prime Club.\"** This system will suggest the most suitable membership tier (or tiers) for a user based on their age, annual income, student status, and employment type. There are 4 types of memberships:\n",
- "\n",
- "### Membership Types\n",
- "\n",
- "1. **Basic Membership:**\n",
- " - **Requirements:**\n",
- " - Age ≥ 18\n",
- " - Annual income ≥ $20,000\n",
- "\n",
- "2. **Premium Membership:**\n",
- " - **Requirements:**\n",
- " - Age ≥ 25\n",
- " - Annual income ≥ $50,000\n",
- "\n",
- "3. **Student Discount:**\n",
- " - **Requirements:**\n",
- " - Must be a student.\n",
- "\n",
- "4. **Senior Discount:**\n",
- " - **Requirements:**\n",
- " - Age ≥ 65\n",
- "\n",
- "## Task Description\n",
- "\n",
- "Using conditional statements, Boolean expressions, and comparison techniques you’ve learned, write a Java program that:\n",
- "\n",
- "1. Prompts the user to input the following:\n",
- " - Age (as an integer)\n",
- " - Annual income (as a double)\n",
- " - Student status (yes or no)\n",
- " - Employment type (full-time, part-time, unemployed)\n",
- "\n",
- "2. Based on these inputs, your program should print out all membership tiers and discounts the user qualifies for. If the user does not qualify for any membership or discount, the program should print: \n",
- " **\"You do not qualify for any memberships or discounts.\"**\n",
- "\n",
- "## Additional Challenge\n",
- "\n",
- "Add a final recommendation where your program prioritizes the **\"best\" membership** for the user if they qualify for multiple memberships (use an `else-if` structure).\n",
- "\n",
- "The best membership should be decided based on the following priorities:\n",
- "1. **Premium Membership** (highest priority)\n",
- "2. **Senior Discount**\n",
- "3. **Student Discount**\n",
- "4. **Basic Membership** (lowest priority)\n",
- "\n",
- "\n",
- "Hints (click to reveal) \n",
- "\n",
- "1. **Input Validation:**\n",
- " - Ensure that age is a positive integer, and annual income is a positive double.\n",
- " - Student status input should be case-insensitive (\"yes\" or \"no\").\n",
- " - Employment type should be one of: \"full-time\", \"part-time\", or \"unemployed.\"\n",
- "\n",
- "2. **Conditions to Consider:**\n",
- " - Use `if-else` statements to check for membership qualifications.\n",
- " - Remember to handle multiple conditions where a user qualifies for more than one membership.\n",
- "\n",
- "3. **Recommendation Logic:**\n",
- " - Use `else-if` statements to prioritize the memberships based on the provided hierarchy.\n",
- "\n",
- " \n",
- "\n",
- "## Constraints\n",
- "\n",
- "- Age must be a positive integer.\n",
- "- Annual income must be a positive double.\n",
- "- Student status should only accept \"yes\" or \"no\" (case-insensitive).\n",
- "- Employment type should be one of: \"full-time\", \"part-time\", or \"unemployed.\"\n",
- "\n",
- "Senior Discount:\n",
- "\n",
- "Requirements:\n",
- "Age ≥ 65\n",
- "Task Description:\n",
- "Using conditional statements, Boolean expressions, and comparison techniques you’ve learned, write a Java program that:\n",
- "\n",
- "Prompts the user to input the following:\n",
- "\n",
- "Age (as an integer)\n",
- "Annual income (as a double)\n",
- "Student status (yes or no)\n",
- "Employment type (full-time, part-time, unemployed)\n",
- "Based on these inputs, your program should print out all membership tiers and discounts the user qualifies for. If the user does not qualify for any membership or discount, the program should print out: \"You do not qualify for any memberships or discounts.\"\n",
- "\n",
- "Additional Challenge: Add a final recommendation where your program prioritizes the \"best\" membership for the user if they qualify for multiple memberships (use an else-if structure).\n",
- "\n",
- "The best membership should be decided based on the following priorities:\n",
- "Premium Membership (highest priority)\n",
- "Senior Discount\n",
- "Student Discount\n",
- "Basic Membership (lowest priority)\n",
- "Constraints:\n",
- "Age must be a positive integer.\n",
- "Annual income must be a positive double.\n",
- "Student status should only accept \"yes\" or \"no\" (case-insensitive).\n",
- "Employment type should be one of: \"full-time\", \"part-time\", or \"unemployed.\""
- ]
- }
- ],
- "metadata": {
- "language_info": {
- "name": "python"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_04/Period1/2024-09-12-U4-Iteration.ipynb b/_notebooks/CSA/units_1_to_10/unit_04/Period1/2024-09-12-U4-Iteration.ipynb
deleted file mode 100644
index c970d373..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_04/Period1/2024-09-12-U4-Iteration.ipynb
+++ /dev/null
@@ -1,167 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "layout: post\n",
- "title: Unit 4 - Iteration P1 \n",
- "toc: True\n",
- "courses: {'csa': {'week': 6}}\n",
- "type: ccc\n",
- "permalink: /csa/unit4-p1/\n",
- "menu: nav/CSA_Units/csa_unit4_p1.html\n",
- "author: hanlun, saaras, arthur, miheer, eshaan, beijan\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Collegeboard Resources for loops/iteration\n",
- " - [AP Classroom](https://apclassroom.collegeboard.org/8/home?unit=4)\n",
- "\n",
- " ## AP Computer Science A - Unit 4 Home Page\n",
- "\n",
- "Welcome to Unit 4! In this unit, we will explore various concepts of **Iteration** in Java, focusing on while, for, for each, do while loops and string manipulation\n",
- "\n",
- "### Learning Goals:\n",
- "- Understand how to declare, initialize, loops\n",
- "- Learn how to iterate through strings\n",
- "- Practice writing algorithms that use iteration\n",
- "\n",
- "### Key Topics:\n",
- "Topic 4.1 - while Loops\n",
- "Topic 4.2 - for Loops\n",
- "Topic 4.3 - Developing Algorithms Using Strings\n",
- "Topic 4.4 - Nested Iteration\n",
- " "
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "\n",
- " \n",
- "
\n",
- "\n",
- "\n",
- "\n",
- "
Adjust Speed: \n",
- "
\n",
- "
2 \n",
- " \n",
- "
Adjust Size: \n",
- "
\n",
- "
15 \n",
- "\n",
- "
Pause \n",
- "
Reset Ball \n",
- " \n",
- "
Iteration: 0
\n",
- "
Current Velocity: 2, 2
\n",
- "
\n",
- "\n",
- "\n"
- ]
- }
- ],
- "metadata": {
- "language_info": {
- "name": "python"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_04/Period1/2024-09-19-unit_4.1.ipynb b/_notebooks/CSA/units_1_to_10/unit_04/Period1/2024-09-19-unit_4.1.ipynb
deleted file mode 100644
index a0e7e228..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_04/Period1/2024-09-19-unit_4.1.ipynb
+++ /dev/null
@@ -1,329 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "layout: post\n",
- "type: collab\n",
- "title: Unit 4.1 - While Loops\n",
- "description: Unit 4 Team Teach\n",
- "comments: true\n",
- "permalink: /csa/unit4-p1/unit4-1\n",
- "menu: nav/CSA_Units/csa_unit4_p1.html\n",
- "author: hanlun, saaras, arthur, miheer, eshaan, beijan\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 4.1 While Loops\n",
- "While loops run until the given condition is false. Format of loop below.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 1,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "0\n",
- "1\n",
- "2\n",
- "3\n",
- "4\n"
- ]
- }
- ],
- "source": [
- "int index = 0; // iterating value\n",
- "while (index < 5) { // condition, if this is false, the loop terminates\n",
- " System.out.println(index); // body code\n",
- " index++; // iterates the iterating value\n",
- "}"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 2,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "0\n",
- "1\n",
- "2\n",
- "3\n",
- "4\n"
- ]
- }
- ],
- "source": [
- "# Python Version\n",
- "i=0\n",
- "while (i<5):\n",
- " print(i)\n",
- " i+=1"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Explanation\n",
- "- in the above while loop: \n",
- " - index is the incrementing variable\n",
- " - index < 5 is the condition (once index < 5 is false, this loop breaks)\n",
- " - System.out.println(i); is the body code that runs every time the loop iterates\n",
- " - index++; is incrementing the incrementing variable"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Do While Loops:\n",
- "- This type of while loop runs the block inside the do{} statement once, then iterates through the loop\n",
- "- this ensures that the code runs at least once\n",
- "\n",
- "### Example of Do While loop below"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 2,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "0\n",
- "1\n",
- "2\n",
- "3\n",
- "4\n"
- ]
- }
- ],
- "source": [
- "int i = 0; // iterating value\n",
- "do { // this makes sure the code runs at least once\n",
- " System.out.println(i); // body code\n",
- " i++; // iterates the iterating value\n",
- "} while (i < 5); // condition, if this is false, loop terminates"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Explanation:\n",
- "- in the above loop:\n",
- " - code inside of the do{} statement runs at least once, then keeps on running as long as the condition, i<5, is true.\n",
- " - similarly to the normal while loop, there is body code, and there is an incrementing variable "
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## IMPORTANT:\n",
- "- While loops to not have to have an incrementing variable, for example, you can have a loop that iterates as long as there are items present in a list"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 1,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "[10, 20, 30, 40] before loop!!\n",
- "Element: 10\n",
- "Element: 20\n",
- "Element: 30\n",
- "Element: 40\n",
- "[] after loop!!\n"
- ]
- }
- ],
- "source": [
- "ArrayList list = new ArrayList<>();\n",
- "list.add(10);\n",
- "list.add(20);\n",
- "list.add(30);\n",
- "list.add(40);\n",
- "\n",
- "System.out.println(list + \" before loop!!\");\n",
- "while (!list.isEmpty()) {\n",
- " System.out.println(\"Element: \" + list.remove(0));\n",
- "}\n",
- "System.out.println(list + \" after loop!!\");"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Fun While Loop Hack:\n",
- "- find and fix the missing increment in the while loop"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "int i = 0;\n",
- "while (i < 5) {\n",
- " System.out.println(i);\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "\n",
- " \n",
- "
\n",
- "\n",
- "\n",
- "\n",
- "
Adjust Speed: \n",
- "
\n",
- "
2 \n",
- " \n",
- "
Adjust Size: \n",
- "
\n",
- "
15 \n",
- "\n",
- "
Pause \n",
- "
Reset Ball \n",
- " \n",
- "
Iteration: 0
\n",
- "
Current Velocity: 2, 2
\n",
- "
\n",
- "\n",
- "\n"
- ]
- }
- ],
- "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": "17.0.12+8-LTS-286"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_04/Period1/2024-09-19-unit_4.2.ipynb b/_notebooks/CSA/units_1_to_10/unit_04/Period1/2024-09-19-unit_4.2.ipynb
deleted file mode 100644
index 402875bf..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_04/Period1/2024-09-19-unit_4.2.ipynb
+++ /dev/null
@@ -1,266 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "layout: post\n",
- "type: collab\n",
- "title: Unit 4.2 - For Loops\n",
- "description: Unit 4 Team Teach\n",
- "comments: true\n",
- "permalink: /csa/unit4-p1/unit4-2\n",
- "menu: nav/CSA_Units/csa_unit4_p1.html\n",
- "author: hanlun, saaras, arthur, miheer, eshaan, beijan\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 4.2 For Loops\n",
- "Similar to while loops, for loops run until a condition is false. Format of for loop below: "
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 9,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "0\n",
- "1\n",
- "2\n",
- "3\n",
- "4\n"
- ]
- }
- ],
- "source": [
- "for (int i = 0; i < 5; i++) {\n",
- " System.out.println(i);\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Explanation\n",
- "- in the above for loop: \n",
- " - int i = 0 defines the iterating variable\n",
- " - i < 5 is the condition (once i < 5 is false, this loop breaks)\n",
- " - i++ is the incrementation of the iterating variable\n",
- " - System.out.println(i); is the body code that runs every time the loop iterates"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## For Each Loops:\n",
- "- Apart from iterating using an incrementing variable, you can also iterate through items in a list.\n",
- "### Example of For Each loop below"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "0\n",
- "1\n",
- "2\n",
- "3\n",
- "4\n"
- ]
- }
- ],
- "source": [
- "int[] list = {1, 2, 3, 4, 5}; // any list\n",
- "for (int item : list) { // for each item in the list, execute the body\n",
- " System.out.println(item); // body code\n",
- "}"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "#python version\n",
- "array=[1, 2, 3, 4, 5]\n",
- "for i in array:\n",
- " print(i)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Explanation:\n",
- "- in the above loop:\n",
- " - int item : list - this line is saying that for each item in the list, execute code below\n",
- " - System.out.println(num); - this line is the body code."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Fun For Loop Hack:\n",
- "Create a program that iterates through a list of numbers (int_list = {0, 4, 51, 83, 92, 10, 123, 145}) using both a for loop and a for each loop, then split the numbers in the list into even/odd lists, and output them.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": []
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "\n",
- " \n",
- "
\n",
- "\n",
- "\n",
- "\n",
- "
Adjust Speed: \n",
- "
\n",
- "
2 \n",
- " \n",
- "
Adjust Size: \n",
- "
\n",
- "
15 \n",
- "\n",
- "
Pause \n",
- "
Reset Ball \n",
- " \n",
- "
Iteration: 0
\n",
- "
Current Velocity: 2, 2
\n",
- "
\n",
- "\n",
- "\n"
- ]
- }
- ],
- "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": "17.0.12+7-Ubuntu-1ubuntu222.04"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_04/Period1/2024-09-19-unit_4.3.ipynb b/_notebooks/CSA/units_1_to_10/unit_04/Period1/2024-09-19-unit_4.3.ipynb
deleted file mode 100644
index d6127367..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_04/Period1/2024-09-19-unit_4.3.ipynb
+++ /dev/null
@@ -1,327 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "layout: post\n",
- "type: collab\n",
- "title: Unit 4.3 - String Iteration\n",
- "description: Unit 4 Team Teach\n",
- "comments: true\n",
- "permalink: /csa/unit4-p1/unit4-3\n",
- "menu: nav/CSA_Units/csa_unit4_p1.html\n",
- "author: hanlun, saaras, arthur, miheer, eshaan, beijan\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 4.3 String Iteration\n",
- "simple for loop to iterate through every character using index with `charAt()`:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "String word = \"hello\";\n",
- "for (int i = 0; i < word.length(); i++) {\n",
- " System.out.println(word.charAt(i));\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "in order to use an enhanced for loop, a character array is needed. \n",
- "`toCharArray()` can help accomplish this. \n",
- "example of iteration with an enhanced for loop:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "String word = \"hello\";\n",
- "for (char c : word.toCharArray()) {\n",
- " System.out.println(c);\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Popcorn Hack:\n",
- "Iterate through the characters a string with a `while` loop"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": []
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### What is a substring?\n",
- "- a substring is a subset of the main string\n",
- "- the substring(a,b) method creates a substring with the characters of the original string with indices of a to b.\n",
- "- string.length() returns the length of the string\n",
- "- string1.equals(string2) determines if the two strings have the same characters"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "String word = \"sunflower\";\n",
- "String sub = \"low\";\n",
- "boolean found = false;\n",
- "for (int i = 0; i < word.length(); i++) {\n",
- " String portion = word.substring(i, i+sub.length());\n",
- " if (portion.equals(sub)){\n",
- " found = true;\n",
- " }\n",
- "}\n",
- "\n",
- "System.out.println(\"is \" + )"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Iterating through words\n",
- "use `split()` to split a string into an array. \n",
- "then we can iterate through the array to access each individual word"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "String phrase = \"this is a string\";\n",
- "String[] words = phrase.split(\" \");\n",
- "for (String word : words) {\n",
- " System.out.println(word);\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Homework Hack!\n",
- "\n",
- "code a caesar cipher that will encrypt any string with any key provided. \n",
- "your code should go into the `encrypt()` method, and should successfully pass the test cases provided \n",
- "as a bonus, try to use StringBuilder"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class CaesarCipher {\n",
- " private int key;\n",
- " private String phrase;\n",
- "\n",
- " public CaesarCipher(int key, String phrase) {\n",
- " this.key = key;\n",
- " this.phrase = phrase;\n",
- " }\n",
- "\n",
- " public String encrypt() {\n",
- " // your code here\n",
- "\n",
- " return null; // return encrypted phrase here\n",
- " }\n",
- "}\n",
- "\n",
- "CaesarCipher test1 = new CaesarCipher(3, \"hello world\");\n",
- "CaesarCipher test2 = new CaesarCipher(10, \"abcdefg\");\n",
- "CaesarCipher test3 = new CaesarCipher(20, \"i love csa\");\n",
- "\n",
- "System.out.println(\"test 1: \" + test1.encrypt());\n",
- "System.out.println(\"test 2: \" + test2.encrypt());\n",
- "System.out.println(\"test 3: \" + test3.encrypt());"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "\n",
- " \n",
- "
\n",
- "\n",
- "\n",
- "\n",
- "
Adjust Speed: \n",
- "
\n",
- "
2 \n",
- " \n",
- "
Adjust Size: \n",
- "
\n",
- "
15 \n",
- "\n",
- "
Pause \n",
- "
Reset Ball \n",
- " \n",
- "
Iteration: 0
\n",
- "
Current Velocity: 2, 2
\n",
- "
\n",
- "\n",
- "\n"
- ]
- }
- ],
- "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": "17.0.12+7-Ubuntu-1ubuntu222.04"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_04/Period1/2024-09-19-unit_4.4.ipynb b/_notebooks/CSA/units_1_to_10/unit_04/Period1/2024-09-19-unit_4.4.ipynb
deleted file mode 100644
index bfb96345..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_04/Period1/2024-09-19-unit_4.4.ipynb
+++ /dev/null
@@ -1,465 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "layout: post\n",
- "type: collab\n",
- "title: Unit 4.4 - Nested Iteration\n",
- "description: Unit 4 Team Teach\n",
- "comments: true\n",
- "permalink: /csa/unit4-p1/unit4-4\n",
- "menu: nav/CSA_Units/csa_unit4_p1.html\n",
- "author: hanlun, saaras, arthur, miheer, eshaan, beijan\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 4.4 Nested Iteration\n",
- "How to iterate through with a time complexity of O(n^2)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 6,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Outer loop iteration: 1\n",
- " Inner loop iteration: 1\n",
- " Inner loop iteration: 2\n",
- " Inner loop iteration: 3\n",
- "Outer loop iteration: 2\n",
- " Inner loop iteration: 1\n",
- " Inner loop iteration: 2\n",
- " Inner loop iteration: 3\n",
- "Outer loop iteration: 3\n",
- " Inner loop iteration: 1\n",
- " Inner loop iteration: 2\n",
- " Inner loop iteration: 3\n"
- ]
- }
- ],
- "source": [
- "for (int i = 1; i <= 3; i++) { // Outer loop\n",
- " System.out.println(\"Outer loop iteration: \" + i);\n",
- " for (int j = 1; j <= 3; j++) { // Inner loop\n",
- " System.out.println(\" Inner loop iteration: \" + j);\n",
- " }\n",
- " }"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## What is wrong with this code cell(Hack)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 5,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Enter the number of rows: "
- ]
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "1 2 3 4 5 \n",
- "1 2 3 4 \n",
- "1 2 3 \n",
- "1 2 \n",
- "1 \n"
- ]
- }
- ],
- "source": [
- "//Hint: Check the Syntax and look at the equals to signs on the example above\n",
- "\n",
- "import java.util.Scanner;\n",
- "Scanner scanner = new Scanner(System.in);\n",
- "System.out.print(\"Enter the number of rows: \");\n",
- "int rows = scanner.nextInt();\n",
- "for (int i = rows; i>1; i-) {\n",
- " for (int j = 1; j <= i; j++) {\n",
- " System.out.print(j + \" \");\n",
- " }\n",
- " System.out.println();\n",
- " }\n",
- " \n",
- "scanner.close();\n",
- " \n",
- "\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Sample input:\n",
- "5\n",
- "\n",
- "Sample Output\n",
- "1 2 3 4 5\n",
- "1 2 3 4\n",
- "1 2 3\n",
- "1 2\n",
- "1\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- " \n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Answer here + One sentence Explanation\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- " \n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Answer here + One sentence Explanation"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "[Video To watch later if you need more help](https://www.youtube.com/watch?v=DgLptGRzFl4)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Cool Usecase of nested loops"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 9,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Diamond Pattern:\n",
- " *\n",
- " ***\n",
- " *****\n",
- " *******\n",
- "*********\n",
- " *******\n",
- " *****\n",
- " ***\n",
- " *\n",
- "\n",
- "Magic Square (Latin Square):\n",
- "9\t15\t1\t7\t\n",
- "14\t4\t6\t12\t\n",
- "3\t5\t11\t13\t\n",
- "8\t10\t16\t2\t\n",
- "\n",
- "Prime Number Spiral:\n",
- "0\t2\t3\t0\t5\t\n",
- "0\t17\t0\t19\t0\t\n",
- "0\t0\t0\t0\t7\t\n",
- "0\t23\t0\t0\t0\t\n",
- "13\t0\t11\t0\t0\t\n"
- ]
- }
- ],
- "source": [
- "\n",
- " // Define the dimensions\n",
- " int rows = 5;\n",
- "\n",
- " // First loop to generate a diamond pattern\n",
- " System.out.println(\"Diamond Pattern:\");\n",
- " for (int i = 1; i <= rows; i++) {\n",
- " // Print spaces for left alignment\n",
- " for (int j = i; j < rows; j++) {\n",
- " System.out.print(\" \");\n",
- " }\n",
- " // Print asterisks for the upper part of the diamond\n",
- " for (int k = 1; k <= (2 * i - 1); k++) {\n",
- " System.out.print(\"*\");\n",
- " }\n",
- " System.out.println();\n",
- " }\n",
- " for (int i = rows - 1; i >= 1; i--) {\n",
- " // Print spaces for right alignment\n",
- " for (int j = rows; j > i; j--) {\n",
- " System.out.print(\" \");\n",
- " }\n",
- " // Print asterisks for the lower part of the diamond\n",
- " for (int k = 1; k <= (2 * i - 1); k++) {\n",
- " System.out.print(\"*\");\n",
- " }\n",
- " System.out.println();\n",
- " }\n",
- "\n",
- " // Second loop: Magic Square (Latin Square)\n",
- " System.out.println(\"\\nMagic Square (Latin Square):\");\n",
- " int size = 4;\n",
- " int[][] magicSquare = new int[size][size];\n",
- " int num = 1, row = 0, col = size / 2;\n",
- "\n",
- " while (num <= size * size) {\n",
- " magicSquare[row][col] = num;\n",
- " num++;\n",
- " int newRow = (row - 1 + size) % size;\n",
- " int newCol = (col + 1) % size;\n",
- "\n",
- " if (magicSquare[newRow][newCol] != 0) {\n",
- " row = (row + 1) % size;\n",
- " } else {\n",
- " row = newRow;\n",
- " col = newCol;\n",
- " }\n",
- " }\n",
- "\n",
- " // Print the magic square\n",
- " for (int[] r : magicSquare) {\n",
- " for (int c : r) {\n",
- " System.out.print(c + \"\\t\");\n",
- " }\n",
- " System.out.println();\n",
- " }\n",
- " \n",
- " // Third loop: Prime Number Spiral\n",
- " System.out.println(\"\\nPrime Number Spiral:\");\n",
- " int spiralSize = 5;\n",
- " int[][] spiral = new int[spiralSize][spiralSize];\n",
- " int val = 1, startRow = 0, endRow = spiralSize - 1, startCol = 0, endCol = spiralSize - 1;\n",
- "\n",
- " while (startRow <= endRow && startCol <= endCol) {\n",
- " // Fill top row\n",
- " for (int i = startCol; i <= endCol; i++) {\n",
- " spiral[startRow][i] = isPrime(val) ? val : 0;\n",
- " val++;\n",
- " }\n",
- " startRow++;\n",
- "\n",
- " // Fill right column\n",
- " for (int i = startRow; i <= endRow; i++) {\n",
- " spiral[i][endCol] = isPrime(val) ? val : 0;\n",
- " val++;\n",
- " }\n",
- " endCol--;\n",
- "\n",
- " // Fill bottom row\n",
- " if (startRow <= endRow) {\n",
- " for (int i = endCol; i >= startCol; i--) {\n",
- " spiral[endRow][i] = isPrime(val) ? val : 0;\n",
- " val++;\n",
- " }\n",
- " endRow--;\n",
- " }\n",
- "\n",
- " // Fill left column\n",
- " if (startCol <= endCol) {\n",
- " for (int i = endRow; i >= startRow; i--) {\n",
- " spiral[i][startCol] = isPrime(val) ? val : 0;\n",
- " val++;\n",
- " }\n",
- " startCol++;\n",
- " }\n",
- " }\n",
- "\n",
- " // Print the spiral\n",
- " for (int[] r : spiral) {\n",
- " for (int c : r) {\n",
- " System.out.print(c + \"\\t\");\n",
- " }\n",
- " System.out.println();\n",
- " }\n",
- "\n",
- "\n",
- "// Method to check if a number is prime\n",
- "static boolean isPrime(int num) {\n",
- " if (num <= 1) return false;\n",
- " for (int i = 2; i <= Math.sqrt(num); i++) {\n",
- " if (num % i == 0) return false;\n",
- " }\n",
- " return true;\n",
- "}\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "\n",
- " \n",
- "
\n",
- "\n",
- "\n",
- "\n",
- "
Adjust Speed: \n",
- "
\n",
- "
2 \n",
- " \n",
- "
Adjust Size: \n",
- "
\n",
- "
15 \n",
- "\n",
- "
Pause \n",
- "
Reset Ball \n",
- " \n",
- "
Iteration: 0
\n",
- "
Current Velocity: 2, 2
\n",
- "
\n",
- "\n",
- "\n"
- ]
- }
- ],
- "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": "17.0.12+8-LTS-286"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_04/Period1/2024-09-19-unit_4_hwquiz.ipynb b/_notebooks/CSA/units_1_to_10/unit_04/Period1/2024-09-19-unit_4_hwquiz.ipynb
deleted file mode 100644
index a29b2dc3..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_04/Period1/2024-09-19-unit_4_hwquiz.ipynb
+++ /dev/null
@@ -1,293 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "layout: post\n",
- "type: collab\n",
- "title: Unit 4 - HW Quiz\n",
- "description: Unit 4 Team Teach HW QUIZ\n",
- "comments: true\n",
- "permalink: /csa/unit4-p1/unit4-hwquiz\n",
- "menu: nav/CSA_Units/csa_unit4_p1.html\n",
- "author: hanlun, saaras, arthur, miheer, eshaan, beijan\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Unit 4 - Iteration:\n",
- "- This is the homework quiz for unit 4, iterations\n",
- "- 4 multiple choice questions\n",
- "- 2 programming hacks\n",
- "- 1 bonus programming hack (required to get above 0.9)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Question 1:\n",
- "What does the following code print? \n",
- "\n",
- "A. 5 6 7 8 9 \n",
- "\n",
- "B. 4 5 6 7 8 9 10 11 12 \n",
- "\n",
- "C. 3 5 7 9 11 \n",
- "\n",
- "D. 3 4 5 6 7 8 9 10 11 12 \n",
- "\n",
- "\n",
- "Click to reveal answer: \n",
- " D\n",
- " \n",
- "\n",
- "Explain your answer. (explanation is graded not answer)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "for (int i = 3; i <= 12; i++) {\n",
- " System.out.print(i + \" \");\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Bonus:\n",
- "- Explain the difference between using a variable like i inside a for loop, vs. using a variable that exists in the code itself for a while loop"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Question 2:\n",
- "How many times does the following method print a \"*\" ?\n",
- "\n",
- "A. 9\n",
- "\n",
- "B. 7\n",
- "\n",
- "C. 8\n",
- "\n",
- "D. 6\n",
- "\n",
- "\n",
- "Click to reveal answer: \n",
- " C\n",
- " \n",
- "\n",
- "Explain your answer. (explanation is graded not answer)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "for (int i = 3; i < 11; i++) {\n",
- " System.out.print(\"*\");\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Question 3:\n",
- "What does the following code print?\n",
- "\n",
- "A. -4 -3 -2 -1 0\n",
- "\n",
- "B. -5 -4 -3 -2 -1\n",
- "\n",
- "C. 5 4 3 2 1\n",
- "\n",
- "\n",
- "Click to reveal answer: \n",
- " A\n",
- " \n",
- "\n",
- "Explain your answer. (explanation is graded not answer)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "int x = -5;\n",
- "while (x < 0)\n",
- "{\n",
- " x++;\n",
- " System.out.print(x + \" \");\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Question 4:\n",
- "What does the following code print?\n",
- "\n",
- "A. 20\n",
- "\n",
- "B. 21\n",
- "\n",
- "C. 25\n",
- "\n",
- "D. 30\n",
- "\n",
- "\n",
- "Click to reveal answer: \n",
- " B\n",
- " \n",
- "\n",
- "Explain your answer. (explanation is graded not answer)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "int sum = 0;\n",
- "\n",
- "for (int i = 1; i <= 5; i++) {\n",
- " if (i % 2 == 0) {\n",
- " sum += i * 2;\n",
- " } else {\n",
- " sum += i;\n",
- " }\n",
- "}\n",
- "\n",
- "System.out.println(sum);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Loops HW Hack"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Easy Hack\n",
- "- Use a while loop to find the numbers from 1-50 that are divisible by 3 or 5, then store them into a list (make sure to print it out at the end)\n",
- "- Use a for loop to do the same thing detailed above"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": []
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Harder Hack\n",
- "#### Palindromes are numbers that have the same value when reversed (ex: “123321” or “323”). Create a program that uses a while loop that outputs all palindromes in any given list. \n",
- "\n",
- "Sample Input: \n",
- "test_list = [5672, 235, 5537, 6032, 317, 8460, 1672, 8104, 7770, 4442, 913, 2508, 1116, 9969, 9091, 522, 8756, 9527, 7968, 1520, 4444, 515, 2882, 6556, 595]\n",
- "\n",
- "Sample Output:\n",
- "4444, 515, 2882, 6556, 595"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": []
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Bonus Hack (for above 0.9)\n",
- "### Use a for loop to output a spiral matrix with size n\n",
- "Example:\n",
- "\n",
- "Sample Input: n = 3\n",
- "\n",
- "Output: [[1, 2, 3], [8, 9, 4], [7, 6, 5]]"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": []
- }
- ],
- "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": "17.0.12+7-Ubuntu-1ubuntu222.04"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_05/Period1/2024-09-12-U5-Writing_Classes_Intro.ipynb b/_notebooks/CSA/units_1_to_10/unit_05/Period1/2024-09-12-U5-Writing_Classes_Intro.ipynb
deleted file mode 100644
index 5d893c0b..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_05/Period1/2024-09-12-U5-Writing_Classes_Intro.ipynb
+++ /dev/null
@@ -1,102 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "comments: true\n",
- "title: Unit 5 - Writing Classes P1 \n",
- "courses: {'csa': {'week': 6}}\n",
- "type: ccc\n",
- "permalink: csa/period1/unit5/intro\n",
- "menu: nav/CSA_Units/csa_unit5_p1.html\n",
- "author: Nisarg, Imaad, Tanay, Dinesh\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# What will we be teaching?\n",
- "We will be teaching Unit 5, Writing Classes. We will explore the anatomy of a class, fields, methods, and constructors. We will learn how constructors initialize objects and the different types, how mutators (setters) modify object properties, and how static variables belong to the class rather than any instance. By the end, there will be a solid understanding of how to create and manage objects efficiently in Java\n",
- "\n",
- "# Unit 5 Topics For Learning:\n",
- "- 5.1 Anatomy of a Class\n",
- "- 5.2 Constructors \n",
- "- 5.4 Accessor Methods\n",
- "- 5.5 Mutator \n",
- "- 5.7 Static Variables and Methods \n",
- "\n",
- "# Why do we need to write classes?\n",
- "Writing classes in Java is essential because it allows you to organize your code into reusable, modular components. Think of a class as a blueprint for creating objects. Without classes, your code would be cluttered and difficult to manage, especially as projects grow larger. Why not just write all your code in one place? Well, that would make it hard to maintain and update, leading to errors and inefficiency. Classes enable you to encapsulate data and behavior, making your code more flexible, scalable, and easier to troubleshoot. This structured approach is key for building complex, real-world applications.\n",
- "\n",
- "# Homework Assignment: Constructors, Mutators, Accessors, and Static Variables in Java\n",
- "\n",
- "## Objective:\n",
- "Create a `BankAccount` class to practice working with constructors, mutators (setters), accessors (getters), and static variables in Java.\n",
- "\n",
- "## Instructions:\n",
- "\n",
- "### Class: `BankAccount`\n",
- "- **Instance Variables:**\n",
- " - `String accountHolderName`\n",
- " - `double balance`\n",
- "- **Static Variable:**\n",
- " - `static int totalAccounts` (tracks the number of accounts created)\n",
- "\n",
- "### Constructors:\n",
- "- **Default constructor:** Sets `accountHolderName` to `\"Unknown\"` and `balance` to `0.0`.\n",
- "- **Parameterized constructor:** Accepts `accountHolderName` and `balance` as parameters.\n",
- "- Both constructors should increment `totalAccounts`.\n",
- "\n",
- "### Mutator Methods:\n",
- "- `void setAccountHolderName(String name)`: Updates the account holder's name.\n",
- "- `void deposit(double amount)`: Adds money to the balance.\n",
- "- `void withdraw(double amount)`: Subtracts money from the balance (if funds are available).\n",
- "\n",
- "### Accessor Methods:\n",
- "- `String getAccountHolderName()`: Returns the account holder's name.\n",
- "- `double getBalance()`: Returns the account balance.\n",
- "- `static int getTotalAccounts()`: Returns the total number of accounts created.\n",
- "\n",
- "### Main Program (`BankApp`):\n",
- "- Create three `BankAccount` objects.\n",
- "- Modify account holder names and balances using setters.\n",
- "- Print account details using getters.\n",
- "- Display the total number of accounts created.\n",
- "\n",
- "### Example Output:\n",
- "\n",
- "```\n",
- "Account Holder: Alice \n",
- "Balance: 500.0\n",
- "\n",
- "Account Holder: Bob \n",
- "Balance: 1000.0\n",
- "\n",
- "Account Holder: Charlie \n",
- "Balance: 750.0\n",
- "\n",
- "Total number of accounts created: 3\n",
- "```\n",
- "\n",
- "### Submission:\n",
- "Submit a Jupyter Notebook file containing your final code."
- ]
- }
- ],
- "metadata": {
- "language_info": {
- "name": "python"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_05/Period1/2024-09-12-U5-game.ipynb b/_notebooks/CSA/units_1_to_10/unit_05/Period1/2024-09-12-U5-game.ipynb
deleted file mode 100644
index c9428182..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_05/Period1/2024-09-12-U5-game.ipynb
+++ /dev/null
@@ -1,143 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "layout: post\n",
- "title: Unit 5 Classes - Game\n",
- "type: issues \n",
- "\n",
- "hide: true\n",
- "permalink: /csa/period1/unit5/game\n",
- "menu: nav/CSA_Units/csa_unit5_p1.html\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "vscode": {
- "languageId": "html"
- }
- },
- "source": [
- "### Please Only Submit on localhost or [this link](https://imaad08.github.io/NITD_frontend/csa/period1/unit5/game)\n",
- "- To avoid CORS errors :(\n",
- "\n",
- " \n",
- "\n",
- "\n",
- "
\n",
- "\n",
- "\n",
- " \n",
- "\n",
- "\n",
- "\n",
- "\n",
- "
\n",
- "
\n",
- "\n",
- ""
- ]
- }
- ],
- "metadata": {
- "language_info": {
- "name": "python"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_05/Period1/2024-09-16-p1_unit5_Anatomy.ipynb b/_notebooks/CSA/units_1_to_10/unit_05/Period1/2024-09-16-p1_unit5_Anatomy.ipynb
deleted file mode 100644
index 2bce55d2..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_05/Period1/2024-09-16-p1_unit5_Anatomy.ipynb
+++ /dev/null
@@ -1,262 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "layout: post\n",
- "title: Unit 5 Anatomy of a Class(Period 1)\n",
- "comments: true\n",
- "hide: true\n",
- "permalink: /csa/period1/unit5/anatomy\n",
- "menu: nav/CSA_Units/csa_unit5_p1.html\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# Anatomy of a Class\n",
- "This notebook will explain the structure of a class in Java, including attributes, methods, and instantiation. It will also include examples and a mini-project that requires fixing broken code."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "![Class Anatomy Diagram](https://jordanblakey.github.io/all_development_notes_2015-2017/Learning%20Java_files/Image.png)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 1. Introduction to Classes\n",
- "- A class in Java is a blueprint for creating objects. It defines a data structure that includes methods and attributes.\n",
- "- Example:\n",
- "\n",
- "\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class Car {\n",
- " // Attributes\n",
- " String model;\n",
- " int year;\n",
- "\n",
- " // Method\n",
- " void drive() {\n",
- " System.out.println(\"Driving the car.\");\n",
- " }\n",
- "}\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "This `Car` class has attributes `model` and `year`, and a method `drive()` that prints a message."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 2. Attributes and Methods\n",
- "- Attributes (or fields) are variables that belong to an object.\n",
- "- Methods are functions that belong to a class.\n",
- "- Example:\n",
- "\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "\n",
- "public class Person {\n",
- " // Attributes\n",
- " String name;\n",
- " int age;\n",
- "\n",
- " // Method\n",
- " void greet() {\n",
- " System.out.println(\"Hello, my name is \" + name);\n",
- " }\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "In this `Person` class, `name` and `age` are attributes, and `greet()` is a method."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 3. Constructor\n",
- "- Constructors are special methods used to initialize objects.\n",
- "- They have the same name as the class and do not have a return type.\n",
- "- Example:\n",
- "\n",
- "\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 1,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class Person {\n",
- " String name;\n",
- " int age;\n",
- "\n",
- " // Constructor\n",
- " public Person(String name, int age) {\n",
- " this.name = name;\n",
- " this.age = age;\n",
- " }\n",
- "\n",
- " void greet() {\n",
- " System.out.println(\"Hello, my name is \" + name);\n",
- " }\n",
- "}\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "This `Person` class includes a constructor to initialize `name` and `age`."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 4. Class vs. Instance Variables\n",
- "- **Instance variables** are attributes specific to each object.\n",
- "- **Class variables** (static variables) are shared among all instances of the class.\n",
- "- Example:\n",
- "\n",
- "\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class Car {\n",
- " // Class variable\n",
- " static int numberOfCars = 0;\n",
- "\n",
- " // Instance variables\n",
- " String model;\n",
- " int year;\n",
- "\n",
- " // Constructor\n",
- " public Car(String model, int year) {\n",
- " this.model = model;\n",
- " this.year = year;\n",
- " numberOfCars++;\n",
- " }\n",
- "}\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Here, `numberOfCars` is a class variable that keeps track of how many `Car` objects have been created."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 5. Mini Project: Fix the Code\n",
- "- Below is a class with broken code. The goal is to fix the class so it properly initializes and uses instance variables.\n",
- "- Broken code:\n",
- "\n",
- "\n",
- "- **Task**: Debug the `Book` class so it correctly initializes `title` and `author`. Consider how the constructor should be modified."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class Book {\n",
- " String title;\n",
- " String author;\n",
- "\n",
- " // Broken constructor\n",
- " public Book(String title) {\n",
- " title = title;\n",
- " }\n",
- "}\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "- **Task**: Debug the `Book` class so it correctly initializes `title` and `author`. Consider how the constructor should be modified."
- ]
- }
- ],
- "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": "19.0.1+10-21"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_05/Period1/2024-09-16-p1_unit5_Mutators.ipynb b/_notebooks/CSA/units_1_to_10/unit_05/Period1/2024-09-16-p1_unit5_Mutators.ipynb
deleted file mode 100644
index ad1f36cc..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_05/Period1/2024-09-16-p1_unit5_Mutators.ipynb
+++ /dev/null
@@ -1,176 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "layout: post\n",
- "title: Unit 5 Classes - Mutator Methods \n",
- "type: issues \n",
- "comments: true\n",
- "hide: true\n",
- "permalink: /csa/period1/unit5/mutators\n",
- "menu: nav/CSA_Units/csa_unit5_p1.html\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# Mutators/Setters\n",
- "Mutators are used to modify the attribute of an object. They are typically public methods to allow external code to modify the object state.\n",
- "### Naming & Parameters\n",
- "Mutators are named in the setBlank syntax where \"Blank\" is the name of the field you want to modify. Mutators, like other methods in Java, take one or more parameters. \n",
- "\n",
- "### Return Type\n",
- "Since mutators are type void as they do not return a value but rather they modify the object's state.\n",
- "\n",
- "### Validation\n",
- "Mutators often include validation logic to ensure that the new values are being set within acceptable bounds. An example of validation being used with mutators can be seen with the setSpeed mutator that doesn't allow negative values. "
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "![Mutators Diagram]( https://www.cs.emory.edu/~cheung/Courses/171/Syllabus/03-classes/FIGS/immutable01d.png)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Lets take a look at an example!\n",
- "This example discusses showcases some of the most vital use cases for mutators"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 13,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Brand: Honda\n",
- "Model: Civic\n",
- "Speed: 100 mph\n",
- "Brand: Rolls Royce\n",
- "Model: Phantom\n",
- "Speed: 150 mph\n",
- "Speed cannot be negative.\n"
- ]
- }
- ],
- "source": [
- "// A class representing a Car with attributes like make, model, and speed.\n",
- "public class Car {\n",
- " private String brand;\n",
- " private String model;\n",
- " private int speed;\n",
- "\n",
- " // Constructor to initialize attributes\n",
- " public Car(String brand, String model, int speed) {\n",
- " this.brand = brand;\n",
- " this.model = model;\n",
- " if (speed >= 0) { \n",
- " this.speed = speed;\n",
- " } else {\n",
- " System.out.println(\"Speed cannot be negative, setting speed to 0.\");\n",
- " this.speed = 0;\n",
- " }\n",
- " }\n",
- " //Mutators \n",
- " public void setBrand(String brand) {\n",
- " this.brand = brand;\n",
- " }\n",
- " public void setModel(String model) {\n",
- " this.model = model;\n",
- " }\n",
- " public void setSpeed(int speed) {\n",
- " if (speed >= 0) { //Validation so speed is not negative\n",
- " this.speed = speed;\n",
- " } else {\n",
- " System.out.println(\"Speed cannot be negative.\");\n",
- " }\n",
- " }\n",
- " // Display car details\n",
- " public void displayCarInfo() {\n",
- " System.out.println(\"Brand: \" + brand);\n",
- " System.out.println(\"Model: \" + model);\n",
- " System.out.println(\"Speed: \" + speed + \" mph\");\n",
- " }\n",
- "}\n",
- "Car myCar = new Car(\"Honda\", \"Civic\", 100);\n",
- "myCar.displayCarInfo();\n",
- "\n",
- "// Modifying attributes mutators\n",
- "myCar.setSpeed(150);\n",
- "myCar.setBrand(\"Rolls Royce\");\n",
- "myCar.setModel(\"Phantom\");\n",
- "myCar.displayCarInfo();\n",
- "\n",
- "//Testing Validation with invalid value (Should trigger warning)\n",
- "myCar.setSpeed(-50); "
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Popcorn Hack\n",
- "\n",
- "### 1. Create a Class\n",
- "Define a class Person with private fields: String name, int age, and double height. This is done for you.\n",
- "### 2. Create Mutators\n",
- "Write mutator methods setName(String name), setAge(int age) (with validation for non-negative age), and setHeight(double height) (with validation for non-negative height).\n",
- "### 3. Write a Constructor\n",
- "Create a constructor that initializes name, age, and height with provided values.\n",
- "### 4. Test the Mutators\n",
- "In the main method, create a Person object, modify its fields using the mutators, and print the details after each modification."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class Person {\n",
- " // Private fields\n",
- " private String name;\n",
- " private int age;\n",
- " private double height;\n",
- "}"
- ]
- }
- ],
- "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": "17.0.12+7-Ubuntu-1ubuntu224.04"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_05/Period1/2024-09-16-p1_unit5_StaticVariables.ipynb b/_notebooks/CSA/units_1_to_10/unit_05/Period1/2024-09-16-p1_unit5_StaticVariables.ipynb
deleted file mode 100644
index 59386a9f..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_05/Period1/2024-09-16-p1_unit5_StaticVariables.ipynb
+++ /dev/null
@@ -1,210 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "layout: post\n",
- "title: Unit 5 Classes - Static Variables\n",
- "type: issues \n",
- "comments: true\n",
- "hide: true\n",
- "permalink: csa/period1/unit5/staticvariables\n",
- "menu: nav/CSA_Units/csa_unit5_p1.html\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# Static Variables\n",
- "This notebook will explain what static variables are, how they differ from instance variables, and provide examples, including a mini-project with broken code to fix."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 1. Introduction to Static Variables\n",
- "- Static variables belong to the class rather than any particular instance. They are shared across all instances of the class.\n",
- "- Example:\n",
- "\n",
- "\n",
- "\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "public class BankAccount {\n",
- " // Static variable\n",
- " static double interestRate = 0.03;\n",
- "\n",
- " // Instance variable\n",
- " double balance;\n",
- "\n",
- " // Constructor\n",
- " public BankAccount(double balance) {\n",
- " this.balance = balance;\n",
- " }\n",
- "\n",
- " // Static method\n",
- " static void setInterestRate(double newRate) {\n",
- " interestRate = newRate;\n",
- " }\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "In this `BankAccount` class, `interestRate` is a static variable shared by all instances, and `setInterestRate()` is a static method that updates this variable."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 2. Defining Static Variables\n",
- "- Static variables are defined using the `static` keyword and accessed using the class name.\n",
- "- Example:\n",
- "\n",
- "\n",
- "\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "public class Student {\n",
- " // Static variable\n",
- " static String schoolName = \"XYZ School\";\n",
- "\n",
- " // Instance variable\n",
- " String name;\n",
- "\n",
- " // Constructor\n",
- " public Student(String name) {\n",
- " this.name = name;\n",
- " }\n",
- "}\n",
- "\n",
- "// Accessing static variable\n",
- "System.out.println(Student.schoolName);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Here, `schoolName` is a static variable shared by all `Student` instances."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 3. Static Methods\n",
- "- Static methods can access static variables but cannot access instance variables directly.\n",
- "- Example:\n",
- "\n",
- "\n",
- "\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "public class BankAccount {\n",
- " static double interestRate = 0.03;\n",
- "\n",
- " static void updateInterestRate(double newRate) {\n",
- " interestRate = newRate;\n",
- " }\n",
- "}\n",
- "\n",
- "// Using static method\n",
- "BankAccount.updateInterestRate(0.04);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "The `updateInterestRate` method updates the static variable `interestRate`."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 4. Mini Project: Fix the Code\n",
- "- Below is a class with broken code. The goal is to fix the class so it correctly implements and accesses static variables and methods.\n",
- "- Broken code:\n",
- "\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "\n",
- "public class Vehicle {\n",
- " static int count = 0;\n",
- "\n",
- " // Constructor\n",
- " public Vehicle() {\n",
- " count = count + 1;\n",
- " }\n",
- "\n",
- " // Method\n",
- " public void displayCount() {\n",
- " System.out.println(count);\n",
- " }\n",
- "}\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "- **Task**: Debug the `Vehicle` class to ensure `count` is properly incremented and displayed. Consider how `displayCount()` should be modified if `count` is a static variable."
- ]
- }
- ],
- "metadata": {
- "kernelspec": {
- "display_name": "Java",
- "language": "java",
- "name": "java"
- },
- "language_info": {
- "codemirror_mode": {
- "name": "java",
- "version": 2
- },
- "file_extension": ".java",
- "mimetype": "text/x-java-source",
- "name": "java",
- "nbconvert_exporter": "java",
- "pygments_lexer": "java",
- "version": "15.0.1"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_05/Period1/2024-09-16-p1_unit5_accessorMethods.ipynb b/_notebooks/CSA/units_1_to_10/unit_05/Period1/2024-09-16-p1_unit5_accessorMethods.ipynb
deleted file mode 100644
index 86c35540..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_05/Period1/2024-09-16-p1_unit5_accessorMethods.ipynb
+++ /dev/null
@@ -1,205 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "layout: post\n",
- "title: Unit 5 Classes - Accessor Methods \n",
- "type: issues \n",
- "comments: true\n",
- "hide: true\n",
- "permalink: /csa/period1/unit5/accessor\n",
- "menu: nav/CSA_Units/csa_unit5_p1.html\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# What is an accessor method? \n",
- "\n",
- "- Allow safe access to instance variables \n",
- " - Prevents access to variables from outside \n",
- "- AKA \"get methods\" or \"getters\" \n",
- "- If another class or a function needs access to the variable, you use an accessor method \n",
- "\n",
- "## Example: "
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class snack { \n",
- " private String name; \n",
- " private int calories; \n",
- "\n",
- " public Snack() { \n",
- " name \"\"; \n",
- " calories = 0; \n",
- " }\n",
- "\n",
- " public Snack (string n, int c) { \n",
- " name = n; \n",
- " calories = c; \n",
- " }\n",
- "\n",
- " public String getName(){\n",
- " return Name; \n",
- " }\n",
- "\n",
- " public int getCalories() { \n",
- " return calories; \n",
- " }\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Private Instance Variables: \n",
- "\n",
- "`private String name; \n",
- "private int calories;`\n",
- "\n",
- "### Default Constructors \n",
- "`public Snack() { \n",
- " name \"\"; \n",
- " calories = 0; \n",
- " }`\n",
- "\n",
- "### Overload Constructor\n",
- "`public Snack (string n, int c) { \n",
- " name = n; \n",
- " calories = c; \n",
- " }`\n",
- "\n",
- "### Accessor Methods \n",
- "` public String getName(){\n",
- " return Name; \n",
- " }`\n",
- "\n",
- "`public int getCalories() { \n",
- " return calories; \n",
- " }`\n",
- "- Return command reciprocate a copy of the instance variable \n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Requirements\n",
- "\n",
- "- Accessor Methods must be public \n",
- "- Return type must match the variable type \n",
- " - int = int \n",
- " - string = string \n",
- " - etc \n",
- "- REMEMBER PRINTING A VALUE IS NOT THE SAME AS RETURNING \n",
- "- Name appropriately\n",
- " - Often is `getNameOfVariable` \n",
- "- No parameters \n",
- "\n",
- "#### Notice how the methods from the example match: `public String getName(){` and `public int getCalories()` "
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "![Accessors Diagram](https://www.cs.emory.edu/~cheung/Courses/171/Syllabus/03-classes/FIGS/immutable01d.png)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Popcorn Hack #1: \n",
- "\n",
- "Below is a constructor of a class, write the acccessor methods for all instance variables. "
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class Pet { \n",
- "\n",
- " private String Name; \n",
- " private String typeOfPet; \n",
- " private int age;\n",
- "\n",
- " /* Type Constructors Here */\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### How can we print out all the information about an instance of an object?"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class SportTester {\n",
- " public static void main (string[] args) {\n",
- " sport volley = new Sport(\"volleyball\", 12); \n",
- " system.out.println(volley);\n",
- " }\n",
- "\n",
- " public String toString(String sportName, int numPlayers) {\n",
- " return \"Sport: \" + sportName + \", Players: \" + numPlayers;\n",
- " }\n",
- "}\n",
- "\n",
- "\n",
- "/* see what it prints out \n",
- " This is called hash code in hexadecimal form*/\n",
- "\n"
- ]
- }
- ],
- "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": "17.0.12+8-LTS-286"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_05/Period1/2024-09-16-p1_unit5_constructors.ipynb b/_notebooks/CSA/units_1_to_10/unit_05/Period1/2024-09-16-p1_unit5_constructors.ipynb
deleted file mode 100644
index 23758402..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_05/Period1/2024-09-16-p1_unit5_constructors.ipynb
+++ /dev/null
@@ -1,467 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "layout: post\n",
- "title: Unit 5 Classes - Constructors\n",
- "type: issues \n",
- "comments: true\n",
- "hide: true\n",
- "permalink: /csa/period1/unit5/constructors\n",
- "menu: nav/CSA_Units/csa_unit5_p1.html\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# Introduction to Constructors in Java\n",
- "\n",
- "## What are Constructors?\n",
- "\n",
- "In Java, a constructor is a special method used to initialize objects. The constructor is called when an object of a class is created. It has the same name as the class and does not return any value, not even `void`.\n",
- "\n",
- "### Key Points:\n",
- "- **Same name as class**: The constructor must have the same name as the class.\n",
- "- **No return type**: Constructors do not return any value.\n",
- "- **Used to initialize objects**: They set initial values for object attributes."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Types of Constructors\n",
- "\n",
- "![TypesofConstructors](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh97RjJAncaxhFZGTwEv6054QSXp4LoRPF8BptqAGfuAy-ZmZZ0M5xtVQoqfqv5K9x_999u74zBDkxWzEHBAONyfPPOlFKD8cViqWU2okToQXExlqEK3tH5MnI2VnvlV3rNKjV7nQbsj6E/s1600/constructor+in+java.png)\n",
- "\n",
- "### 1. Default Constructor:\n",
- "A constructor that does not accept any parameters. Java provides a default constructor if you don't define any.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 14,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Unknown\n"
- ]
- }
- ],
- "source": [
- "class Car {\n",
- " String brand;\n",
- " \n",
- " // Default constructor\n",
- " Car() {\n",
- " brand = \"Unknown\";\n",
- " }\n",
- "}\n",
- "\n",
- "Car myCar = new Car();\n",
- "System.out.println(myCar.brand); // Outputs: Unknown"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### 2. Parameterized Constructor:\n",
- "A constructor that takes parameters to initialize object attributes with custom values."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 13,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Toyota\n"
- ]
- }
- ],
- "source": [
- "class Car {\n",
- " String brand;\n",
- "\n",
- " // Parameterized constructor\n",
- " Car(String b) {\n",
- " brand = b;\n",
- " }\n",
- "}\n",
- "\n",
- "Car myCar = new Car(\"Toyota\");\n",
- "System.out.println(myCar.brand); // Outputs: Toyota"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### 3. **Constructor Overloading**\n",
- "\n",
- "\n",
- "## Constructor Overloading\n",
- "\n",
- "In Java, you can have more than one constructor in a class. This is known as constructor overloading. Each constructor must have a different parameter list.\n",
- "\n",
- "\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 15,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Unknown 0\n",
- "Ford 2020\n"
- ]
- }
- ],
- "source": [
- "class Car {\n",
- " String brand;\n",
- " int year;\n",
- "\n",
- " // Default constructor\n",
- " Car() {\n",
- " brand = \"Unknown\";\n",
- " year = 0;\n",
- " }\n",
- "\n",
- " // Parameterized constructor\n",
- " Car(String b, int y) {\n",
- " brand = b;\n",
- " year = y;\n",
- " }\n",
- "}\n",
- "Car car1 = new Car();\n",
- "Car car2 = new Car(\"Ford\", 2020);\n",
- "System.out.println(car1.brand + \" \" + car1.year); // Outputs: Unknown 0\n",
- "System.out.println(car2.brand + \" \" + car2.year); // Outputs: Ford 2020"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "![Constructors Diagram](https://runestone.academy/ns/books/published/csjava/_images/TurtleClassDefn.png)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# Escape Room: Constructor Puzzle\n",
- "\n",
- "You're trapped in a room and the only way out is to unlock a door using your Java constructor knowledge!\n",
- "\n",
- "### Rules:\n",
- "- Each clue is a code snippet related to constructors. Solve the problems to reveal the next clue.\n",
- "- Once you complete all tasks, you will receive the \"escape\" message.\n",
- "\n",
- "### Clue 1: \n",
- "The constructor below is missing a key part. Complete the code so that it runs correctly.\n",
- "\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "// CLUE 1 \n",
- "\n",
- "class Door {\n",
- " String lockCode;\n",
- "\n",
- " // Add the correct constructor here\n",
- " Door(_____ lock) {\n",
- " // Constructor body\n",
- " lockCode = _____;\n",
- " }\n",
- "}\n",
- "\n",
- "\n",
- "Door escapeDoor = new Door(\"1234\");\n",
- "System.out.println(escapeDoor.lockCode); // Should print: 1234\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "//CLUE 2\n",
- "\n",
- "class Room {\n",
- " String name;\n",
- " int area;\n",
- "\n",
- " // Constructor 1\n",
- " Room(String name) {\n",
- " this.name = name;\n",
- " }\n",
- "\n",
- " // Constructor 2 (missing)\n",
- " Room(String name, int area) {\n",
- " // Complete this constructor\n",
- " // Hint: Use the 'this' keyword\n",
- " }\n",
- "}\n",
- "\n",
- "Room escapeRoom = new Room(\"Puzzle Room\", 500);\n",
- "System.out.println(\"Room: \" + escapeRoom.name + \", Area: \" + escapeRoom.area); \n",
- "// Should print: Room: Puzzle Room, Area: 500\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "//CLUE 3\n",
- "class Key {\n",
- " String keyType;\n",
- "\n",
- " // Default constructor (to be completed)\n",
- " Key() {\n",
- " // Hint: Initialize keyType to a default value, e.g., \"Unknown\"\n",
- " }\n",
- "\n",
- " // Parameterized constructor\n",
- " Key(String keyType) {\n",
- " this.keyType = keyType;\n",
- " }\n",
- "}\n",
- "\n",
- "Key defaultKey = new Key();\n",
- "Key customKey = new Key(\"Golden Key\");\n",
- "\n",
- "System.out.println(\"Default Key: \" + defaultKey.keyType); // Should print: Unknown\n",
- "System.out.println(\"Custom Key: \" + customKey.keyType); // Should print: Golden Key\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "//CLUE 4\n",
- "class Vault {\n",
- " String vaultCode;\n",
- " boolean isLocked;\n",
- "\n",
- " // Constructor (Fix it)\n",
- " Vault(String code, Boolean lockStatus) {\n",
- " vaultCode = code;\n",
- " isLocked = lockStatus;\n",
- " }\n",
- "}\n",
- "\n",
- "Vault secretVault = new Vault(\"X1Y2Z3\", true);\n",
- "System.out.println(\"Vault Code: \" + secretVault.vaultCode + \", Is Locked: \" + secretVault.isLocked);\n",
- "// Should print: Vault Code: X1Y2Z3, Is Locked: true"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "//CLUE 5\n",
- "class Safe {\n",
- " String safeName;\n",
- " int capacity;\n",
- "\n",
- " // Default constructor (to be written)\n",
- " Safe() {\n",
- " // Initialize safeName to \"Unknown\" and capacity to 100\n",
- " }\n",
- "\n",
- " // Parameterized constructor (already complete)\n",
- " Safe(String name, int cap) {\n",
- " safeName = name;\n",
- " capacity = cap;\n",
- " }\n",
- "}\n",
- "\n",
- "Safe defaultSafe = new Safe();\n",
- "Safe customSafe = new Safe(\"Treasure Safe\", 1000);\n",
- "System.out.println(defaultSafe.safeName + \" \" + defaultSafe.capacity); // Outputs: Unknown 100\n",
- "System.out.println(customSafe.safeName + \" \" + customSafe.capacity); // Outputs: Treasure Safe 1000"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "//CLUE 6\n",
- "class Box {\n",
- " String color;\n",
- " int weight;\n",
- "\n",
- " // Constructor (with mistake)\n",
- " Box(String color, int w) {\n",
- " this.color = color;\n",
- " weight = w;\n",
- " }\n",
- "}\n",
- "\n",
- "Box myBox = new Box(\"Red\", 50);\n",
- "System.out.println(\"Box Color: \" + myBox.color + \", Weight: \" + myBox.weight);\n",
- "// Should print: Box Color: Red, Weight: 50"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "//FINAL CLUE\n",
- "class TreasureChest {\n",
- " String chestType;\n",
- " int goldCoins;\n",
- " boolean isLocked;\n",
- "\n",
- " // Constructor 1: No parameters (use constructor chaining to call Constructor 2)\n",
- " TreasureChest() {\n",
- " // Call Constructor 2 with default values \"Wooden\", 50, true\n",
- " }\n",
- "\n",
- " // Constructor 2: Takes all parameters\n",
- " TreasureChest(String type, int coins, boolean locked) {\n",
- " chestType = type;\n",
- " goldCoins = coins;\n",
- " isLocked = locked;\n",
- " }\n",
- "\n",
- " // Constructor 3: Takes only type and coins, defaults 'isLocked' to true\n",
- " TreasureChest(String type, int coins) {\n",
- " // Use constructor chaining to call Constructor 2 with true as the 'isLocked' value\n",
- " }\n",
- "\n",
- " // Constructor 4: Takes only the number of coins and defaults type to \"Wooden\" and isLocked to false\n",
- " TreasureChest(int coins) {\n",
- " // Call Constructor 2 using \"Wooden\", coins, and false as values\n",
- " }\n",
- "\n",
- " // Print method to check the values\n",
- " void printChestInfo() {\n",
- " System.out.println(\"Chest Type: \" + chestType + \", Gold Coins: \" + goldCoins + \", Is Locked: \" + isLocked);\n",
- " }\n",
- "}\n",
- "\n",
- "public class EscapeRoom {\n",
- " public static void main(String[] args) {\n",
- " // Test the different constructors by creating different objects\n",
- " TreasureChest chest1 = new TreasureChest();\n",
- " TreasureChest chest2 = new TreasureChest(\"Golden\", 100);\n",
- " TreasureChest chest3 = new TreasureChest(200);\n",
- "\n",
- " // Print information to check if everything works correctly\n",
- " chest1.printChestInfo(); // Should print: Wooden, 50, true\n",
- " chest2.printChestInfo(); // Should print: Golden, 100, true\n",
- " chest3.printChestInfo(); // Should print: Wooden, 200, false\n",
- "\n",
- " // Escape message when code is correctly fixed\n",
- " if (chest1 != null && chest2 != null && chest3 != null) {\n",
- " System.out.println(\"You have successfully escaped!\");\n",
- " }\n",
- " }\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# HINT: \n",
- "\n",
- " 1. Constructor chaining: You must properly use this() to chain constructors and avoid code duplication.\n",
- "\t2.\tCalling another constructor from a constructor: Ensure that each constructor calls the correct constructor with default or passed values.\n",
- "\t3.\tInitialize all fields properly: Ensure that every TreasureChest object is initialized with the correct values based on the constructor called."
- ]
- }
- ],
- "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": "17.0.12+8-LTS-286"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_05/Period3/2024-09-15-unit_5-constructors.ipynb b/_notebooks/CSA/units_1_to_10/unit_05/Period3/2024-09-15-unit_5-constructors.ipynb
deleted file mode 100644
index 8a8d5566..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_05/Period3/2024-09-15-unit_5-constructors.ipynb
+++ /dev/null
@@ -1,371 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "title: Constructors\n",
- "description: Unit 5 Classes and Objects - Constructors\n",
- "toc: True\n",
- "permalink: /csa/unit5/5.2/\n",
- "menu: nav/CSA_Units/csa_unit5_p3.html\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- " "
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Definition\n",
- "\n",
- "Constructors are like methods but are called as soon as an object of a class is made. They have the same name as the class and have no return type."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "public class Minion {\n",
- " Minion() {\n",
- " // constructor body\n",
- " }\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Cool example 🥶"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 2,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Name is: Bob\n"
- ]
- }
- ],
- "source": [
- "class Minion\n",
- "{\n",
- " // our name variable\n",
- " String name;\n",
- "\n",
- " // constructor\n",
- " Minion()\n",
- " {\n",
- " name = \"Bob\"; // set the name to something\n",
- " }\n",
- "}\n",
- "// Create minion object\n",
- "Minion myMinion = new Minion();\n",
- "System.out.println(\"Name is: \" + myMinion.name);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Your turn (yes this is a popcorn hack)\n",
- "\n",
- "- Make your own class with an integer variable\n",
- "- Make a constructor for that\n",
- "- Create an object and print the variable"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Constructor types (wait, theres more???)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### No-Arg Constructors\n",
- "\n",
- "A constructor with no parameters (arguments). Basically the one I just showed.\n",
- "\n",
- "```java\n",
- "Minion(/* there are no paremeters here*/) {\n",
- " name = \"Bob\";\n",
- "}\n",
- "```\n",
- "\n",
- "You can have a private and public version."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 6,
- "metadata": {},
- "outputs": [],
- "source": [
- "// private no-arg constructor\n",
- "\n",
- "class Minion\n",
- "{\n",
- " // our name variable\n",
- " String name;\n",
- "\n",
- " // constructor\n",
- " private Minion() {\n",
- " name = \"Bob\"; // set the name to something\n",
- " }\n",
- "\n",
- " public static void main(String[] args) {\n",
- " Minion myMinion = new Minion();\n",
- " }\n",
- "}\n",
- "\n",
- "// you can't make the object out of the class like below:\n",
- "// you will get an error\n",
- "\n",
- "// Minion myMinion = new Minion();"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 7,
- "metadata": {},
- "outputs": [],
- "source": [
- "// public no-arg constructor\n",
- "\n",
- "class Minion\n",
- "{\n",
- " // our name variable\n",
- " String name;\n",
- "\n",
- " // constructor\n",
- " public Minion() {\n",
- " name = \"Bob\"; // set the name to something\n",
- " }\n",
- "}\n",
- "\n",
- "// i can run this outside of the class now\n",
- "Minion myMinion = new Minion();"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Paremeterized Constructors\n",
- "\n",
- "A constructor WITH parameters (arguments).\n",
- "\n",
- "```java\n",
- "Minion(String n) {\n",
- " name = n;\n",
- "}\n",
- "```\n",
- "\n",
- "That's cool, but why use this???\n",
- "\n",
- "Well, what if I don't want the name to be \"Bob\"? What if I want it to be named \"mitochondria\"? That's what a parameterized constructor helps with!"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 9,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Name is: mitochondria\n",
- "Name is: Democratic Republic of Congo\n"
- ]
- }
- ],
- "source": [
- "class Minion\n",
- "{\n",
- " // our name variable\n",
- " String name;\n",
- "\n",
- " // constructor\n",
- " Minion(String n) {\n",
- " name = n; // set the name to something\n",
- " }\n",
- "}\n",
- "\n",
- "// demo:\n",
- "Minion myMinion = new Minion(\"mitochondria\");\n",
- "System.out.println(\"Name is: \" + myMinion.name);\n",
- "\n",
- "Minion myOtherMinion = new Minion(\"Democratic Republic of Congo\");\n",
- "System.out.println(\"Name is: \" + myOtherMinion.name);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Default Constructors\n",
- "\n",
- "**You can run but you can't hide (from constructors).**\n",
- "\n",
- "If you don't specify a constructor, Java will automatically make a no-arg constructor when you execute the constructor. You can think of it like a hidden constructor."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 11,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Name is: null\n"
- ]
- }
- ],
- "source": [
- "class Minion\n",
- "{\n",
- " // our name variable\n",
- " String name;\n",
- "\n",
- "}\n",
- "\n",
- "Minion myMinion = new Minion();\n",
- "System.out.println(\"Name is: \" + myMinion.name);\n",
- "\n",
- "// output should be null since we didn't give a value"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Your turn (aren't you having fun!!!)\n",
- "\n",
- "Using the code you wrote before (you did do the previous popcorn hack... right?), complete the following\n",
- "- Make a no-arg constructor\n",
- "- Make a parameterized constructor\n",
- "- \"Make\" a default constructor\n",
- "\n",
- "Please seperate all of those three into different code cells.\n",
- "\n",
- "Also, you don't actually have to use your previous code. I just thought it would be a good template."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Notes on contructors\n",
- "- Constructors are always made by default\n",
- "- To make a constructor:\n",
- " - Constructor name should be same as class name\n",
- " - Constructor has no return type\n",
- "- Constructor types:\n",
- " - No-Arg Constructor - a constructor that does not accept any arguments\n",
- " - Parameterized constructor - a constructor that accepts arguments\n",
- " - Default Constructor - a constructor that is automatically created by the Java compiler if it is not explicitly defined.\n",
- "- Constructor cannot be `abstract`, `static`, or `final`\n",
- "- A constructor can be overloaded (see below)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 12,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Bob\n",
- "Kevin\n"
- ]
- }
- ],
- "source": [
- "// overloaded constructor\n",
- "// (i put this last since it's a bit complicated)\n",
- "\n",
- "class Minion\n",
- "{\n",
- " String name;\n",
- "\n",
- " // no-arg constructor\n",
- " Minion() {\n",
- " this.name = \"Bob\";\n",
- " }\n",
- "\n",
- " // parameterized constructor\n",
- " // notice how it has the same name as the no-arg\n",
- " Minion(String n) {\n",
- " this.name = n;\n",
- " }\n",
- "\n",
- " public String getName() {\n",
- " return name;\n",
- " }\n",
- "\n",
- "}\n",
- "\n",
- "Minion myMinion = new Minion(); // no parameters\n",
- "Minion myOtherMinion = new Minion(\"Kevin\"); // with parameters\n",
- "\n",
- "System.out.println(myMinion.getName());\n",
- "System.out.println(myOtherMinion.getName());"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Your turn\n",
- "\n",
- "- Make a overloaded constructor"
- ]
- }
- ],
- "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": "3.12.6"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_05/Period3/2024-09-16-unit_5-classanatomy.ipynb b/_notebooks/CSA/units_1_to_10/unit_05/Period3/2024-09-16-unit_5-classanatomy.ipynb
deleted file mode 100644
index 3f3c50ca..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_05/Period3/2024-09-16-unit_5-classanatomy.ipynb
+++ /dev/null
@@ -1,261 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "title: Anatomy \n",
- "description: Unit 5 Classes and Objects - Anatomy\n",
- "toc: True\n",
- "menu: nav/CSA_Units/csa_unit5_p3.html\n",
- "permalink: /csa/unit5/5.1/"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Anatomy of a Class\n",
- "\n",
- "what is a class\n",
- "In object-oriented programming (OOP), a class is a blueprint for creating objects, which are the building blocks of a program. A class is a template that defines the variables and methods for a specific type of object.\n",
- "\n",
- "A class is composed of several key components that define its structure, behavior, and interaction with objects. Following are the key components of a class:\n",
- "\n",
- "### Class Declaration\n",
- "This is the starting point of any class. It includes the class keyword, class name, and access modifiers (public, private, etc.). It is a common convention to capitalize the first letter of the class name."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class Minions {\n",
- " // class body\n",
- "}\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Instance Variables\n",
- "Instance variables represent the attributes of the class. These variables are declared inside the class but outside any method. Instance variables are normally set as private variable and can be accessed using Accessor and Mutator methods."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class Minions {\n",
- " private String color;\n",
- " private int num_eyes;\n",
- "}\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Constructors\n",
- "A constructor is a special method that is called when an object is instantiated. It typically initializes the object’s fields.\n",
- "\n",
- "1. Default constructor: A constructor with no parameters.\n",
- "1. Overloaded constructor: A constructor that accepts parameters to initialize fields."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class Minions {\n",
- " private String color;\n",
- " private int num_eyes;\n",
- " \n",
- " // Default constructor\n",
- " public Minions() {\n",
- " color = \"\";\n",
- " num_eyes = 0; \n",
- " }\n",
- "\n",
- " // Overloaded constructor\n",
- " public Minions(String c, int n) {\n",
- " color = c;\n",
- " num_eyes = n;\n",
- " }\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Methods\n",
- "Methods define the behavior of a class. These are functions that operate on the class’s data (fields) or provide functionality.\n",
- "\n",
- "1. Accessor methods (Getters): Used to retrieve field values.\n",
- "1. Mutator methods (Setters): Used to modify field values."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class Minions {\n",
- " private String color;\n",
- " private int num_eyes;\n",
- " \n",
- " // Default constructor\n",
- " public Minions() {\n",
- " color = \"\";\n",
- " num_eyes = 0; \n",
- " }\n",
- "\n",
- " // Overloaded constructor\n",
- " public Minions(String c, int n) {\n",
- " color = c;\n",
- " num_eyes = n;\n",
- " }\n",
- "\n",
- " //Accessor Methods\n",
- " public String getColor() {\n",
- " return color;\n",
- " }\n",
- "\n",
- " public int getnumeyes(){\n",
- " return num_eyes;\n",
- " }\n",
- "\n",
- " //Mutator Methods\n",
- " public void setColor(String c){\n",
- " color = c;\n",
- " }\n",
- "\n",
- " public void setNumeyes(int n){\n",
- " if(n < 0 || n > 2){\n",
- " num_eyes = 1; //default value\n",
- " }\n",
- " else {\n",
- " num_eyes = n;\n",
- " }\n",
- " }\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Data Encapsulation\n",
- "Encapsulation is achieved by making instance variables private and providing public getter and setter methods to access and update the fields. This ensures that the internal implementation is hidden from the user and protects the object’s state. The setter method can contain validation logic that ensures only valid data is assigned to the field."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Popcorn Hack 1.\n",
- "\n",
- "Write a Student class. \n",
- " - Each student has a name \n",
- " - Each student has a score (out of 100)\n",
- " - A student passes if their score is above 70\n",
- "\n",
- "Check which student passes (write a class header, instance variables, constructors, and methods)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class Student {\n",
- " private String name;\n",
- " private int score;\n",
- " \n",
- " // Default constructor\n",
- " public Student() {\n",
- " name = \"\";\n",
- " score = 0; \n",
- " }\n",
- "\n",
- " // Overloaded constructor\n",
- " public Student(String n, int s) {\n",
- " name = n;\n",
- " score = s;\n",
- " }\n",
- "\n",
- " //Accessor Methods\n",
- " public String getName() {\n",
- " return name;\n",
- " }\n",
- "\n",
- " public int getScore(){\n",
- " return score;\n",
- " }\n",
- "\n",
- " //Mutator Methods\n",
- " public void setName(String n){\n",
- " name = n;\n",
- " }\n",
- "\n",
- " public void setScore(int s){\n",
- " if(s < 0 || s > 100){\n",
- " score = 0; //default value\n",
- " }\n",
- " else {\n",
- " score = s;\n",
- " }\n",
- " }\n",
- "\n",
- " public boolean pass(){\n",
- " return (score >= 70);\n",
- " }\n",
- "}"
- ]
- }
- ],
- "metadata": {
- "language_info": {
- "name": "python"
- },
- "orig_nbformat": 4
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_05/Period3/2024-09-17-unit_5-accessor.ipynb b/_notebooks/CSA/units_1_to_10/unit_05/Period3/2024-09-17-unit_5-accessor.ipynb
deleted file mode 100644
index 40316cb3..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_05/Period3/2024-09-17-unit_5-accessor.ipynb
+++ /dev/null
@@ -1,211 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "title: Accessor Methods\n",
- "description: Team Teach\n",
- "toc: True\n",
- "permalink: /csa/unit5/5.4/\n",
- "menu: nav/CSA_Units/csa_unit5_p3.html\n",
- "\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- " \n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## What is an Accessory Method?\n",
- "\n",
- "An accessor method, also known as getter methods allows other objects to obtain the value of instance variables or **static** variables.\n",
- "\n",
- "## Purpose of Accessor Methods\n",
- "- Allows safe access to instance variables\n",
- "- Accessor Methods keep data access private and secure\n",
- "- If you need to access instance variables form a different class, accessor methods are necessary"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Lets Make Our Own Accessor Methods"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 1,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Kevin\n",
- "4.1\n",
- "Sprout-Cut\n",
- "2\n"
- ]
- }
- ],
- "source": [
- "public class Minion\n",
- "{\n",
- " // Start by defining instance variables that you'll want to access later via the accessor methods\n",
- " private double height;\n",
- " private String name;\n",
- " private String hair;\n",
- " private int eyes;\n",
- "\n",
- " // Default Constructor\n",
- " //String n, int c\n",
- " public Minion()\n",
- " {\n",
- " height = 3.7;\n",
- " name = \"Bob\";\n",
- " hair = \"None\";\n",
- " eyes = 2;\n",
- " }\n",
- "\n",
- " // Overloaded Constructor\n",
- " public Minion(double h, String n, String hr, int e)\n",
- " {\n",
- " height = h;\n",
- " name = n;\n",
- " hair = hr;\n",
- " eyes = e;\n",
- " }\n",
- " // Accessor Methods!\n",
- " public double getHeight()\n",
- " {\n",
- " return height;\n",
- " }\n",
- " public String getName()\n",
- " {\n",
- " return name;\n",
- " }\n",
- " public String getHair()\n",
- " {\n",
- " return hair;\n",
- " }\n",
- " public int getEyes()\n",
- " {\n",
- " return eyes;\n",
- " }\n",
- "}\n",
- "\n",
- "// Create minion object Kevin\n",
- "Minion kevin = new Minion(4.10,\"Kevin\",\"Sprout-Cut\",2);\n",
- "\n",
- "// Print Kevin's properties\n",
- "System.out.println(kevin.getName());\n",
- "System.out.println(kevin.getHeight());\n",
- "System.out.println(kevin.getHair());\n",
- "System.out.println(kevin.getEyes());"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Popcorn Hack\n",
- "Gru is preparing for his big mission to steal the moon, and he needs to assign his minions various tasks based on their skills. Create a new getter method called ``skillLevel`` and print out the Minion's ``skillLevel``Minion class with the attributes ``name, task, and skillLevel.`` Implement some getter accessor methods, and then create a ``Minion`` object to retrieve its values."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 3,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Stuart\n",
- "Developing propulsion system\n"
- ]
- }
- ],
- "source": [
- "public class Minion {\n",
- " private String name;\n",
- " private String task;\n",
- " \n",
- " // Create skillLevel instance variable\n",
- "\n",
- " public Minion(String n, String t)\n",
- " {\n",
- " name = n;\n",
- " task = t;\n",
- " }\n",
- " // Getter Methods\n",
- " public String getName()\n",
- " {\n",
- " return name;\n",
- " }\n",
- " public String getTask()\n",
- " {\n",
- " return task;\n",
- " }\n",
- "\n",
- " // Add getter method here\n",
- "}\n",
- "Minion Stuart = new Minion(\"Stuart\", \"Developing propulsion system\");\n",
- "System.out.println(Stuart.getName());\n",
- "System.out.println(Stuart.getTask());\n",
- "// Add print statement to get skillLevel\n",
- "\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Things to keep in mind when creating your Accessor Methods\n",
- "- The accessor method must be public so that you can retrieve your instance variables outside of the class\n",
- "- The return Type must match the type of the instance variable accessed\n",
- "- The naming convention is often getNameOfVariable\n",
- "- There should be **no** parameters in your getter methods"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "![image](https://github.com/user-attachments/assets/17c57fb1-3572-4e6d-b695-914285cc867b)\n"
- ]
- }
- ],
- "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": "11.0.24+8-post-Ubuntu-1ubuntu322.04"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_05/Period3/2024-09-17-unit_5-mutator-methods.ipynb b/_notebooks/CSA/units_1_to_10/unit_05/Period3/2024-09-17-unit_5-mutator-methods.ipynb
deleted file mode 100644
index 8ff3c421..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_05/Period3/2024-09-17-unit_5-mutator-methods.ipynb
+++ /dev/null
@@ -1,230 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "title: Mutator Methods\n",
- "description: Team Teach\n",
- "toc: True\n",
- "permalink: /csa/unit5/5.5/\n",
- "menu: nav/CSA_Units/csa_unit5_p3.html\n",
- "\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- " "
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Definition\n",
- "\n",
- "A mutator method modifies an object's state my changing the value of its fields or attributes.\n",
- "\n",
- "Example:\n",
- "\n",
- "Say you have an object called \"Minion.\" If I have a field like \"name,\" a mutator method lets me change its value.\n",
- "\n",
- "## Okay but why???\n",
- "\n",
- "Mutator methods are part of Java's philsophy of \"encapsulation.\"\n",
- "\n",
- "That's nerd-speak for \"keeping things seperate\". It's the idea of enclosing data and methods as a unit. You want to restrict direct access to data, only accessing them through a PROPERLY defined way."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Mutator method types:\n",
- "\n",
- "Accessors: can you guess what this does? That's right, it lets you *access* data. These can be called \"get\" methods or \"getters.\""
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class Minion\n",
- "{\n",
- " private String name;\n",
- "\n",
- " // notice how the getter method starts with \"get\" (pretty creative, I know)\n",
- " // these methods have to be names like this where you have get\n",
- " public String getName() {\n",
- " // because \"name\" is a string, return type is String\n",
- " return name;\n",
- " }\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Your turn!\n",
- "\n",
- "- Make your own class with your own getter method"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Mutators: wait a minute, a \"mutator\" is a type of mutator method??? Yeah, Java is kinda wacky like that. Try not to think about it much. Anyways... these methods let you *mutate* data (basically change it). They can be called \"set\" methods or \"setters.\""
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class Minion\n",
- "{\n",
- " private String name;\n",
- "\n",
- " // same naming scheme as a getter but with set instead\n",
- " public void setName(String n) {\n",
- " name = n;\n",
- " }\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Your turn!\n",
- "\n",
- "- Make your own class with your own **setter** method"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## EXAMPLE TIME WOOOOOOO!!!!!!! 🤓🤓🤓"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 22,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Kevin\n",
- "Bob\n"
- ]
- }
- ],
- "source": [
- "public class Minion {\n",
- " // the minion's name\n",
- " private String name;\n",
- "\n",
- " // Constructor to set the name\n",
- " public Minion(String n) {\n",
- " name = n;\n",
- " }\n",
- "\n",
- " // getter\n",
- " public String getName() {\n",
- " return name;\n",
- " }\n",
- "\n",
- " // setter\n",
- " public void setName(String n) {\n",
- " name = n;\n",
- " }\n",
- "}\n",
- "\n",
- "// Create a Minion object and interact with it\n",
- "Minion myMinion = new Minion(\"Kevin\");\n",
- "\n",
- "System.out.println(myMinion.getName()); // get the name\n",
- "\n",
- "myMinion.setName(\"Bob\");\n",
- "System.out.println(myMinion.getName()); // wow look, the name changed!!\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Your turn!\n",
- "\n",
- "Make your own class with:\n",
- "- A constructor\n",
- "- A getter\n",
- "- A setter\n",
- "\n",
- "Create an object and interact with it! Make sure you use both your setter and getter methods at least once."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## When making mutator methods...\n",
- "- A setter method has a `void` return type since it doesn't return anything\n",
- " - Naming convention: `set` like `setName`\n",
- "- A getter method's return type is of what it is returning\n",
- " - Naming convention: `get` like `getName`\n",
- "- Mutator methods in general change variable in a safe way\n",
- " - They have to be public if you want to access these variable outside of the class (which is the purpose they serve)\n",
- "- Parameter type matches the variable you're modifying\n",
- " - `public void setName(String n)`\n",
- " - You are modifying a `String` called `n`\n",
- " - Parameter type matches!"
- ]
- }
- ],
- "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": "17.0.12+7-Ubuntu-1ubuntu222.04"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_05/Period3/2024-09-17-unit_5-toString.ipynb b/_notebooks/CSA/units_1_to_10/unit_05/Period3/2024-09-17-unit_5-toString.ipynb
deleted file mode 100644
index 9558fcb1..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_05/Period3/2024-09-17-unit_5-toString.ipynb
+++ /dev/null
@@ -1,217 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "title: toString Method\n",
- "description: Team Teach\n",
- "toc: True\n",
- "permalink: /csa/unit5/5.41/\n",
- "menu: nav/CSA_Units/csa_unit5_p3.html\n",
- "\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- " "
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## toString Accessor Method\n",
- "The toString accessor method is an overridden method that is included in classes to provide a description of a specific object. It returns a sting description of the instance variables of the object. The method is called automatically to try to convert an object to a String when needed.\n",
- "\n",
- "If System.out.print or System.out.println is passed an object, that object's toString method is called and the returned string is printed."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## If you try to just print the object...\n",
- "It won't print the information that you want."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 1,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "REPL.$JShell$12$Minion@f979182\n"
- ]
- }
- ],
- "source": [
- "public class Minion\n",
- "{\n",
- " // Start by defining instance variables that you'll want to access later via the accessor methods\n",
- " private double height;\n",
- " private String name;\n",
- " private String hair;\n",
- " private int eyes;\n",
- "\n",
- " // Default Constructor\n",
- " //String n, int c\n",
- " public Minion()\n",
- " {\n",
- " height = 3.7;\n",
- " name = \"Bob\";\n",
- " hair = \"None\";\n",
- " eyes = 2;\n",
- " }\n",
- "\n",
- " // Overloaded Constructor\n",
- " public Minion(double h, String n, String hr, int e)\n",
- " {\n",
- " height = h;\n",
- " name = n;\n",
- " hair = hr;\n",
- " eyes = e;\n",
- " }\n",
- " // Accessor Methods!\n",
- " public double getHeight()\n",
- " {\n",
- " return height;\n",
- " }\n",
- " public String getName()\n",
- " {\n",
- " return name;\n",
- " }\n",
- " public String getHair()\n",
- " {\n",
- " return hair;\n",
- " }\n",
- " public int getEyes()\n",
- " {\n",
- " return eyes;\n",
- " }\n",
- "}\n",
- "// Create minion object Kevin\n",
- "Minion kevin = new Minion(4.10,\"Kevin\",\"Sprout-Cut\",2);\n",
- "\n",
- "// Print Kevin Object\n",
- "System.out.println(kevin);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## The toString Method\n",
- "When the System.out.println() is used, the toString method ``within the class`` is automatically called to print the object's values.\n",
- "![image](https://github.com/user-attachments/assets/ba8657e5-a3ba-4445-b26a-ad6712cf223b)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Popcorn Hack\n",
- "\n",
- "Return all the instance variables in ``Minion`` so that we can directly print the object values of the minion Kevin."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 4,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Name:Kevin\n",
- "Height: 4.1\n",
- "Hair:Sprout-Cut\n",
- "Eyes: 2\n"
- ]
- }
- ],
- "source": [
- "public class Minion\n",
- "{\n",
- " // Start by defining instance variables that you'll want to access later via the accessor methods\n",
- " private double height;\n",
- " private String name;\n",
- " private String hair;\n",
- " private int eyes;\n",
- "\n",
- " // Default Constructor\n",
- " //String n, int c\n",
- " public Minion()\n",
- " {\n",
- " height = 3.7;\n",
- " name = \"Bob\";\n",
- " hair = \"None\";\n",
- " eyes = 2;\n",
- " }\n",
- "\n",
- " // Overloaded Constructor\n",
- " public Minion(double h, String n, String hr, int e)\n",
- " {\n",
- " height = h;\n",
- " name = n;\n",
- " hair = hr;\n",
- " eyes = e;\n",
- " }\n",
- " // Accessor Methods!\n",
- " public String toString()\n",
- " {\n",
- " // Code here\n",
- " }\n",
- "}\n",
- "// Create minion object Kevin\n",
- "Minion kevin = new Minion(4.10,\"Kevin\",\"Sprout-Cut\",2);\n",
- "\n",
- "// Print Kevin Object\n",
- "System.out.println(kevin);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## When Creating a toString Accessor Method...\n",
- "- You cannot change the header of the method public String toString() -> cannot change this\n",
- "- Always returns string\n",
- "- Doesn't take any parameters\n",
- "- When System.out.printIn(object) is called on an object:\n",
- " - toString method is called\n",
- " - returned string is printed"
- ]
- }
- ],
- "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": "11.0.24+8-post-Ubuntu-1ubuntu322.04"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_05/Period3/2024-09-17-unit_5-writing-methods.ipynb b/_notebooks/CSA/units_1_to_10/unit_05/Period3/2024-09-17-unit_5-writing-methods.ipynb
deleted file mode 100644
index e8ce137e..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_05/Period3/2024-09-17-unit_5-writing-methods.ipynb
+++ /dev/null
@@ -1,210 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "toc: true\n",
- "title: Writing Methods \n",
- "type: ccc\n",
- "Authors: Aashray, Lilian, Matthew, Tara, and Trevor\n",
- "permalink: /csa/unit5/5.6/\n",
- "menu: nav/CSA_Units/csa_unit5_p3.html\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- " "
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## What is a Method?!\n",
- "> A method is a **block of code that belong to a class**, very similar to a function. \n",
- "\n",
- "Methods in Java can take inputs (parameters), perform actions, and return a value (or void if no value is returned).\n",
- "\n",
- "Methods that are created by the programmer to perform tasks are called **user-defined methods**, while other methods can be built in (like System.out.println())."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Types of methods:\n",
- "There are many different types of methods in Java, but here I'll only highlight the two most common ones and the ones used by College board.\n",
- "\n",
- "> Instance Methods: Methods that belong to an **instance** of a class\n",
- "Instance methods require an object of the class to be used. They operate on objects of the class.\n",
- "- Can access instance variables and other instance methods within the class\n",
- "- Can access static variables and methods\n",
- "\n",
- "> Static Methods: Methods that belong to the class itself trather than any instance of the class. Trhey are used for operations taht do not depend on instance-spefific data. \n",
- "- Can only directly access other static variables and methods."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Here's a quick example!\n",
- "- Example of an instance method: addMinion()\n",
- " - Adds a minion to the list of a villain\n",
- " - Parameters: String minon\n",
- " - Example call: gru.addMinion(\"Kevin\")\n",
- "- Second example of an instance method: Villain()\n",
- " - Changes instance data\n",
- " - Parameters: string Name, String evilPlan\n",
- "\n",
- "- Example of a static method: getVillainCount()\n",
- " - Returns the total amount of Villain instances\n",
- " - No parameters\n",
- " - Example call: System.out.println(\"There are \" + Villain.getVillainCount() + \" villains in the world.\");"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Popcorn hack:\n",
- "- Add another static method to the Villain class\n",
- "- Keep it minion themed and fun!"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 21,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "=== Adding Minions ===\n",
- "Kevin has been added to Gru's army.\n",
- "Stuart has been added to Gru's army.\n",
- "Bob has been added to Gru's army.\n",
- "Henchman 1 has been added to Vector's army.\n",
- "\n",
- "=== Villain Descriptions ===\n",
- "Gru is planning to: steal the moon!\n",
- "They have 3 minions.\n",
- "\n",
- "Vector is planning to: take over the world with magnitude and direction!\n",
- "They have 1 minions.\n",
- "\n",
- "=== Total Villain Count ===\n",
- "There are 2 villains in the world.\n"
- ]
- }
- ],
- "source": [
- "import java.util.ArrayList;\n",
- "import java.util.List;\n",
- "\n",
- "public class Villain {\n",
- " // Instance variables\n",
- " public String name;\n",
- " public String evilPlan;\n",
- " public List minions;\n",
- " public static int villainCount = 0;\n",
- "\n",
- " // Constructor for name, plan, and minions\n",
- " public Villain(String name, String evilPlan) {\n",
- " this.name = name;\n",
- " this.evilPlan = evilPlan;\n",
- " this.minions = new ArrayList<>();\n",
- " villainCount++;\n",
- " }\n",
- "\n",
- " // Instance method to add a minion. LOOK HERE!!\n",
- " public void addMinion(String minion) {\n",
- " minions.add(minion);\n",
- " System.out.println(minion + \" has been added to \" + name + \"'s army.\");\n",
- " }\n",
- "\n",
- " // Instance method to describe the villain. \n",
- " public void describeVillain() {\n",
- " System.out.println(name + \" is planning to: \" + evilPlan);\n",
- " System.out.println(\"They have \" + minions.size() + \" minions.\");\n",
- " }\n",
- "\n",
- " // Static method to get the total count of villains\n",
- " public static int getVillainCount() {\n",
- " return villainCount;\n",
- " }\n",
- "}\n",
- "\n",
- "public class Main {\n",
- " public static void main(String[] args) {\n",
- " Villain.villainCount = 0;\n",
- "\n",
- " // Create new villains\n",
- " Villain gru = new Villain(\"Gru\", \"steal the moon!\");\n",
- " Villain vector = new Villain(\"Vector\", \"take over the world with magnitude and direction!\");\n",
- "\n",
- " System.out.println(\"=== Adding Minions ===\");\n",
- " // Create some minions\n",
- " gru.addMinion(\"Kevin\");\n",
- " gru.addMinion(\"Stuart\");\n",
- " gru.addMinion(\"Bob\");\n",
- "\n",
- " // Create some minions for Vector\n",
- " vector.addMinion(\"Henchman 1\");\n",
- "\n",
- " System.out.println();\n",
- "\n",
- " // Describe the villains and their plans\n",
- " System.out.println(\"=== Villain Descriptions ===\");\n",
- " gru.describeVillain();\n",
- " System.out.println();\n",
- " vector.describeVillain();\n",
- " System.out.println();\n",
- "\n",
- " // Get the total count of villains\n",
- " System.out.println(\"=== Total Villain Count ===\");\n",
- " System.out.println(\"There are \" + Villain.getVillainCount() + \" villains in the world.\");\n",
- " }\n",
- "}\n",
- "\n",
- "Main.main(null);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Popcorn hack:\n",
- "Dr. Nefario is busy assigning work for the minions, and he needs your help to organize his group. Your mission is to write and implement a Java classes for each minion which includes their name, gadgets, personality, and more. Get ready to make Dr. Nefario's life easier and keep the minions organized!"
- ]
- }
- ],
- "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": "17.0.12+7-Ubuntu-1ubuntu222.04"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_05/Period3/2024-09-18-unit_5-static-variables-and-methods.ipynb b/_notebooks/CSA/units_1_to_10/unit_05/Period3/2024-09-18-unit_5-static-variables-and-methods.ipynb
deleted file mode 100644
index 93890c51..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_05/Period3/2024-09-18-unit_5-static-variables-and-methods.ipynb
+++ /dev/null
@@ -1,231 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "toc: true\n",
- "title: Static Variables and Methods\n",
- "Authors: Aashray, Lilian, Matthew, Tara, and Trevor\n",
- "permalink: /csa/unit5/5.7/\n",
- "menu: nav/CSA_Units/csa_unit5_p3.html\n",
- "\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- " "
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## What are static variables?\n",
- "> Static variables: belong to the class rather than a particular instance. \n",
- "- These types of variables are variables shared across all instances of a class."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 13,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Total gadgets made: 3\n"
- ]
- }
- ],
- "source": [
- "import java.util.ArrayList;\n",
- "import java.util.List;\n",
- "\n",
- "public class Gadget {\n",
- " public static int totalGadgets = 0; // Static variable to track total gadgets made\n",
- " private String gadgetName; // Instance variable to store the name of the gadget\n",
- " //public static List gadgetsList = new ArrayList<>(); // Static list to track all gadgets\n",
- "\n",
- " // Constructor to set the gadget name and increment totalGadgets\n",
- " public Gadget(String gadgetName) {\n",
- " this.gadgetName = gadgetName;\n",
- " totalGadgets++; // Increment the total gadgets count\n",
- " // gadgetsList.add(this); // Add this gadget to the static list\n",
- " }\n",
- "\n",
- "}\n",
- "// In the Main class:\n",
- "public class Main {\n",
- " public static void main(String[] args) {\n",
- " // Create three gadgets\n",
- " Gadget g1 = new Gadget(\"Freeze Ray\");\n",
- " Gadget g2 = new Gadget(\"Banana Blaster\");\n",
- " Gadget g3 = new Gadget(\"Lipstick Taser\");\n",
- "\n",
- " // Print the total number of gadgets\n",
- " System.out.println(\"Total gadgets made: \" + Gadget.totalGadgets);\n",
- " }\n",
- "}\n",
- "\n",
- "Main.main(null);\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Cool, but why did I have to use a static variable?\n",
- "- The totalGadgets was made as a static variable because it is tracking data that is shared across **all instances** of the Gadget class.\n",
- "- If totalGadgets was an instance variable, then it would always be 1 since it would only reflect how many gadgets are in the specific instance."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Popcorn hacks:\n",
- "- Look at some of the code I've commented out and try experimenting with gadgetsList if you want. Otherwise, just make a static variable that serves a purpose in the program."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## What are static methods?\n",
- "> Static methods are associated with the class and not any object of the class\n",
- "- Static methods can only directly access other static methods and static variables of the class. \n",
- "- They cannot use the \"this\" keyword because they don't belong to any instance."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Here's an example:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 14,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Total gadgets made: 3\n",
- "Gadgets created:\n",
- "- Freeze Ray\n",
- "- Banana Blaster\n",
- "- Lipstick Taser\n"
- ]
- }
- ],
- "source": [
- "import java.util.ArrayList;\n",
- "import java.util.List;\n",
- "\n",
- "public class Gadget {\n",
- " public static int totalGadgets = 0; // Static variable to track total gadgets made\n",
- " private String gadgetName; // Instance variable to store the name of the gadget\n",
- " public static List gadgetsList = new ArrayList<>(); // Static list to track all gadgets\n",
- "\n",
- " // Constructor to set the gadget name and increment totalGadgets\n",
- " public Gadget(String gadgetName) {\n",
- " this.gadgetName = gadgetName;\n",
- " totalGadgets++; // Increment the total gadgets count\n",
- " gadgetsList.add(this); // Add this gadget to the static list\n",
- " }\n",
- "\n",
- " // Getter for the gadget name\n",
- " public String getGadgetName() {\n",
- " return gadgetName;\n",
- " }\n",
- "\n",
- " // Static method to print all gadgets in the list\n",
- " public static void printAllGadgets() {\n",
- " System.out.println(\"Gadgets created:\");\n",
- " for (int i = 0; i < gadgetsList.size(); i++) {\n",
- " System.out.println(\"- \" + gadgetsList.get(i).getGadgetName());\n",
- " }\n",
- " }\n",
- "}\n",
- "\n",
- "// In the Main class:\n",
- "public class Main {\n",
- " public static void main(String[] args) {\n",
- " // Create three gadgets\n",
- " Gadget g1 = new Gadget(\"Freeze Ray\");\n",
- " Gadget g2 = new Gadget(\"Banana Blaster\");\n",
- " Gadget g3 = new Gadget(\"Lipstick Taser\");\n",
- "\n",
- " // Print the total number of gadgets\n",
- " System.out.println(\"Total gadgets made: \" + Gadget.totalGadgets);\n",
- "\n",
- " // Print all gadgets stored in the static list\n",
- " Gadget.printAllGadgets();\n",
- " }\n",
- "}\n",
- "\n",
- "Main.main(null);\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Why did I use a static method?\n",
- "- Static methods can only directly access other static variables and methods, such as gadgetsList\n",
- "- I needed to print inforamtion about all instances of the Gadget class, which applied to the entire class as a whole."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "source": [
- "## Popcorn hack:\n",
- "Dr. Nefario and Gru need to calculate the cost of their equipment to remain under the budget for this year! Add a second parameter to the Gadget constructor to include cost for Gadget instances, and make a static method to calculate the price of all gadgets that have been made so far."
- ]
- }
- ],
- "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": "17.0.12+7-Ubuntu-1ubuntu222.04"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_05/Period3/2024-09-19-unit_5-this-keyword.ipynb b/_notebooks/CSA/units_1_to_10/unit_05/Period3/2024-09-19-unit_5-this-keyword.ipynb
deleted file mode 100644
index 64d0e3cd..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_05/Period3/2024-09-19-unit_5-this-keyword.ipynb
+++ /dev/null
@@ -1,296 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "title: This Keyword\n",
- "description: Team Teach\n",
- "toc: True\n",
- "permalink: /csa/unit5/5.9/\n",
- "menu: nav/CSA_Units/csa_unit5_p3.html\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# `This` Keyword\n",
- "\n",
- "### General\n",
- "- `this` keyword is used as a reference to the object itself\n",
- " - It can be used to reference the object’s instance variables, methods, constructors, etc.\n",
- " - Enables instance variables to access an object’s variables and methods\n",
- "- It is used to avoid confusion between instance variables and parameter values (local variables)\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class Minion {\n",
- " private int banana = 5;\n",
- " public void setBanana(int banana) {\n",
- " this.banana = banana; //this.banana refers to the instance variable banana\n",
- " // banana refers to the parameter banana\n",
- " }\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Calling Another Constructor\n",
- "- `this` keyword can be used to invoke another constructor of the same class\n",
- "\n",
- "Format: this.(*argument*)\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class MinionGoggles {\n",
- " private double lensSize;\n",
- " public MinionGoggles(double lensSize) {\n",
- " this.lensSize = lensSize; //this keyword references the hidden data field, lensSize\n",
- " }\n",
- " public MinionGoggles() {\n",
- " this(1.0); //passes 1.0 as an argument to the 1st constructor\n",
- " }\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Calling Other Methods\n",
- "- `this` keyword can be used to call other methods in the same class\n",
- "\n",
- "Format: this.*methodName*()"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class Minion {\n",
- " private String name;\n",
- "\n",
- " public Minion(String name) {\n",
- " this.name = name;\n",
- " }\n",
- "\n",
- " public void run() {\n",
- " System.out.println(this.name + \" is running\");\n",
- " this.speak(); // Calls the speak method of the current object\n",
- " }\n",
- "\n",
- " public void speak() {\n",
- " System.out.println(this.name + \" says: 'Bello!'\");\n",
- " }\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Passing `this` as a Parameter\n",
- "- `this` keyword can be used to pass the reference of the current object to a method or constructor\n",
- "- Format: *methodName*(this)\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "class Minion {\n",
- " String name;\n",
- "\n",
- " Minion(String name) {\n",
- " this.name = name;\n",
- " }\n",
- "\n",
- " void printMinion(Student minion) {\n",
- " System.out.println(\"Minion name: \" + minion.name);\n",
- " }\n",
- " \n",
- " void callPrintMinion() {\n",
- " printMinion(this); // Passes the current object to the method\n",
- " }\n",
- "}\n",
- "\n",
- "public class Main {\n",
- " public static void main(String[] args) {\n",
- " Student minion1 = new Minion(\"Kevin\");\n",
- " minion1.callPrintMinion(); // Output: Minion name: Kevin\n",
- " }\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Popcorn Hacks\n",
- "The Minions are preparing for a big event where the tallest and fastest minion will get to assist Gru on his next mission! You’ve been called in as the official \"Minion Trainer\" to help compare the minions. The goal is to see which minion is more prepared for the mission.\n",
- "\n",
- " \n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 17,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class Minion {\n",
- " private String speed;\n",
- " private int height;\n",
- "\n",
- " public void Minion(String speed, int height) {\n",
- " this.speed = speed;\n",
- " this.height = height;\n",
- " }\n",
- "\n",
- " public void setHeight(int height) {\n",
- " this.height = height; \n",
- " }\n",
- "\n",
- " public String getSpeed() {\n",
- " return this.speed; \n",
- " }\n",
- "\n",
- " public boolean isTallerThan(Minion otherMinion) {\n",
- " return this.height > otherMinion.height; \n",
- " }\n",
- "\n",
- " public static void main(String[] args) {\n",
- " Minion minion1 = new Minion(\"fast\", 43);\n",
- " Minion minion2 = new Minion(\"medium\", 28);\n",
- "\n",
- " System.out.println(\"minion 1 speed: \" + minion1.getSpeed());\n",
- " System.out.println(\"Is minion1 taller than minion2? \" + minion1.isTallerThan(minion2));\n",
- "\n",
- " minion2.setHeight(50);\n",
- " System.out.println(\"Is minion1 still taller than minion2? \" + minion1.isTallerThan(minion2));\n",
- " }\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "1. What is the output of the statement *System.out.println(\"minion 1 speed: \" + minion1.speed())*? Explain why the `this` keyword is useful in the *getSpeed()* method.\n",
- "\n",
- "2. What does the *isTallerThan()* method compare?\n",
- "\n",
- "3. What happens to the result of *System.out.println(\"Is minion1 taller than minion2? \" + minion1.isTallerThan(minion2))* after *minion2.setHeight(50)* is called?\n",
- "\n",
- "\n",
- "Who should be selected for the mission?🤔"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌🍌\n",
- " \n",
- " \n",
- "\n",
- "In the bustling kitchen of Gru’s secret lab, the Minions were on a mission to create the perfect pancake for their breakfast feast. Kevin needed to make sure each pancake was perfectly round, with the exact right circumference for maximum deliciousness. But how? He needed to figure out the precise relationship between the pancake’s radius and its circumference. Help Kevin create the perfect pancake!\n",
- "\n",
- "The `MinionPancake` class below should have:\n",
- "- A `radius` field\n",
- "- A method `setRadius(double radius)`: have this set as the radius\n",
- "- A method `calculateCircumference()`: have this calculate the circumference of a circle with radius 5 and print it\n",
- " - (hint: use Math.PI for 'π')"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 13,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "class MinionPancake {\n",
- " private double radius;\n",
- "\n",
- " public void setRadius(double radius) {\n",
- " // Use 'this' to set the radius\n",
- " \n",
- " }\n",
- "\n",
- " public void calculateCircumference() {\n",
- " // Calculate circumference and print result\n",
- " \n",
- " }\n",
- "}\n",
- "\n",
- "// Create a pancake with radius 5 and calculate its circumference\n",
- "MinionPancake pancake = new MinionPancake();\n"
- ]
- }
- ],
- "metadata": {
- "kernelspec": {
- "display_name": "java (IJava/j!)",
- "language": "java",
- "name": "jbang-ijava"
- },
- "language_info": {
- "codemirror_mode": "java",
- "file_extension": ".jshell",
- "mimetype": "text/x-java-source",
- "name": "Java",
- "pygments_lexer": "java",
- "version": "22.0.2+9-70"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_05/Period3/2024-09-22-unit_5-home.ipynb b/_notebooks/CSA/units_1_to_10/unit_05/Period3/2024-09-22-unit_5-home.ipynb
deleted file mode 100644
index 976d63ed..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_05/Period3/2024-09-22-unit_5-home.ipynb
+++ /dev/null
@@ -1,56 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "title: Unit 5 Classes P3\n",
- "type: ccc\n",
- "toc: True\n",
- "courses: {'csa': {'week': 6}}\n",
- "permalink: /csa/unit5/\n",
- "menu: nav/CSA_Units/csa_unit5_p3.html\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Unit 5 Homepage\n",
- "In unit 5, you will be learning all about classes and methods in Java.\n",
- "\n",
- "### Learning Objectives\n",
- "- Learn about the different types of methods\n",
- "- Understand how to write classes \n",
- "- Practice your skills in the homework!\n",
- "\n",
- "### Topics\n",
- "- **5.1** Anatomy of a Class\n",
- "- **5.2** Constructors\n",
- "- **5.4** Accessor Methods\n",
- "- **5.5** Mutator Methods\n",
- "- **5.6** Writing Methods\n",
- "- **5.7** Static Variables and Methods\n",
- "- **5.8** Scope and Access\n",
- "- **5.9** this Keyword\n",
- "\n",
- "\n",
- "\n"
- ]
- }
- ],
- "metadata": {
- "language_info": {
- "name": "python"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_05/Period3/2024-09-22-unit_5-scope_access_hacks.ipynb b/_notebooks/CSA/units_1_to_10/unit_05/Period3/2024-09-22-unit_5-scope_access_hacks.ipynb
deleted file mode 100644
index cedbe9ba..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_05/Period3/2024-09-22-unit_5-scope_access_hacks.ipynb
+++ /dev/null
@@ -1,187 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "title: Scope and Access\n",
- "description: Team Teach\n",
- "toc: True\n",
- "permalink: /csa/unit5/5.8/\n",
- "menu: nav/CSA_Units/csa_unit5_p3.html\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- " "
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Scope and Access"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Local Scope\n",
- "- Local variables can be ``declared in the body of constructors and methods``. These variables may only be used within the constructor method and cannot be declared to be **public** or **private**\n",
- "\n",
- "- When there is a local variable with the same name as an instance variable, the variable name will refer to the local variable instead of the instance variable\n",
- "\n",
- "- Formal parameters and variables declared in a method or constructor can only be used within that method or constructor"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class LocalScopeExample{\n",
- " public void Local()\n",
- " {\n",
- " int a = 10;//Defining a local variable\n",
- " if (a > 5)\n",
- " {\n",
- " int b = 20;//Defining a variable in the local scope of this if statement\n",
- " }\n",
- " // Try to access the local variable outside the class\n",
- " System.out.println(b);\n",
- "\n",
- " }\n",
- "}\n",
- "LocalScopeExample example = new LocalScopeExample();\n",
- "example.Local(); // This will print: Value of b: 20"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Class Level Scope\n",
- "- Instance variables will be accessible **anywhere within the class** and they can be used in all of the methods in the class. If the variable is defined as ``private`` the variable will not be accessible outside of the class. If it is defined as public, it allows access to a class, method or variable from ``both inside and outside the class.``"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class LocalScopeExample{\n",
- " // Defining an instance variable\n",
- " private int b = 10;\n",
- "\n",
- " public void Local()\n",
- " {\n",
- " int a = 10;//Defining a local variable\n",
- " if (a > 5)\n",
- " {\n",
- " b = 20;//Defining a variable in the local scope of this if statement\n",
- " }\n",
- " // Try to access the local variable outside the class\n",
- " System.out.println(\"Value of b: \" + b);\n",
- " }\n",
- "}\n",
- "LocalScopeExample example = new LocalScopeExample();\n",
- "example.Local(); // This will print: Value of b: 20"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Let's go through an example\n",
- "\n",
- "Lets create a class called MinionMood. In order to ensure maximum productivity with the minions we have to keep track of how they're feeling throughout the day.\n",
- "\n",
- "Then lets create some instance variables and a method to increase the happiness level of the minion based on how many bananas they have eaten, and make it such that the energy level of the minion decreases based on how many tasks they have to complete."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class MinionMood\n",
- "{\n",
- " private int happinessLevel;\n",
- " private int energyLevel;\n",
- "\n",
- " public MinionMood(int bananas, int tasks)\n",
- " {\n",
- " int happinessLevel = 2*bananas;\n",
- " int energyLevel = tasks;\n",
- " }\n",
- " public String toString()\n",
- " {\n",
- " return \"Happiness Level: \" + happinessLevel + \"\\nEnergy Level: \" + energyLevel;\n",
- " }\n",
- "}\n",
- "\n",
- "MinionMood bob = new MinionMood(5, 2);\n",
- "System.out.println(bob);\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Popcorn Hack\n",
- "- Figure out why the happiness level and the energy level is not showing up the way we want it to. First one to do so will get a high five from Trevor Huang."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Oops...\n",
- "\n",
- "Its very important to keep in mind that a local variable within a method that has the same name as an instance variable will just redeclare the variable. So, to make the code work the way we want it to, all that we have to do is get rid of the statements that redeclare the variable.s"
- ]
- }
- ],
- "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": "11.0.24+8-post-Ubuntu-1ubuntu322.04"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_05/Period3/2024-09-23-unit_5-homework.ipynb b/_notebooks/CSA/units_1_to_10/unit_05/Period3/2024-09-23-unit_5-homework.ipynb
deleted file mode 100644
index d14ec041..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_05/Period3/2024-09-23-unit_5-homework.ipynb
+++ /dev/null
@@ -1,52 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "title: Homework\n",
- "description: Unit 5 Homework (Period 3)\n",
- "toc: True\n",
- "permalink: /csa/unit5/homework/\n",
- "menu: nav/CSA_Units/csa_unit5_p3.html\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Hack 1\n",
- "Gru has just recently stopped El Macho from destroying the world. But now, Gru needs to separate the leftover purple minions and the yellow minions so that he can cure the infected minions. He then needs to organize the minions in terms of recovery time and usefulness. To do this, Gru needs you to make a minion class with the instance variables ``color, name, energy levels, gadgets, hair, height``\n",
- "\n",
- "## Hack 2\n",
- "Now Gru needs you to make a default constructor for all the NPC minions. Assign each default minion a default color,name,energy level, gadget, hair, and height. \n",
- "\n",
- "## Hack 3\n",
- "Now please make a parameterized constructor to create the main-character minions easily.\n",
- "\n",
- "## Hack 4\n",
- "Create three minions and print out their values(color, name, energy levels, gadgets, hair, height)\n",
- "\n",
- "## Hack 5\n",
- "Gru wants to make sure his workers are not overworked as per OSHA. So, Gru wants you to print out the average energy levels of all his Minions. (Hint: you should use static variables) \n",
- "\n",
- "## For 0.90+\n",
- "Dr. Nefario is trying to assign a recovery time for each minion! Minions who were purple and got cured are very tired, and so are a lot of minions with low energy levels. Create a simple algorithm to calculate how long each minion needs to recover based on their color and energy levels.\n"
- ]
- }
- ],
- "metadata": {
- "language_info": {
- "name": "python"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_06/Period1/2024-09-12-unit_6-0-homepage.ipynb b/_notebooks/CSA/units_1_to_10/unit_06/Period1/2024-09-12-unit_6-0-homepage.ipynb
deleted file mode 100644
index e8b1d026..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_06/Period1/2024-09-12-unit_6-0-homepage.ipynb
+++ /dev/null
@@ -1,77 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "toc: true\n",
- "title: Unit 6 Arrays P1 \n",
- "courses: {'csa': {'week': 4}}\n",
- "type: ccc\n",
- "categories: [AP CSA]\n",
- "permalink: /csa/unit6-p1/\n",
- "menu: nav/CSA_Units/csa_unit6_p1.html\n",
- "author: (J)onathan, (I)an, (T)arun, (S)rijan\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## AP Computer Science A - Unit 6 Home Page\n",
- "\n",
- "Welcome to Unit 6! In this unit, we will explore various concepts of **Arrays** in Java, focusing on traversing and manipulating arrays.\n",
- "\n",
- "### Learning Goals:\n",
- "- Understand how to declare, initialize, and traverse arrays\n",
- "- Learn how to manipulate array elements\n",
- "- Practice writing algorithms that use arrays\n",
- "\n",
- "### Key Topics:\n",
- "Topic 6.1 - Array Creation and Access (Tarun)\n",
- "Topic 6.2 - Traversing Array (1D) (Srijan)\n",
- "Topic 6.3 Enhanced for loop for Arrays (Jonathan)\n",
- "Topic 6.4: Developing Algorithms Using Arrays (Ian)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# AP Computer Science A - Unit 6 Home Page\n",
- "\n",
- "Welcome to Unit 6! In this unit, we will explore various concepts of **Arrays** in Java, focusing on traversing and manipulating arrays.\n",
- "\n",
- "### Learning Goals:\n",
- "- Understand how to declare, initialize, and traverse arrays\n",
- "- Learn how to manipulate array elements\n",
- "- Practice writing algorithms that use arrays\n",
- "\n",
- "### Key Topics:\n",
- "- Topic 6.1 - Array Creation and Access (Tarun)\n",
- "- Topic 6.2 - Traversing Array (1D) (Srijan)\n",
- "- Topic 6.3 Enhanced for loop for Arrays (Jonathan)\n",
- "- Topic 6.4: Developing Algorithms Using Arrays (Ian)"
- ]
- }
- ],
- "metadata": {
- "kernelspec": {
- "display_name": "java (IJava/j!)",
- "language": "java",
- "name": "jbang-ijava"
- },
- "language_info": {
- "name": "java"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_06/Period1/2024-09-12-unit_6-1.ipynb b/_notebooks/CSA/units_1_to_10/unit_06/Period1/2024-09-12-unit_6-1.ipynb
deleted file mode 100644
index 6a95b978..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_06/Period1/2024-09-12-unit_6-1.ipynb
+++ /dev/null
@@ -1,479 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "title: Unit 6 - Arrays\n",
- "description: Unit 6 Team Teach - Arrays\n",
- "permalink: /csa/unit6-p1/unit6-1\n",
- "menu: nav/CSA_Units/csa_unit6_p1.html\n",
- "author: (J)onathan, (I)an, (T)arun, (S)rijan\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 6.1 Array Creation and Access\n",
- "\n",
- "#### MUST KNOW TERMS\n",
- "- Array: A data structure that holds a group of object references.\n",
- "- Element: A single item stored inside an array.\n",
- "- Element index: The location of an element in the array (in Java AND PYTHON(called a list) the first element is at index 0).\n",
- "- Array length: Number of elements in the Array\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Declaring Array\n",
- "To declare an array, you need the name of the array and the datatype.\n",
- "\n",
- "Syntax: dataType[] arrayName;\n",
- "\n",
- "\n",
- "(note in python that no need to declare which is called dynamic typing)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 5,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "int[] grades; // Declare an integer array\n",
- "String[] class_list; // Declare a string array\n",
- "boolean[] light_switch;"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Creating an Array\n",
- "\n",
- "Gives memory for the array but we need to specify its size for java compared to python(with arraylists in the next lesson you won't)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 1,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "\n",
- "// Syntax: arrayName = new dataType[size];\n",
- "int[]grades = new int[5]; // Create an integer array with 5 elements\n",
- "String[]class_list = new String[3]; // Create a string array with 3 elements\n",
- "boolean[]light_switch= new boolean[5];\n",
- "\n",
- "// Can also predefine the terms rather than setting to default value\n",
- "int[]grades={100,90,100,10,20};\n",
- "boolean[]light_switch={true,false,true,false,true};\n",
- "\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 1,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "numbers=list()\n",
- "names=list()\n",
- "light_switch=list()"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Printing out an Array"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 7,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "[100, 90, 100, 10, 20]\n"
- ]
- }
- ],
- "source": [
- "import java.util.Arrays;\n",
- "// Printing out the array with java method\n",
- "int[]grades={100,90,100,10,20};\n",
- "System.out.println(Arrays.toString(grades));"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Popcorn Hack 1(Time 0.5 minute)\n",
- "\n",
- "Create an array that represents numerous car brands(Audi, toyota,etc. )"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Array with custom Objects"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 8,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "[REPL.$JShell$26$Coder@5a4be8a2, REPL.$JShell$26$Coder@548c1d9b, REPL.$JShell$26$Coder@50b383d2, REPL.$JShell$26$Coder@15b117a0, REPL.$JShell$26$Coder@10baf34c]\n"
- ]
- }
- ],
- "source": [
- "class Coder{\n",
- " public boolean codecodecoder;\n",
- " public int age;\n",
- " Coder(boolean codecodecoder, int age){\n",
- " this.codecodecoder=codecodecoder;\n",
- " this.age=age;\n",
- " }\n",
- " \n",
- "}\n",
- "Coder[]allthecoders=new Coder[5];\n",
- "\n",
- "\n",
- "for(int i=0;ifalse\n",
- "System.out.println(\"After: \"+Arrays.toString(light_switch));\n",
- "\n",
- "// String array\n",
- "String[]student_names={\"Bob\", \"Sir Mort\",\" Sir Tarun\", \"Sensei Wu\"};\n",
- "System.out.println(\"Before: \"+Arrays.toString(student_names));\n",
- "student_names[0]=\"Sir Jonathon\";\n",
- "System.out.println(\"After: \"+Arrays.toString(student_names));\n",
- "\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 3,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Before [10, 20, 30, 40]\n",
- "After [10, 100, 30, 40]\n"
- ]
- }
- ],
- "source": [
- "\n",
- "# Python translation/example\n",
- "grades=[10,20,30,40]\n",
- "print(\"Before\",grades)\n",
- "\n",
- "grades[1]=100 # changing the secon d element to 100\n",
- "print(\"After\",grades)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Iterating Through an Array\n",
- "Loops through the array, printing each element."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 8,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Index 0: 10\n",
- "Index 1: 20\n",
- "Index 2: 30\n",
- "Index 3: 40\n",
- "Index 4: 50\n"
- ]
- }
- ],
- "source": [
- "int[] numbers = {10, 20, 30, 40, 50};\n",
- "for (int i = 0; i < numbers.length; i++) { // going from the first index(0) to the last index(length of array-1)\n",
- " System.out.println(\"Index \"+i+\": \"+numbers[i]);\n",
- "}"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Index 0 : 10\n",
- "Index 1 : 20\n",
- "Index 2 : 30\n",
- "Index 3 : 40\n"
- ]
- }
- ],
- "source": [
- "numbers=[10,20,30,40]\n",
- "for i in range(0,len(numbers)):\n",
- " print(\"Index\",i,\":\",numbers[i])"
- ]
- }
- ],
- "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": "17.0.12+7-Ubuntu-1ubuntu222.04"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_06/Period1/2024-09-12-unit_6-2.ipynb b/_notebooks/CSA/units_1_to_10/unit_06/Period1/2024-09-12-unit_6-2.ipynb
deleted file mode 100644
index cafce823..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_06/Period1/2024-09-12-unit_6-2.ipynb
+++ /dev/null
@@ -1,279 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "title: Unit 6.2 - Arrays\n",
- "description: Unit 6 Team Teach - Arrays\n",
- "comments: true\n",
- "permalink: /csa/unit6-p1/unit6-2\n",
- "menu: nav/CSA_Units/csa_unit6_p1.html\n",
- "author: (J)onathan, (I)an, (T)arun, (S)rijan\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Topic 6.2 - Traversing Array (1D)\n",
- "> Using iteration statements (standard for loops and while loops) to access each element in an array."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### The Classic For Loop\n",
- "- An array in java is indexed from n1 to the number of elements n2.\n",
- "\n",
- "#### Review on what a for loop is?\n",
- "- init: The init expression is used to initialize a variable (executed once)\n",
- "- condition: The loop executes the condition statement every iteration.\n",
- "- incr/decr: The increment/decrement statement applied to the variables which updates the initial expression.\n",
- "![forLoopExample](https://github.com/user-attachments/assets/b3805ce2-eaeb-427e-9eca-acb3fa2421fe)\n",
- "\n",
- "\n",
- "#### Here's some basic code (boring stuff): "
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 4,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "0\n",
- "0\n",
- "1\n",
- "2\n",
- "2\n",
- "2\n"
- ]
- }
- ],
- "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);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "![forLoopGif](https://github.com/user-attachments/assets/684186c5-1833-436c-9292-24075e6ba9d3)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## For Loop: Accessing List Elements\n",
- "\n",
- "**Popcorn hack question**\n",
- "\n",
- "Which part of the following code would I want to change if I wanted to access all odd indices of the list."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 2,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Even Index\n",
- "0\n",
- "2\n",
- "4\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",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Standard While Loop\n",
- "Does the following loop accomplish traversing the array?"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 4,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "New index: 5\n"
- ]
- }
- ],
- "source": [
- "int [] list = new int[5];\n",
- "int index = 0; \n",
- "\n",
- "while (index < list.length) \n",
- "{\n",
- " // Do something\n",
- " index ++; \n",
- "}\n",
- "\n",
- "System.out.println(\"New index: \" + index);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "**Popcorn hack question:**\n",
- "\n",
- "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?"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Bounds Errors\n",
- "\n",
- "\n",
- "\n",
- "When traversing an array, we need to be careful with the indices to avoid an ArrayIndexOutOfBoundsException being thrown.\n",
- "\n",
- "**ATTENTION: MOST COMMON MISTAKE: **\n",
- "8. What is wrong with the for loop and while loop below? Why does this produce an ArrayIndexOutOfBoundsException error? The first index is 0 making the equation invalid. You must change the signs or add a -1\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Off by One Error : missing the first or last element of an array when trying to traverse"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Developing Methods Using Arrays\n",
- "\n",
- "Reviewing common methods asked on AP Exams FRQs\n",
- "\n",
- "### Average Value\n",
- "\n",
- "**Popcorn Hack**:\n",
- "\n",
- "Create/complete the code in order to return the average grade of all grades in the list of grades.\n",
- "\n",
- "**Homework:**\n",
- "\n",
- " Have the code print \"Man, you guys need to study more\" if the grades are beneath a certain percentage. \n",
- " \n",
- " Bonus:\n",
- " Have the code iterate through the list and add some points to each grade because you're a very generous grader."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class GradeAverage {\n",
- " public static void main(String[] args) {\n",
- " /* grades out of 100 */\n",
- " int[] grades = {90, 50, 70, 20, 80, 97};\n",
- " int sum = 0;\n",
- " double average;\n",
- " \n",
- " for (int i = 0; i carMap = new HashMap();\n",
- "/*\n",
- " HashMap Syntax\n",
- " Map.Entry entry for iterable loops\n",
- " Refer to the iterated HashMap as carMap.entrySet()\n",
- " entry.getKey()\n",
- " entry.getValue()\n",
- "*/\n",
- "\n",
- "carMap.put(\"MortMobile\",9999);\n",
- "carMap.put(\"CSAwesomeCar\",500);\n",
- "carMap.put(\"ArrayceCar\",5000);\n",
- "\n",
- "for(int i=0;i carMap = new HashMap();\n",
- "\n",
- " carMap.put(\"MortMobile\",9999);\n",
- " carMap.put(\"CSAwesomeCar\",500);\n",
- " carMap.put(\"ArrayceCar\",5000);\n",
- " for(Map.Entry entry : carMap.entrySet())\n",
- " {\n",
- " System.out.println(entry.getKey());\n",
- " System.out.println(entry.getValue());\n",
- " }"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# Limitations On Enhanced For Loops\n",
- "\n",
- "It does not allow for access to the index number of the element,\n",
- "You cannot modify elements of the loop\n",
- "You cannot get a specific index in the same way array[ i ] can\n",
- "\n",
- "# Final Hack\n",
- "Finish the following code with a for each and normal for loop\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 16,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "int[] nums = {1,2,3,4,5,6,2000};\n",
- "\n",
- "//loop through the array and print if the current index is even"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 17,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "false\n",
- "true\n",
- "false\n",
- "true\n",
- "false\n",
- "true\n",
- "true\n",
- "false\n",
- "true\n",
- "false\n",
- "true\n",
- "false\n",
- "true\n",
- "true\n"
- ]
- }
- ],
- "source": [
- "//Sample Solution\n",
- "int[] nums = {1,2,3,4,5,6,2000};\n",
- "\n",
- "for(int i=0;i max) {\n",
- " max = value;\n",
- " }\n",
- " }\n",
- " return max;\n",
- "}\n",
- "\n",
- "/* run on array */\n",
- "double[] nums = {1,2,3,4,5,6,2000, 123.123, 1230912839018230.123901823};\n",
- "System.out.println(findMax(nums));"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Popcorn Hack\n",
- "Implement a function to find the minimum of the EVEN INDEXED elements in array of integers. "
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "private double findMinEven(int [] values) {\n",
- " /*Function here */\n",
- "}\n",
- "\n",
- "int[] nums = {};\n",
- "System.out.println(findMinEven(nums));"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Ok wait but i don't want to copy this every time. what happened to python's .max?"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "double[] nums = {1,2,3,4,5,6,2000};\n",
- "System.out.println(Arrays.stream(nums).max().getAsDouble())\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Shifting Arrays\n",
- "Oftentimes we need to shift an array. \n",
- "ex. Shifting an array right two:\n",
- "Original: {\"a\", \"b\", \"c\", \"d\"}\n",
- "Final: {\"d\", \"c\", \"a\", \"b\"}\n",
- "\n",
- "How do we do this?\n",
- "1. Create a new array\n",
- "2. Iterate through each element in the array\n",
- "3. Place in appropriate spoce"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 40,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "3\n",
- "4\n",
- "5\n",
- "6\n",
- "7\n",
- "8\n",
- "9\n",
- "10\n",
- "1\n",
- "2\n"
- ]
- }
- ],
- "source": [
- "int [] numbers = {1,2,3,4,5,6,7,8,9,10};\n",
- "\n",
- "int shift = 8;\n",
- "\n",
- "/* function */\n",
- "private int [] shiftRight(int [] values, int shift) {\n",
- " /* declare new array */\n",
- " int [] shifted = new int [values.length];\n",
- " /* iterate through each array */\n",
- " for (int index = 0; index < values.length; index++) {\n",
- " /*\n",
- " Breakdown:\n",
- " shifted [new index] = numbers[index] (old value)\n",
- "\n",
- " WAIT! but i'm adding a value to somewhere in the middle of the array! \n",
- " we couldn't do that in python but since we specified the type and length of the array, this is possible in java\n",
- "\n",
- " Calculating the new index:\n",
- " 1. we add the shift to the index\n",
- " 2. handle overflow: we use % to take the modulo operation\n",
- " */\n",
- " shifted [Math.abs((index + shift) % numbers.length)] = numbers[index];\n",
- " }\n",
- " return shifted;\n",
- "}\n",
- "\n",
- "for ( int value : shiftRight(numbers, shift)) {\n",
- " System.out.println(value);\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Challenge Hack:\n",
- "Create a function that iterates through every X items and shifts *only* those elements Y shift left.\n",
- "\n",
- "Example: ({1, 2, 3, 4, 5, 6}, Y = 1, X = 2)\n",
- "Output: {5, 2, 1, 4, 3, 6}\n",
- "\n",
- "Example: ({1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, Y = 2, X = 3)\n",
- "Output: {10, 2, 3, 1, 5, 6, 4, 8, 9, 7}"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "int [] numbers = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};\n",
- "\n",
- "int shift = 2;\n",
- "int space = 4;\n",
- "\n",
- "/* function */\n",
- "private int [] shiftRight(int [] values, int shift, int space) {\n",
- " /* code here */\n",
- "}\n",
- "\n",
- "for ( int value : shiftRight(numbers, shift, space)) {\n",
- " System.out.println(value);\n",
- "}"
- ]
- }
- ],
- "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": "17.0.12+7-Ubuntu-1ubuntu222.04"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_06/Period3/2024-09-12-Unit-6-0-Home-Page.ipynb b/_notebooks/CSA/units_1_to_10/unit_06/Period3/2024-09-12-Unit-6-0-Home-Page.ipynb
deleted file mode 100644
index e0232056..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_06/Period3/2024-09-12-Unit-6-0-Home-Page.ipynb
+++ /dev/null
@@ -1,56 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "toc: True\n",
- "title: Unit 6 Arrays P3\n",
- "courses: {'csa': {'week': 4}}\n",
- "type: ccc\n",
- "categories: [AP CSA]\n",
- "permalink: /csa/unit6_p3\n",
- "menu: nav/CSA_Units/csa_unit6_p3.html\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## AP Computer Science A - Unit 6 Home Page\n",
- "\n",
- "Welcome to Unit 6! In this unit, we will explore various concepts of **Arrays** in Java, focusing on traversing and manipulating arrays.\n",
- "\n",
- "### Learning Goals:\n",
- "- Understand how to declare, initialize, and traverse arrays\n",
- "- Learn how to manipulate array elements\n",
- "- Practice writing algorithms that use arrays\n",
- "\n",
- "### Key Topics:\n",
- "1. Introduction to Arrays\n",
- "2. Traversing Arrays\n",
- "3. Array Algorithms\n",
- "4. Searching and Sorting Arrays"
- ]
- }
- ],
- "metadata": {
- "kernelspec": {
- "display_name": "java (IJava/j!)",
- "language": "java",
- "name": "jbang-ijava"
- },
- "language_info": {
- "name": "java"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_06/Period3/2024-09-13-Unit-6.1-Lesson.ipynb b/_notebooks/CSA/units_1_to_10/unit_06/Period3/2024-09-13-Unit-6.1-Lesson.ipynb
deleted file mode 100644
index 7c20315f..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_06/Period3/2024-09-13-Unit-6.1-Lesson.ipynb
+++ /dev/null
@@ -1,464 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "title: Unit 6.1 Lesson\n",
- "type: collab \n",
- "toc: true\n",
- "permalink: /csa/unit6_p3/6.1/\n",
- "menu: nav/CSA_Units/csa_unit6_p3.html\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# 6.1: Array Creation and Access"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# Intro to Arrays"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "#### What are arrays?"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "They are data structures used to implement a collection of primitive or object reference data. An array in Java is basically like a list in python, but they are only allowed to store values of one data type."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "Each value in the array is called an \"element\""
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "The position of an element in the array is called an \"index\".\n",
- "Just like in Python, the first element of an array always has an index of zero."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "The `length` of an array is how many elements there are in the array."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "`length` has the dataype `public final`\n",
- "- we can access the length in any class since it's `public`\n",
- "- also, we can't change the array's length after it's been created since the length is `final`"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- " "
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "source": [
- "#### Example"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 10,
- "metadata": {},
- "outputs": [],
- "source": [
- "int [] array1 = new int[5]"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "The above code cell defines the array with:\n",
- "- the name `array1`\n",
- "- the datatype `int` (means that only integer values can go in the array)\n",
- "- the number of elements in the array is five, as shown by `int[5]`\n",
- "- all the 5 elements in the array have a value of zero, because the elements weren't specified"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Question: How would you find the index of the last element of the array, if you didn't know how many elements there were in the array?"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "##### You guys answer!!"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Remember, unlike python, negative indexing does not work in Java and it will result in an error !!!\n",
- "Uncomment the code and see for yourself!"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 12,
- "metadata": {},
- "outputs": [],
- "source": [
- "// int [] array2 = {1,2,3,4,5};\n",
- "// System.out.println(array2[-1]);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "source": [
- "### Primitive Elements"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Now, let's go back to array1 and modify some stuff."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "System.out.println(array1[4]); // 5th element of the array"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "As you can see, it returns zero because when we defined the array, we used `new`, which made all the elements have the value of zero. Now, let's change it."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "array1[4] = 30;\n",
- "System.out.println(array1[4]);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "source": [
- "We successfully changed the fifth element from zero to thirty."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Putting the name of the array in the print statement in Java outputs the memory reference of the array and not the elements of the array.\n",
- "Below is a great way to print out the array."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "System.out.println(array1)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "System.out.println(Arrays.toString(array1));"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Popcorn Hack (do this on separate cells)\n",
- "- Create an array called \"city_array\" with the elements \"San Diego\", \"Los Angeles\", \"San Francisco\", \"Sacramento\"\n",
- "- Print out the first element in the array\n",
- "- Print out the third element in the array\n",
- "- Change the second element in the array to \"Sacramento\"\n",
- "- Change the fourth element in the array to \"San Jose\"\n",
- "- Print out the length of the array"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Mutable Elements"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 17,
- "metadata": {},
- "outputs": [],
- "source": [
- "public class Mutable{\n",
- " private int value;\n",
- " public Mutable(int start) {\n",
- " value = start;\n",
- " }\n",
- " public void incrementValue() {\n",
- " value++;\n",
- " }\n",
- " public int getValue() {\n",
- " return value;\n",
- " }\n",
- "}"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "Mutable[] array3; //initialize array of mutable objects\n",
- "array3 = new Mutable[3]; //set size of array3 equal to three\n",
- "array3[1] = new Mutable(33); //assigning the number 33 to the second element\n",
- "array3[0] = new Mutable(array3[1].getValue() - 3); //assigning the second element's value minus three to the first element aka the number 30\n",
- "for (Mutable m : array3) { //printing out the values of the array using for loop\n",
- " if (m != null) {\n",
- " System.out.println(m.getValue());\n",
- " } else {\n",
- " System.out.println(\"null\");\n",
- " }\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "**Important**: When the array is initialized (you're not providing any values to it):\n",
- "- int elements are set to `0`\n",
- "- reference type elements are set to `null`\n",
- "- double elements are set to `0.0`\n",
- "- boolean elements are set to `false`"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Popcorn Hack:\n",
- "Create four new INITIALIZED arrays, with int, string, double, and boolean types respectively. Print out the second element of each array to see the default values."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# Practice MCQs"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Question 1\n",
- "Consider the following method which is intended to return the position of `find` within the String referenced at the third last index of `arr`.\n",
- " \n",
- " \n",
- "`public static int findThirdLast(String [] arr, String find)`\n",
- " \n",
- "`{`\n",
- " \n",
- "`return /*missing code*/;`\n",
- " \n",
- "`}`\n",
- " \n",
- " \n",
- "Which of the following could replace `/*missing code*/` to complete the method as specified?\n",
- " \n",
- "A. `arr[].indexOf(find)`\n",
- " \n",
- "B. `arr.indexOf(find)`\n",
- " \n",
- "C. `arr[arr.length].indexOf(find)`\n",
- " \n",
- "D. `arr[arr.length - 3].indexOf(find)`\n",
- " \n",
- "E. `arr[arr.length - 2].indexOf(find)`"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "#### Here's an image for your reference, in case you want to visualize it.\n",
- " "
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 17,
- "metadata": {},
- "outputs": [],
- "source": [
- "public static int findThirdLast(String [] arrtest, String find)\n",
- "{\n",
- " return arrtest[arrtest.length-3].indexOf(find);\n",
- "}"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "String [] testArray = {\"cat\", \"dog\", \"horse\", \"monkey\", \"snake\", \"elephant\"};\n",
- "int result = findThirdLast(testArray, \"on\");\n",
- "System.out.println(result);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Question 2\n",
- "Consider the following method:\n",
- " \n",
- " \n",
- "`public static int mystery(int [] arr)`\n",
- " \n",
- "`{`\n",
- " \n",
- "`return arr[1] + arr[4]/2`\n",
- " \n",
- "`}`\n",
- " \n",
- " \n",
- "The `mystery` method is called from another method in the same class:\n",
- "`int[] list = {1,9,2,5,6};`\n",
- " \n",
- "`int result = mystery(list);`\n",
- " \n",
- " \n",
- "What is stored in result after executing the above code?\n",
- " \n",
- " \n",
- "A. 2\n",
- " \n",
- "B. 12\n",
- " \n",
- "C. 15\n",
- " \n",
- "D. 9\n",
- " \n",
- "E. 8"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "public static int mystery(int [] myarr)\n",
- "{\n",
- " return myarr[1] + myarr[4]/2;\n",
- "}\n",
- "int[] list = {1,9,2,5,6};\n",
- "int result = mystery(list);\n",
- "System.out.println(result);"
- ]
- }
- ],
- "metadata": {
- "kernelspec": {
- "display_name": "java (IJava/j!)",
- "language": "java",
- "name": "jbang-ijava"
- },
- "language_info": {
- "codemirror_mode": "java",
- "file_extension": ".jshell",
- "mimetype": "text/x-java-source",
- "name": "java",
- "pygments_lexer": "java",
- "version": "17.0.12+7-Ubuntu-1ubuntu224.04"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_06/Period3/2024-09-13-Unit-6.2-Lesson.ipynb b/_notebooks/CSA/units_1_to_10/unit_06/Period3/2024-09-13-Unit-6.2-Lesson.ipynb
deleted file mode 100644
index 65439d8c..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_06/Period3/2024-09-13-Unit-6.2-Lesson.ipynb
+++ /dev/null
@@ -1,492 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "title: Unit 6.2 Lesson\n",
- "type: collab \n",
- "toc: true\n",
- "menu: nav/CSA_Units/csa_unit6_p3.html\n",
- "permalink: /csa/unit6_p3/6.2/\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# 6.2 Traversing Arrays\n",
- "Using iterative statements (such as standard for loops and while loops) to traverse each element in an array.\n",
- " \n",
- "\n",
- "## Traversing using a `for` loop\n",
- "\n",
- "- **Traversing** an array means to access each element of an array.\n",
- " - Since an array is indexed from 0 to the number of elements -1, a standard for loop is a convenient way to accomplish traversal of an array.\n",
- "\n",
- "The `for` loop is used to iterate over a sequence of elements. The syntax of the `for` loop is as follows:\n",
- " \n",
- "```java\n",
- "for (initialization; condition; increment/decrement) {\n",
- " // code to be executed\n",
- "}\n",
- "```\n",
- "\n",
- "![forloopimage](https://www.w3resource.com/w3r_images/java-for-loop-image1.png)\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "public static void main(String[] args) { \n",
- " int[] list = new int[5];\n",
- " for (int index =0; index < list.length; index++) {\n",
- " list[index] = (int) (Math.random() * 100);\n",
- " }\n",
- " System.out.println(Arrays.toString(list));\n",
- "}\n",
- "main(null);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### What does the code above do?\n",
- "\n",
- "- A for loop can also be used to access only some of the elements in an array"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "public static void main(String[] args) { \n",
- " int[] list = new int[5];\n",
- " for (int index =0; index < list.length; index+=2) {\n",
- " list[index] = (int) (Math.random() * 100);\n",
- " }\n",
- " System.out.println(Arrays.toString(list));\n",
- "}\n",
- "main(null);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "source": [
- "### What is the difference of between this code and the previous code? What do you think the output will look like?\n",
- "\n",
- "## For loop : Accessing Some Elements of a List\n",
- "- The for loop can be used to access only some of the elements in an array.\n",
- "\n",
- "### Odd Index only"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "public class oddIndexOnly {\n",
- " public static void main(String[] args) {\n",
- " int[] listOfNumbers = new int[] {1, 2, 3, 4, 5};\n",
- " for (int index=0; index\n",
- "\n",
- "- The for-each loop doesn't have direct access to the index of the array elements, so it’s not possible to easily skip elements based on their index, like odd or even indices\n",
- "- Solution: Use a separate variable to keep track of the index\n",
- "\n",
- "```java\n",
- "int[] array = {1, 2, 3, 4, 5, 6, 7};\n",
- "int index = 0;\n",
- "\n",
- "for (int num : array) {\n",
- " if (index % 2 != 0) { // Check if index is odd\n",
- " System.out.println(num);\n",
- " }\n",
- " index++;\n",
- "}\n",
- "```"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Popcorn Hack 2\n",
- "\n",
- "Write a method that traverses an integer array and counts how many times a specific number appears. Make sure to use a **for-each loop**."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "public static int countOccurrences(int[] arr, int target) {\n",
- " /*\n",
- " * This function takes an array of integers and a target integer as input and returns the number of times the target integer appears in the array.\n",
- " */\n",
- "}\n",
- "\n",
- "// Example usage:\n",
- "int[] arr = {3, 5, 3, 3, 7, 5};\n",
- "int target = 3;\n",
- "System.out.println(countOccurrences(arr, target)); // Output: 3"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Traversing with a `while` loop\n",
- "- The `while` loop is used to iterate over a block of code as long as the condition is true.\n",
- "- The syntax of the `while` loop is as follows:\n",
- "\n",
- "```java\n",
- "while (condition) {\n",
- " // code to be executed\n",
- "}\n",
- "```\n",
- "\n",
- "### Example of while loop"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "public static void main(String[] args) { \n",
- " int[] arr = new int[5];\n",
- " int position = 0;\n",
- " while (position < arr.length) {\n",
- " arr[position] = (int) (Math.random() * 100);\n",
- " position ++;\n",
- " }\n",
- " System.out.println(Arrays.toString(arr));\n",
- "}\n",
- "main(null);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Does the while loop accomplish **traversing** the array? \n",
- "Remember that traversing means to access each element of an array.\n",
- "\n",
- "### Both the while loop and the for loop perform the same task. The key difference is that after the while loop finishes, the variable index will still exist.\n",
- "\n",
- "## Popcorn Hack 3\n",
- "\n",
- "Write a method that traverses an array of integers and returns the index of the first negative number. If there are no negative numbers, return -1. Use a **while loop.**"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "public static int firstNegativeIndex(int[] arr) {\n",
- " /*\n",
- " * This function takes an array of integers as input and returns the index of the first negative number in the array. \n",
- " * If there are no negative numbers in the array, the function should return -1.\n",
- " */\n",
- "}\n",
- "\n",
- "// Example usage:\n",
- "int[] arr = {4, 7, -2, 5};\n",
- "System.out.println(firstNegativeIndex(arr)); // Output: 2"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Bound Errors\n",
- "- When using loops to access array elements, we need to be careful with the condition in order to avoid an `ArrayIndexOutOfBoundsException` being thrown.\n",
- "\n",
- "```java\n",
- "int[] list = new int[5];\n",
- "for (int index =0; index <= list.length; index++) {\n",
- " list[index] = (int) (Math.random() * 10);\n",
- "}\n",
- "```\n",
- "Or\n",
- "```java\n",
- "int[] arr = new int[5];\n",
- "int position = 0;\n",
- "while (position <= arr.length) {\n",
- " arr[position] = (int) (Math.random() * 10);\n",
- " position ++;\n",
- "}\n",
- "```\n",
- "Here, the condition in the for loop is `index <= list.length` or `position <= arr.length`, which will cause an `ArrayIndexOutOfBoundsException` because the index is out of bounds when it is equal to the length of the array.\n",
- "\n",
- "When using loops to access array elements, we also need to be sure we include all of the elements desired. It is easy to miss the first or last element, which is considered an \"off by one\" error.\n",
- "\n",
- "```java\n",
- "int[] list = new int[5];\n",
- "for (int index =0; index < list.length-1; index++) {\n",
- " list[index] = (int) (Math.random() * 10);\n",
- "}\n",
- "```\n",
- "Or\n",
- "```java\n",
- "int[] arr = new int[5];\n",
- "int position = 1;\n",
- "while (position < arr.length) {\n",
- " arr[position] = (int) (Math.random() * 10);\n",
- " position ++;\n",
- "}\n",
- "```\n",
- "What do you think is wrong with both of these loops?\n",
- "\n",
- "## Multiple Choice Question\n",
- "\n",
- "Consider the following code:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "String[] list = {\"red\", \"yellow\", \"blue\"};\n",
- "for (int i = 0; i < list.length; i++) {\n",
- " System.out.print(list[i].length() + \"_\");\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "What is displayed after the code is executed?\n",
- "\n",
- "A. `red_yellow_blue`\n",
- "\n",
- "B. `3_3_3_`\n",
- "\n",
- "C. `3_6_4_`\n",
- "\n",
- "D. `3_3_`\n",
- "\n",
- "E. `3_6_`\n",
- "\n",
- " \n",
- "Consider the following code segment which is intended to display every other element in `numbers`, beginning with the first element:\n",
- "\n",
- "```java\n",
- "int[] numbers = {13, 33, 3, -3, -333};\n",
- "for (/*missing*/) {\n",
- " System.out.print(numbers[i]);\n",
- "}\n",
- "```\n",
- "\n",
- "Which of the following could replace `/*missing code*/` to make the code work as intended?\n",
- "\n",
- "(A) `int i = 0; i < numbers. length 12; it+`\n",
- "\n",
- "(B) `int i = 1; i ‹ numbers. length; i++`\n",
- "\n",
- "(C) `int i = 1; i < numbers.length; i+=2`\n",
- "\n",
- "(D) `int i = 0; i ‹ numbers.length; i++`\n",
- "\n",
- "(E) `int i = 0; i < numbers.length; i+=2`\n",
- "\n",
- " \n",
- "Consider the method which is intended to reverse the order of the elements in `arr`.\n",
- "\n",
- "```java\n",
- "public static void reverseArray (double [] arr) {\n",
- " for (int i = 0; i < arr.length; i++) {\n",
- " double temp = arr [i];\n",
- " arr[i] = arr[arr.length-1-i];\n",
- " arr[arr.length-1-i] = temp;\n",
- " }\n",
- "}\n",
- "```\n",
- "\n",
- "Which of the following would fix the method so it works as intended?\n",
- "\n",
- "(A) Change the loop condition to: \n",
- "\n",
- "```java\n",
- "i < arr. length - 1\n",
- "```\n",
- "\n",
- "(B) Change the loop condition to: \n",
- "\n",
- "```java\n",
- "i < arr.length/2\n",
- "```\n",
- "\n",
- "(C) Change the loop condition to: \n",
- "\n",
- "```java\n",
- "i < arr.length/2 - 1\n",
- "```\n",
- "\n",
- "(D) Change lines 6 and 7 to:\n",
- "\n",
- "```java\n",
- "arr[1] = arr[arr.length-1];\n",
- "\n",
- "arr [arr.length-i] = temp;\n",
- "```\n",
- "\n",
- "(E) Change the loop body to:\n",
- "\n",
- "```java\n",
- "arr[1] = arr[arr.length-1-1];\n",
- "\n",
- "arr [arr.length-1-1] = arr[i];\n",
- "```"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# Homework Hack\n",
- "\n",
- "**Problem Statement:** Given an array of integers, write a method to find the second largest unique element in the array. If the array has fewer than two distinct elements, return -1.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "public static int findSecondLargest(int[] arr) {\n",
- " /*\n",
- " * This function takes an array of integers as input and returns the second largest unique element in the array. \n",
- " * If the array has less than 2 elements, the function should return -1.\n",
- " */\n",
- "}\n",
- "\n",
- "// Example usage:\n",
- "public static void main(String[] args) {\n",
- " int[] arr1 = {3, 1, 4, 1, 5, 9, 2, 6};\n",
- " System.out.println(findSecondLargest(arr1)); // Output: 6\n",
- "\n",
- " int[] arr2 = {10, 10, 10, 10};\n",
- " System.out.println(findSecondLargest(arr2)); // Output: -1\n",
- "}"
- ]
- }
- ],
- "metadata": {
- "kernelspec": {
- "display_name": "java (IJava/j!)",
- "language": "java",
- "name": "jbang-ijava"
- },
- "language_info": {
- "codemirror_mode": "java",
- "file_extension": ".jshell",
- "mimetype": "text/x-java-source",
- "name": "java",
- "pygments_lexer": "java",
- "version": "17.0.11+7-LTS-207"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_06/Period3/2024-09-16-Unit-6.3-Lesson.ipynb b/_notebooks/CSA/units_1_to_10/unit_06/Period3/2024-09-16-Unit-6.3-Lesson.ipynb
deleted file mode 100644
index f996302c..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_06/Period3/2024-09-16-Unit-6.3-Lesson.ipynb
+++ /dev/null
@@ -1,206 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "title: Unit 6.3 Lesson\n",
- "type: collab \n",
- "toc: true\n",
- "menu: nav/CSA_Units/csa_unit6_p3.html\n",
- "permalink: /csa/unit6_p3/6.3/\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "> # Enhanced For Loop (For-each)\n",
- "\n",
- "An enhanced For Loop is a simplified version of a regular for loop, where the coder doesn't need to specify the increment and can access each element directly.\n",
- "\n",
- "### Pros\n",
- " - Can access the elements of a array instad of a counter\n",
- " - Enhanced readability\n",
- " - Less likely to be buggy\n",
- "\n",
- "### Cons\n",
- " - Can only traverse the array in order\n",
- " - Accesses a copy of the array, so modifications to the variables are not saved in the original array"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Regular For Loop\n",
- "![Regular For Loop](https://media.geeksforgeeks.org/wp-content/uploads/20231221155254/cpp-for-loop.png)\n",
- "\n",
- "## Enhanced For Loop\n",
- "![Enhanced For Loop](https://swcarpentry.github.io/python-novice-inflammation/fig/05-loops_image_num.png)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "int[] numbers = {10, 20, 30, 40, 50};\n",
- "for (int number : numbers) {\n",
- " number += 1;\n",
- " System.out.println(number);\n",
- "};\n",
- "\n",
- "System.out.println(Arrays.toString(numbers))"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Comparing a regular for loop with the enhanced for loop\n",
- "\n",
- "Popcorn Hack: Rewrite this code to use an enhanced for loop instead. make comments explaining what you added/changed"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "String[] languages = {\"Java\", \"Python\", \"Markdown\", \"C++\", \"Go\", \"JavaScript\", \"HTML\"};\n",
- "\n",
- "for (int i = 0; i max) {\n",
- " max = array[i]; \n",
- " }\n",
- " if (array[i] < min) {\n",
- " min = array[i]; \n",
- " }\n",
- " }\n",
- "\n",
- " System.out.println(\"Maximum value: \" + max);\n",
- " System.out.println(\"Minimum value: \" + min);\n",
- " }\n",
- "\n",
- " public static void main(String[] args) {\n",
- " \n",
- " int[] array = {3, 5, 7, 2, 8, -1, 4, 10, 12};\n",
- "\n",
- " \n",
- " findMaxAndMin(array);\n",
- " }\n",
- "}\n",
- "MaxMinInArray.main(null)\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Popcorn Hack: If an integer in the array is greater than the integer below it, print \"Increase\""
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 9,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Maximum value: 12\n",
- "Minimum value: -1\n"
- ]
- }
- ],
- "source": [
- "public class MaxMinInArray {\n",
- "\n",
- " public static void findMaxAndMin(int[] array) {\n",
- " \n",
- " if (array == null || array.length == 0) {\n",
- " System.out.println(\"Array is empty\");\n",
- " return;\n",
- " }\n",
- "\n",
- " int max = array[0];\n",
- " int min = array[0];\n",
- "\n",
- " \n",
- " for (int i = 1; i < array.length; i++) {\n",
- " // Add code here\n",
- " if (array[i] > max) {\n",
- " max = array[i]; \n",
- " }\n",
- " if (array[i] < min) {\n",
- " min = array[i]; \n",
- " }\n",
- " }\n",
- "\n",
- " System.out.println(\"Maximum value: \" + max);\n",
- " System.out.println(\"Minimum value: \" + min);\n",
- " }\n",
- "\n",
- " public static void main(String[] args) {\n",
- " \n",
- " int[] array = {3, 5, 7, 2, 8, -1, 4, 0, 12};\n",
- "\n",
- " \n",
- " findMaxAndMin(array);\n",
- " }\n",
- "}\n",
- "MaxMinInArray.main(null)\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "![Visualization](https://www.w3resource.com/w3r_images/java-basic-image-exercise-106.png)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 11,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "gamma delta alpha beta "
- ]
- }
- ],
- "source": [
- "public class WordShifter { \n",
- " public static void main(String[] args) {\n",
- " String[] words = {\"alpha\", \"beta\", \"gamma\", \"delta\"};\n",
- " int shiftWord = 2;\n",
- " for (int count = 0; count < shiftWord; count++) {\n",
- " String temp = words[0];\n",
- " for (int index = 0; index < words.length - 1; index++) {\n",
- " words[index] = words[index + 1];\n",
- " }\n",
- " words[words.length - 1] = temp;\n",
- " }\n",
- " for (String word : words) {\n",
- " System.out.print(word + \" \");\n",
- " }\n",
- " }\n",
- "}\n",
- "WordShifter.main(null)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### HW Hack: Go through the array in reverse order and output each object"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 14,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "Integer[] myArray = {0, 1, 2, 3, 4, 5};\n",
- "\n",
- "for (int i=1; count < myArray.length; i++) {\n",
- " //Add code here\n",
- "};"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### HW Hack: Print words while skipping every other word (\"Alpha\", \"Gamma\", \"Beta\", \"Delta\")"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class WordShifter { \n",
- " public static void main(String[] args) {\n",
- " String[] words = {\"alpha\", \"beta\", \"gamma\", \"delta\"};\n",
- " int shiftWord = 2;\n",
- " for (int count = 0; count < shiftWord; count++) {\n",
- " String temp = words[0];\n",
- " for (int index = 0; index < words.length - 1; index++) {\n",
- " words[index] = words[index + 1];\n",
- " }\n",
- " words[words.length - 1] = temp;\n",
- " }\n",
- " for (String word : words) {\n",
- " System.out.print(word + \" \");\n",
- " }\n",
- " }\n",
- "}\n",
- "WordShifter.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": "17.0.12+7-Ubuntu-1ubuntu222.04"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_07/Period1/2024-09-19-unit_7_p1-7.3.ipynb b/_notebooks/CSA/units_1_to_10/unit_07/Period1/2024-09-19-unit_7_p1-7.3.ipynb
deleted file mode 100644
index 31c26353..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_07/Period1/2024-09-19-unit_7_p1-7.3.ipynb
+++ /dev/null
@@ -1,309 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "toc: true\n",
- "title: 7.3 - Traversing Arraylists\n",
- "description: ArrayLists Lesson\n",
- "authors: Aidan Lau, Saathvik Gampa, Sri Surapaneni, Tanav Kambhampati\n",
- "categories: [AP CSA]\n",
- "type: ccc\n",
- "permalink: /csa/unit7-p1/unit7-3\n",
- "menu: nav/CSA_Units/csa_unit7_p1.html\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# 7.3 Traversing Arraylists\n",
- "\n",
- "You can traverse through the elements in an ArrayList using loops. In order to traverse ArrayLists, we can use iterative statements, or loops. We can use **For Each Loops**, **For Loops**, and **While Loops**\n",
- "\n",
- "The following code uses a **For Each** loop to traverse through the ArrayList."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 1,
- "metadata": {
- "vscode": {
- "languageId": "plaintext"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "50\n",
- "30\n",
- "20\n"
- ]
- }
- ],
- "source": [
- "//7.3.1: For Each Loop\n",
- "ArrayList myList = new ArrayList();\n",
- " myList.add(50);\n",
- " myList.add(30);\n",
- " myList.add(20);\n",
- " for (Integer value : myList)\n",
- " {\n",
- " System.out.println(value);\n",
- " }"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Popcorn Hack #1:\n",
- "\n",
- "Modify the code above so that it prints out the sum of all the elements in the list. "
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "plaintext"
- }
- },
- "outputs": [],
- "source": []
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "The problem with For Each loops is that you can't modify the ArrayList. To do that, you will need to use another type of loop. If you attempt to modify the ArrayList, you will get a **ConcurrentModificationException** error.\n",
- "\n",
- "## ConcurrentModificationException Error:\n",
- "- Happens when you try to modify the structure of an ArrayList using a For Each loop.\n",
- "\n",
- "Think about it this way:\n",
- "Imagine you are standing in a line at the store and then somebody cuts the line. The order of the line has changed. \n",
- "The store doesn't want people cutting the line becaues it changes the order and creates confusion. So, it throws out a ConcurrentModificationError to alert you that something is wrong and that you shouldn't do it. \n",
- "\n",
- "It's the same for For Each Loops in Java - You can't add or remove elements because it changes the structure of the loop. \n",
- "\n",
- "![image](https://github.com/user-attachments/assets/27a0d094-f4bf-47af-b047-bef393f05627)\n",
- "\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "#### Common mistakes with For Each Loops:\n",
- "1. Make sure that the data type of your variable is the same as the data type of the ArrayList\n",
- "2. Don't try to modify the ArrayList!!!!!! I can't stress this enough\n",
- "\n",
- "![image](https://github.com/user-attachments/assets/c6c2c194-ea02-48f6-acb8-efdf4aeb180b)\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### For Loops\n",
- "Here's how to traverse through an arraylist using a **For Loop**. The following code will give you an **IndexOutOfBounds** error, do you know how to fix this error?\n",
- "\n",
- "There are three major parts of a for loop:\n",
- "- Initialisation, this is where you declare the variable index\n",
- "\n",
- "- Boolean condition, this is where you declare the stop condition, when it's true, it stops.\n",
- "\n",
- "- Update, this is the increment value, i++ is increment and i-- is decrement"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 8,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "50\n",
- "30\n",
- "20\n"
- ]
- },
- {
- "ename": "EvalException",
- "evalue": "Index 3 out of bounds for length 3",
- "output_type": "error",
- "traceback": [
- "\u001b[1m\u001b[31m---------------------------------------------------------------------------\u001b[0m",
- "\u001b[1m\u001b[31mjava.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 3\u001b[0m",
- "\u001b[1m\u001b[31m\tat java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)\u001b[0m",
- "\u001b[1m\u001b[31m\tat java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)\u001b[0m",
- "\u001b[1m\u001b[31m\tat java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:266)\u001b[0m",
- "\u001b[1m\u001b[31m\tat java.base/java.util.Objects.checkIndex(Objects.java:361)\u001b[0m",
- "\u001b[1m\u001b[31m\tat java.base/java.util.ArrayList.get(ArrayList.java:427)\u001b[0m",
- "\u001b[1m\u001b[31m\tat .(#46:1)\u001b[0m"
- ]
- }
- ],
- "source": [
- "// 7.3.2 For Loops\n",
- "ArrayList myList = new ArrayList();\n",
- " myList.add(50);\n",
- " myList.add(30);\n",
- " myList.add(20);\n",
- " for (int i = 0; i <= myList.size(); i++) \n",
- " {\n",
- " System.out.println(myList.get(i));\n",
- " }\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## IndexOutOfBoundsException\n",
- "\n",
- "- This happens when the program is trying to fetch something that isn't there. If we have the equals since in the for loop, it will try to fetch up to index 3 because thats the list size. When we remove the equals sign, it goes to whatever is <3, which is 2. So, it fetches up to index 2, meaning 3 elements. "
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "#### Popcorn Hack 2:\n",
- "Suppose we have an arraylist named grades, and we want to remove the entries that are lower than 70. Use a for loop to achieve this.\n",
- "\n",
- "![image](https://github.com/user-attachments/assets/6964847e-0eec-4275-9d47-1d06136466b4)\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 3,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [
- {
- "ename": "CompilationException",
- "evalue": "",
- "output_type": "error",
- "traceback": [
- "\u001b[1m\u001b[30m| \u001b[1m\u001b[30m for(int i = 0; i<=\u001b[0m\u001b[1m\u001b[30m\u001b[41m\u001b[0m\u001b[1m\u001b[30m; i++){\u001b[0m",
- "\u001b[1m\u001b[31millegal start of expression\u001b[0m",
- "",
- "\u001b[1m\u001b[30m| \u001b[1m\u001b[30m \u001b[0m\u001b[1m\u001b[30m\u001b[41m\u001b[0m\u001b[1m\u001b[30m???\u001b[0m",
- "\u001b[1m\u001b[31millegal start of expression\u001b[0m",
- "",
- "\u001b[1m\u001b[30m| \u001b[1m\u001b[30m ?\u001b[0m\u001b[1m\u001b[30m\u001b[41m\u001b[0m\u001b[1m\u001b[30m??\u001b[0m",
- "\u001b[1m\u001b[31millegal start of expression\u001b[0m",
- "",
- "\u001b[1m\u001b[30m| \u001b[1m\u001b[30m ??\u001b[0m\u001b[1m\u001b[30m\u001b[41m\u001b[0m\u001b[1m\u001b[30m?\u001b[0m",
- "\u001b[1m\u001b[31millegal start of expression\u001b[0m",
- "",
- "\u001b[1m\u001b[30m| \u001b[1m\u001b[30m \u001b[0m\u001b[1m\u001b[30m\u001b[41m\u001b[0m\u001b[1m\u001b[30m}\u001b[0m",
- "\u001b[1m\u001b[31millegal start of expression\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(int i = 0; i<=; i++){\n",
- " if(grades.get(i)<70){\n",
- " //remember, use grades.remove(index) \n",
- " ???\n",
- " }\n",
- " }\n",
- " System.out.println(grades);\n",
- " }\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# While Loops\n",
- "\n",
- "Here is the final example of traversing through ArrayLists using while loops"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 4,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "apple\n",
- "banana\n",
- "orange\n"
- ]
- }
- ],
- "source": [
- "ArrayList fruits = new ArrayList<>();\n",
- "fruits.add(\"apple\");\n",
- "fruits.add(\"banana\");\n",
- "fruits.add(\"orange\");\n",
- "\n",
- "int index = 0;\n",
- "while (index < fruits.size()) {\n",
- " System.out.println(fruits.get(index));\n",
- " index++;\n",
- "}"
- ]
- }
- ],
- "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": "17.0.12+7-Ubuntu-1ubuntu224.04"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 4
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_07/Period1/2024-09-19-unit_7_p1-7.4.ipynb b/_notebooks/CSA/units_1_to_10/unit_07/Period1/2024-09-19-unit_7_p1-7.4.ipynb
deleted file mode 100644
index 73f060fe..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_07/Period1/2024-09-19-unit_7_p1-7.4.ipynb
+++ /dev/null
@@ -1,321 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "toc: true\n",
- "title: 7.4 - Developing Algorithms Using ArrayLists\n",
- "description: ArrayLists Lesson\n",
- "authors: Aidan Lau, Saathvik Gampa, Sri Surapaneni, Tanav Kambhampati\n",
- "categories: [AP CSA]\n",
- "type: ccc\n",
- "permalink: /csa/unit7-p1/unit7-4\n",
- "menu: nav/CSA_Units/csa_unit7_p1.html\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# 7.4 Developing Algorithms Using ArrayLists\n",
- "\n",
- "Common Arraylist Methods: \n",
- "- size(): Returns the size of the arraylist as an Integer\n",
- "- add(object): Adds an object to the end of your ArrayList\n",
- "- void add(index, object): Addes an object to an index of your choice. Shifts the index of everything to the right by one and increases size by 1\n",
- "- get(index): Retrieves the object at the index specified\n",
- "- set(index, obj): Like void add, but instead of adding, it replaces the object that's already in that index\n",
- "- remove(index): Removes the object at specified index"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 1,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "3\n"
- ]
- }
- ],
- "source": [
- "//size() & add(object)\n",
- "\n",
- "ArrayList numbers = new ArrayList<>();\n",
- " numbers.add(1.0);\n",
- " numbers.add(2.0);\n",
- " numbers.add(3.0);\n",
- "\n",
- "int size = numbers.size();\n",
- "\n",
- "System.out.println(size);"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 2,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "3.0\n",
- "4.0\n",
- "3.0\n"
- ]
- }
- ],
- "source": [
- "//void add(index, object)\n",
- "//get(index)\n",
- "ArrayList numbers = new ArrayList<>();\n",
- " numbers.add(1.0);\n",
- " numbers.add(2.0);\n",
- " numbers.add(3.0);\n",
- "\n",
- "System.out.println(numbers.get(2));\n",
- "\n",
- " numbers.add(2,4.0);\n",
- "\n",
- "System.out.println(numbers.get(2));\n",
- "System.out.println(numbers.get(3));"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 3,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "3.0\n",
- "4.0\n"
- ]
- }
- ],
- "source": [
- "// set(index, obj)\n",
- "\n",
- "\n",
- "ArrayList numbers = new ArrayList<>();\n",
- " numbers.add(1.0);\n",
- " numbers.add(2.0);\n",
- " numbers.add(3.0);\n",
- "\n",
- "System.out.println(numbers.get(2));\n",
- "\n",
- " numbers.set(2,4.0);\n",
- "\n",
- "System.out.println(numbers.get(2));\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 4,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "3.0\n",
- "1.0\n",
- "2.0\n"
- ]
- },
- {
- "ename": "EvalException",
- "evalue": "Index 2 out of bounds for length 2",
- "output_type": "error",
- "traceback": [
- "\u001b[1m\u001b[31m---------------------------------------------------------------------------\u001b[0m",
- "\u001b[1m\u001b[31mjava.lang.IndexOutOfBoundsException: Index 2 out of bounds for length 2\u001b[0m",
- "\u001b[1m\u001b[31m\tat java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)\u001b[0m",
- "\u001b[1m\u001b[31m\tat java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)\u001b[0m",
- "\u001b[1m\u001b[31m\tat java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:266)\u001b[0m",
- "\u001b[1m\u001b[31m\tat java.base/java.util.Objects.checkIndex(Objects.java:361)\u001b[0m",
- "\u001b[1m\u001b[31m\tat java.base/java.util.ArrayList.get(ArrayList.java:427)\u001b[0m",
- "\u001b[1m\u001b[31m\tat .(#38:1)\u001b[0m"
- ]
- }
- ],
- "source": [
- "// remove(index)\n",
- "\n",
- "\n",
- "ArrayList numbers = new ArrayList<>();\n",
- " numbers.add(1.0);\n",
- " numbers.add(2.0);\n",
- " numbers.add(3.0);\n",
- "System.out.println(numbers.get(2));\n",
- " numbers.remove(2);\n",
- "\n",
- "System.out.println(numbers.get(0));\n",
- "System.out.println(numbers.get(1));\n",
- "System.out.println(numbers.get(2));\n",
- "\n",
- "//anybody know why we get an IndexOutofBoundsException eror?"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Here's an example of a program using **Arrays** that finds the maximum value:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 5,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "The maximum value is: 5.0\n"
- ]
- }
- ],
- "source": [
- "public class Main {\n",
- " public static void main(String[] args) {\n",
- " double[] values = {1, 2, 3, 4, 5};\n",
- "\n",
- " double maxValue = findMax(values);\n",
- " System.out.println(\"The maximum value is: \" + maxValue);\n",
- " }\n",
- "\n",
- " private static double findMax(double[] values) {\n",
- " double max = values[0];\n",
- " for (int index = 1; index < values.length; index++) {\n",
- " if (values[index] > max) {\n",
- " max = values[index];\n",
- " }\n",
- " }\n",
- " return max;\n",
- " }\n",
- "}\n",
- "Main.main(null);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "#### Now, how can we modify this to use an ArrayList?"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 6,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "The maximum value is: 4.9\n"
- ]
- }
- ],
- "source": [
- "\n",
- "public class Main {\n",
- " public static void main(String[] args) {\n",
- " ArrayList values = new ArrayList<>();\n",
- " values.add(1.2);\n",
- " values.add(3.4);\n",
- " values.add(2.6);\n",
- " values.add(4.9);\n",
- " values.add(0.8);\n",
- "\n",
- " double maxValue = findMax(values);\n",
- " System.out.println(\"The maximum value is: \" + maxValue);\n",
- " }\n",
- "\n",
- " private static 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",
- " return max; \n",
- " }\n",
- "}\n",
- "Main.main(null);\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Homework:\n",
- "\n",
- "(Paragraph Answer)\n",
- "1. What is the difference between the two examples above. Which one is better and why?\n",
- "\n",
- "(Code Answer)\n",
- "\n",
- "2. Make your own algorithm using ArrayLists that finds the sum of the elements in the ArrayList"
- ]
- }
- ],
- "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": "17.0.12+7-Ubuntu-1ubuntu224.04"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 4
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_07/Period1/2024-09-23-unit_7_p1-7.1.ipynb b/_notebooks/CSA/units_1_to_10/unit_07/Period1/2024-09-23-unit_7_p1-7.1.ipynb
deleted file mode 100644
index d8cbc60c..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_07/Period1/2024-09-23-unit_7_p1-7.1.ipynb
+++ /dev/null
@@ -1,194 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "toc: true\n",
- "title: 7.1 ArrayList Intro\n",
- "description: Introduction to ArrayLists \n",
- "authors: Aidan Lau, Saathvik Gampa, Sri Surapaneni, Tanav Kambhampati\n",
- "categories: [AP CSA]\n",
- "type: ccc\n",
- "permalink: /csa/unit7-p1/unit7-1\n",
- "menu: nav/CSA_Units/csa_unit7_p1.html\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 7.1: ArrayList Intro"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "- ArrayLists are dynamic (size can grow and shrink unlike arrays which are static)\n",
- "- Instead of creating a different size array each time, we can use ArrayLists!\n",
- "- Ex: You and ur beautiful wife...\n",
- "\n",
- "![Screenshot 2024-09-18 at 8 05 02 PM](https://github.com/user-attachments/assets/480349f7-a97f-4c3d-a6f6-1868e095a2f4)\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "In order to use the ArrayList class, it needs to be imported from the java util package. This can be done by writing import java.util.ArrayList; at the beginning of the code\n",
- "\n",
- "- To use Arraylist class, it needs to be imported from java.util package\n",
- "- At beginning of code using an Arraylist, type the command below!"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "import java.util.ArrayList;\n",
- "\n",
- "// your amazing code here!"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "ArrayList objects are initialized the same way as most object classes. However, the element type (String, Integer, Boolean) must be specified in the <>. Look at the example below, where the element type is String in this case.\n",
- "\n",
- "- Arraylist objects are initialized like most object classes\n",
- "- the element type must be initialized in <>\n",
- "- The objects can't store primitive types directly"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "ArrayList bobtheminion = new ArrayList(); // example of initializing an arraylist of strings called \"awesomeword\"\n",
- "ArrayList bobtheminionage = new ArrayList<>();\n",
- "ArrayList isbobtheminionavailable = new ArrayList<>(); \n",
- "ArrayList minionheights = new ArrayList<>();"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# Popcorn Hack #1\n",
- "What's wrong with the code below?"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "import java.util.ArrayList;\n",
- "\n",
- "ArrayList awesomeword = new ArrayList(); \n",
- "ArrayList coolnumbers = new ArrayList();\n",
- "ArrayList truefalse = new ArrayList();\n",
- "// change code and comment what you changed when doing homework"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "\n",
- " "
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "ArrayLists can be created without specifying a type, allowing them to hold any object type. However, its better to define the type because it allows the compiler to catch errors at compile time whcich makes the code more efficient and easier to debug. Example is below\n",
- "- Arraylists can be created without specifying a type (they can hold any)\n",
- "- Better to define the type as it makes code easier to debug and more efficient"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "ArrayList list = new ArrayList(); // no object type specified!"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "#### Popcorn Hack #2\n",
- "\n",
- "Create two ArrayList objects, one for storing integers (called sritestgrades) and another for storing strings (called srishobbies)."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "import java.util.ArrayList;\n",
- "\n",
- " // ur code here\n",
- " \n",
- " sritestgrades.add(45);\n",
- " sritestgrades.add(32);\n",
- " sritestgrades.add(1);\n",
- " sritestgrades.add(90);\n",
- " sritestgrades.add(74);\n",
- " \n",
- " srishobbies.add(\"watching netflix\");\n",
- " srishobbies.add(\"sleeping\");\n",
- " srishobbies.add(\"\");\n",
- " srishobbies.add(\"annoying saathvik\");\n",
- " \n",
- " // Printing the values\n",
- " System.out.println(\"Sri's horrible test grades are: \" + sritestgrades);\n",
- " System.out.println(\"Sri's hobbies are: \" + srishobbies);\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- " "
- ]
- }
- ],
- "metadata": {
- "kernelspec": {
- "display_name": "java (IJava/j!)",
- "language": "java",
- "name": "jbang-ijava"
- },
- "language_info": {
- "codemirror_mode": "java",
- "file_extension": ".jshell",
- "mimetype": "text/x-java-source",
- "name": "java",
- "pygments_lexer": "java",
- "version": "17.0.11+7-LTS-207"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_07/Period1/2024-09-23-unit_7_p1-7.2.ipynb b/_notebooks/CSA/units_1_to_10/unit_07/Period1/2024-09-23-unit_7_p1-7.2.ipynb
deleted file mode 100644
index f35e9df2..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_07/Period1/2024-09-23-unit_7_p1-7.2.ipynb
+++ /dev/null
@@ -1,619 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "toc: true\n",
- "title: 7.2 - ArrayList Methods\n",
- "description: ArrayList Methods\n",
- "authors: Aidan Lau, Saathvik Gampa, Sri Surapaneni, Tanav Kambhampati\n",
- "categories: [AP CSA]\n",
- "type: ccc\n",
- "permalink: /csa/unit7-p1/unit7-2\n",
- "menu: nav/CSA_Units/csa_unit7_p1.html\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# 7.2: ArrayList Methods"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "- Getting access to elements stored in an ArrayList can be done with iteration statements\n",
- "- This is called \"traversing\" the ArrayList\n",
- "\n",
- "Here are some useful ArrayList methods:\n",
- "\n",
- "* `void add(int index, Object obj)` - Inserts `obj` at the specified `index`, shifting elements at and above that position to the right, and increases the list's size by one.\n",
- " \n",
- "* `boolean add(Object obj)` - Adds `obj` to the end of the list and returns `true`.\n",
- "\n",
- "* `Object get(int index)` - Retrieves the element located at the specified `index`.\n",
- "\n",
- "* `int size()` - Returns the total number of elements currently in the list.\n",
- "\n",
- "* `Object set(int index, Object obj)` - Replaces the element at `index` with `obj` and returns the element previously at that position.\n",
- "\n",
- "* `Object remove(int index)` - Deletes the element at `index`, shifts all subsequent elements to the left, and returns the removed element.\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Note on Arraylist<> (Specifying Elements)\n",
- "- When Arraylist is specified, then the code will only allow or return objects of that specific type\n",
- "- You don't have to define an element, its just better to because the compiler will show an error and it'll catch bugs easier\n",
- "\n",
- "Examples below!\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "ArrayList names = new ArrayList<>(); // Will only store Strings\n",
- "ArrayList numbers = new ArrayList<>(); // Will only store Integers"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 1,
- "metadata": {},
- "outputs": [
- {
- "ename": "CompilationException",
- "evalue": "",
- "output_type": "error",
- "traceback": [
- "\u001b[1m\u001b[30m| \u001b[1m\u001b[30mages.add(\u001b[0m\u001b[1m\u001b[30m\u001b[41m\"25\"\u001b[0m\u001b[1m\u001b[30m); // Compiler error because \"25\" is a String, not an Integer\u001b[0m",
- "\u001b[1m\u001b[31mincompatible types: java.lang.String cannot be converted to java.lang.Integer\u001b[0m",
- ""
- ]
- }
- ],
- "source": [
- "ArrayList ages = new ArrayList<>();\n",
- "ages.add(25); // Works fine\n",
- "ages.add(\"25\"); // Compiler error because \"25\" is a String, not an Integer\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Size of the ArrayList\n",
- "\n",
- "* `int size();` : returns the number of elements in the list\n",
- "\n",
- "Example below!"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 2,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "3\n"
- ]
- }
- ],
- "source": [
- "ArrayList a1 = new ArrayList<>();\n",
- "a1.add(10);\n",
- "a1.add(20);\n",
- "a1.add(30);\n",
- "\n",
- "System.out.println(a1.size()); \n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Adding Items to an ArrayList\n",
- "\n",
- "* `boolean add(Object obj);` : adds obj to the end of the `rrayList and returns true\n",
- "* `void add(int index, Object obj)` : inserts obj at the specified index and if the index is valid, it shifts all the elements to the right from that position and increases the size of the Arraylist (wow i bet arrays cant do that!)\n",
- "\n",
- "example below!\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 1,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "[5.5, 6.3, 7.2, 9.8]\n"
- ]
- }
- ],
- "source": [
- "ArrayList numbers = new ArrayList<>();\n",
- "numbers.add(5.5);\n",
- "numbers.add(7.2);\n",
- "numbers.add(9.8);\n",
- "\n",
- "numbers.add(1, 6.3); // inserts 6.3 at index 1\n",
- "\n",
- "System.out.println(numbers);\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- " "
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# Popcorn Hack #3 (Long)\n",
- "- Step 1: Declare and Initialize\n",
- "\n",
- "Create an ArrayList that stores Double values, called scores.\n",
- "- Step 2: Add Elements\n",
- "\n",
- "Add the following values to your scores list: 85.6, 92.4, 78.9, 88.1.\n",
- "Print the size of the list after adding these elements\n",
- "- Step 3: insert at index\n",
- "\n",
- "use the add(int index, Double obj) method to insert the value 90.0 at index 2.\n",
- "Print the list to verify the insertion.\n",
- "- Step 4: Remove an Element\n",
- "\n",
- "Remove the element at index 3 using remove(int index).\n",
- "Print the list to see the updated values.\n",
- "- Step 5: Get and Set\n",
- "\n",
- "Retrieve the element at index 1 and print it.\n",
- "Then, use set(int index, Double obj) to update the element at index 0 to 91.5.\n",
- "Print the list after the modification."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Deleting Items from an ArrayList\n",
- "\n",
- "`E remove(int index)` : Deletes the element at the specified index and shifts all elements after that index one position to the left. it reduces the size of the arraylist by 1. (also returns element thats removed when used)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 2,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "initial cars list: [MortMobile, Lopez Lambo, Jonathan Jeepatron, Cybertruck]\n",
- "updated cars list: [MortMobile, Lopez Lambo, Cybertruck]\n"
- ]
- }
- ],
- "source": [
- "ArrayList cars = new ArrayList<>();\n",
- "cars.add(\"MortMobile\");\n",
- "cars.add(\"Lopez Lambo\");\n",
- "cars.add(\"Jonathan Jeepatron\");\n",
- "cars.add(\"Cybertruck\");\n",
- "\n",
- "// prints the initial list of cars\n",
- "System.out.println(\"initial cars list: \" + cars);\n",
- "\n",
- "// removing the car at index 2 (Jonathan Jeepatron)\n",
- "cars.remove(2);\n",
- "\n",
- "// prints updated list of cars after deletion (rip jonathan jeepatron)\n",
- "System.out.println(\"updated cars list: \" + cars);\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "------------------------------------------------------------------------------------------------"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Updating Items in an `ArrayList`\n",
- "\n",
- "To update variables or object properties in Java, simply assign new values using the = operator or update object fields through methods. Make sure the data types match and understand how scopes affect where updates can occur."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 3,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Original list: [Apple, Banana, Orange]\n",
- "Updated list: [Apple, Grapes, Orange]\n"
- ]
- }
- ],
- "source": [
- "import java.util.ArrayList;\n",
- "\n",
- "ArrayList fruits = new ArrayList<>();\n",
- "\n",
- "\n",
- "fruits.add(\"Apple\");\n",
- "fruits.add(\"Banana\");\n",
- "fruits.add(\"Orange\");\n",
- "\n",
- "System.out.println(\"Original list: \" + fruits);\n",
- "\n",
- "\n",
- "fruits.set(1, \"Grapes\");\n",
- "\n",
- "\n",
- "System.out.println(\"Updated list: \" + fruits);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Popcorn hack\n",
- "\n",
- "You have an `ArrayList` that contains the names of 5 cities:\n",
- "\n",
- "```java\n",
- "[\"New York\", \"Los Angeles\", \"Chicago\", \"Houston\", \"Phoenix\"]\n",
- "\n",
- "Write a Java program to update the third city (index 2) to \"San Francisco\" using the set() method, and then print the updated list.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "\n",
- "\n",
- "import java.util.ArrayList;\n",
- "\n",
- "\n",
- "ArrayList<_____> cities = new ArrayList<>();\n",
- "cities.add(\"New York\");\n",
- "cities.add(\"Los Angeles\");\n",
- "cities.add(\"Chicago\");\n",
- "cities.add(\"Houston\");\n",
- "cities.add(\"Phoenix\");\n",
- "\n",
- "\n",
- "System.out.println(cities);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Expected Output:\n",
- "[New York, Los Angeles, San Francisco, Houston, Phoenix]"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Accessing Items in an `ArrayList`\n",
- "\n",
- "In Java, you can access items in an array by using the index of the element, with array indices starting from 0. For example, array[0] will access the first element, and array[2] will access the third element. You can use a loop, such as a for or while loop, to iterate through all the elements of the array."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 5,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "First number: 10\n",
- "Third number: 30\n"
- ]
- }
- ],
- "source": [
- "\n",
- "import java.util.ArrayList;\n",
- "\n",
- "ArrayList numbers = new ArrayList<>();\n",
- "\n",
- "numbers.add(10);\n",
- "numbers.add(20);\n",
- "numbers.add(30);\n",
- "numbers.add(40);\n",
- "\n",
- "int firstNumber = numbers.get(0); \n",
- "int thirdNumber = numbers.get(2); \n",
- "\n",
- "\n",
- "System.out.println(\"First number: \" + firstNumber);\n",
- "System.out.println(\"Third number: \" + thirdNumber);"
- ]
- },
- {
- "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": 8,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "ArrayList Elements:\n",
- "Dog\n",
- "Cat\n",
- "Elephant\n"
- ]
- }
- ],
- "source": [
- "\n",
- "import java.util.ArrayList;\n",
- "\n",
- "public class Main {\n",
- "\n",
- " public static void main(String[] args) {\n",
- " // Create an ArrayList of strings\n",
- " ArrayList animals = new ArrayList<>();\n",
- " animals.add(\"Dog\");\n",
- " animals.add(\"Cat\");\n",
- " animals.add(\"Elephant\");\n",
- "\n",
- " printArrayList(animals);\n",
- " }\n",
- " \n",
- " public static void printArrayList(ArrayList list) {\n",
- " System.out.println(\"ArrayList Elements:\");\n",
- " for (String element : list) {\n",
- " System.out.println(element);\n",
- " }\n",
- " }\n",
- "\n",
- "\n",
- "}\n",
- "\n",
- "Main.main(null);"
- ]
- },
- {
- "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": 9,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Returned ArrayList: [Lion, Tiger, Elephant]\n"
- ]
- }
- ],
- "source": [
- "\n",
- "import java.util.ArrayList;\n",
- "\n",
- "public class Main {\n",
- "\n",
- " public static ArrayList createAnimalList() {\n",
- " ArrayList animals = new ArrayList<>();\n",
- " animals.add(\"Lion\");\n",
- " animals.add(\"Tiger\");\n",
- " animals.add(\"Elephant\");\n",
- " return animals;\n",
- " }\n",
- "\n",
- " public static void main(String[] args) {\n",
- " ArrayList animalList = createAnimalList();\n",
- "\n",
- " System.out.println(\"Returned ArrayList: \" + animalList);\n",
- " }\n",
- "}\n",
- "\n",
- "Main.main(null);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# Hard Hack: **\"Simple Inventory Manager\"**\n",
- "\n",
- "### Problem Statement:\n",
- "\n",
- "You are building a basic inventory system using Java’s `ArrayList` to manage a list of items in a store. You will implement functions to add, update, delete, and view items in the inventory.\n",
- "\n",
- "**Starting Inventory**: \n",
- "The inventory already contains the following items:\n",
- "- `\"Laptop\"`, `\"Mouse\"`, `\"Keyboard\"`\n",
- "\n",
- "Your task is to:\n",
- "1. **Add items** to the inventory.\n",
- "2. **Update an item** at a specific position in the inventory.\n",
- "3. **Delete an item** from the inventory.\n",
- "4. **View all the items** currently in the inventory.\n",
- "\n",
- "### Directions:\n",
- "\n",
- "1. **Create an `ArrayList`** called `inventory` that holds strings representing the items.\n",
- "2. **Implement the following methods**:\n",
- " - `addItem(ArrayList inventory, String item)`: Adds an item to the inventory.\n",
- " - `updateItem(ArrayList inventory, int index, String newItem)`: Updates the item at the specified index.\n",
- " - `deleteItem(ArrayList inventory, int index)`: Deletes the item at the specified index.\n",
- " - `viewInventory(ArrayList inventory)`: Displays all the items in the inventory.\n",
- "\n",
- "3. **In your `main()` method**:\n",
- " - Initialize the `inventory` with the starting items.\n",
- " - Add one new item to the inventory.\n",
- " - Update the second item.\n",
- " - Delete the third item.\n",
- " - Display the final inventory.\n",
- "\n",
- "### Example Workflow:\n",
- "\n",
- "1. Start with the `inventory`: `[\"Laptop\", \"Mouse\", \"Keyboard\"]`.\n",
- "2. Add `\"Monitor\"`.\n",
- "3. Update `\"Mouse\"` to `\"Gaming Mouse\"`.\n",
- "4. Delete `\"Keyboard\"`.\n",
- "5. Display the final `inventory`.\n",
- "\n",
- "---\n",
- "\n",
- "### Expectations:\n",
- "\n",
- "- Ensure **valid index** when updating or deleting items (handle out-of-bounds indices).\n",
- "- Use the **`get()`, `set()`, `add()`, and `remove()`** methods to manage the `ArrayList`.\n",
- "- After all operations, print the final version of the `inventory` using `viewInventory()`.\n",
- "\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Starter Code"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 10,
- "metadata": {},
- "outputs": [],
- "source": [
- "import java.util.ArrayList;\n",
- "\n",
- "public class InventoryManager {\n",
- "\n",
- " // Method to add an item to the inventory\n",
- " public static void addItem(ArrayList inventory, String item) {\n",
- " inventory.add(item);\n",
- " }\n",
- "\n",
- " // Method to update an item at a specific index in the inventory\n",
- " public static void updateItem(ArrayList inventory, int index, String newItem) {\n",
- " if (index >= 0 && index < inventory.size()) {\n",
- " inventory.set(index, newItem);\n",
- " } else {\n",
- " System.out.println(\"Invalid index. Cannot update.\");\n",
- " }\n",
- " }\n",
- "\n",
- " // Method to delete an item from the inventory\n",
- " public static void deleteItem(ArrayList inventory, int index) {\n",
- " if (index >= 0 && index < inventory.size()) {\n",
- " inventory.remove(index);\n",
- " } else {\n",
- " System.out.println(\"Invalid index. Cannot delete.\");\n",
- " }\n",
- " }\n",
- "\n",
- " // Method to display all items in the inventory\n",
- " public static void viewInventory(ArrayList inventory) {\n",
- " System.out.println(\"Current Inventory: \" + inventory);\n",
- " }\n",
- "\n",
- " public static void main(String[] args) {\n",
- " // Initialize the inventory with starting items\n",
- " ArrayList inventory = new ArrayList<>();\n",
- " inventory.add(\"Laptop\");\n",
- " inventory.add(\"Mouse\");\n",
- " inventory.add(\"Keyboard\");\n",
- "\n",
- " // Add a new item\n",
- " addItem(inventory, \"Monitor\");\n",
- "\n",
- " // Update the second item\n",
- " updateItem(inventory, 1, \"Gaming Mouse\");\n",
- "\n",
- " // Delete the third item\n",
- " deleteItem(inventory, 2);\n",
- "\n",
- " // View the final inventory\n",
- " viewInventory(inventory);\n",
- " }\n",
- "}"
- ]
- }
- ],
- "metadata": {
- "kernelspec": {
- "display_name": "java (IJava/j!)",
- "language": "java",
- "name": "jbang-ijava"
- },
- "language_info": {
- "codemirror_mode": "java",
- "file_extension": ".jshell",
- "mimetype": "text/x-java-source",
- "name": "java",
- "pygments_lexer": "java",
- "version": "17.0.11+7-LTS-207"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_07/Period1/2024-09-23-unit_7_p1-7.5.ipynb b/_notebooks/CSA/units_1_to_10/unit_07/Period1/2024-09-23-unit_7_p1-7.5.ipynb
deleted file mode 100644
index 59ce0f99..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_07/Period1/2024-09-23-unit_7_p1-7.5.ipynb
+++ /dev/null
@@ -1,280 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "toc: true\n",
- "title: 7.5 Searching\n",
- "description: Searching ArrayLists\n",
- "authors: Aidan Lau, Saathvik Gampa, Sri Surapaneni, Tanav Kambhampati\n",
- "categories: [AP CSA]\n",
- "type: ccc\n",
- "permalink: /csa/unit7-p1/unit7-5\n",
- "menu: nav/CSA_Units/csa_unit7_p1.html\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Binary and Linear Search\n",
- "> There are two search algorithms you will see on the AP exam:\n",
- "- Linear Search \n",
- "- Binary Search \n",
- "\n",
- "### Linear(Sequential) Search\n",
- "![Linear Search GIF 2](https://github.com/user-attachments/assets/81815823-0e64-4147-babf-5bfacb4bd175)\n",
- "\n",
- "> Search Process\n",
- "1. Remember iteration and selection? Its the same for ArrayLists: a for loop with an if statement inside. \n",
- "2. The for loop parameter uses comparison operators to compare an item inside the ArrayList to the desired searched value\n",
- "3. Keep repeating 1 and 2 until we find the desired searched value\n",
- " \n",
- "\n",
- "### Binary Search\n",
- "![Binary Search GIF 2](https://github.com/user-attachments/assets/17231c38-f0af-4b9f-8efe-6b66292f6e83)\n",
- "> Search Process\n",
- "0. Before anything, the ArrayList HAS to be sorted\n",
- "1. Set the initial minimum, middle, and max of the ArrayList. Your target value is the value you want to find\n",
- "2. Check middle value in comparison with the minimum and maximum\n",
- " - If the middle value is less than the target value, only check the right half of the ArrayList\n",
- " - If the middle value is greater than the target value, only check the left half of the ArrayList\n",
- "\n",
- "**Yes its very confusing but just look at the GIF**"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Now lets look at an example of Linear Search"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "> Visualize this while going through the code\n",
- "![Linear Searching GIF](https://github.com/user-attachments/assets/9704be28-32ff-48e1-88ff-bbf01b64147c)\n",
- "- A for loop will go through each index and its corresponding value until it finds the desired value. \n",
- "\n",
- "### Code\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 8,
- "metadata": {},
- "outputs": [],
- "source": [
- "import java.util.ArrayList;\n",
- "import java.util.Scanner;\n",
- "\n",
- "public class Main {\n",
- " public static void main(String[] args) {\n",
- " ArrayList numbers = new ArrayList();\n",
- " \n",
- " // missing 3, 6, 7, and 10\n",
- " numbers.add(1);\n",
- " numbers.add(2);\n",
- " \n",
- " numbers.add(4);\n",
- " numbers.add(5);\n",
- " \n",
- " \n",
- " numbers.add(8);\n",
- " numbers.add(9);\n",
- " \n",
- " \n",
- " Scanner scanNumber = new Scanner(System.in);\n",
- " System.out.println(\"Enter a number 1-10\");\n",
- " Integer desiredNumber = scanNumber.nextInt();\n",
- " \n",
- "\n",
- " for (int index = 0; index < numbers.size(); index++) {\n",
- " // notice how the == operator is used to compare integers\n",
- " if (numbers.get(index) == desiredNumber) {\n",
- "\n",
- " System.out.println(desiredNumber + \" is in the list\");\n",
- " scanNumber.close();\n",
- " } else {\n",
- " System.out.println(desiredNumber + \" is not in the list.\");\n",
- " scanNumber.close();\n",
- " }\n",
- " }\n",
- "\n",
- " \n",
- " } \n",
- "\n",
- "}"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Things to Remember\n",
- "> To remember linear searching, think:\n",
- "- Iteration and Selection\n",
- " - **Iteration**\n",
- " - Iteration is the process of repeating a step multiple times; In this case, we keep searching for a desired value until it is found\n",
- " - **Selection**\n",
- " - Selection is the process of finding a specific element within a list. We do this using comparison operators\n",
- "- When comparing ``int`` values, use the == operator.\n",
- "- When comparing ``Object`` values, use the ``.equals()`` method to compare values."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Popcorn Hack #1(0.2 mins)\n",
- "\n",
- "![Sequential Searching Flow](https://miro.medium.com/v2/resize:fit:800/0*OWWv4gUnex1Zk2sn.png)\n",
- "\n",
- "> What does each hop or jump represent? What code(look above) is used to achieve this?"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Now lets look at an example of Binary Search\n",
- "> Visualize this while going through the code\n",
- "![Binary Search GIF 2](https://github.com/user-attachments/assets/17231c38-f0af-4b9f-8efe-6b66292f6e83)\n",
- "- Repeatedly divide the search range in half until the target is found or the range is empty\n",
- "- **this is a great GIF to visualize binary searching**\n",
- "\n",
- "### Code"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 9,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "2\n",
- "0\n",
- "4\n",
- "-1\n"
- ]
- }
- ],
- "source": [
- "import java.util.ArrayList;\n",
- "import java.util.Collections;\n",
- "\n",
- "\n",
- "public static int binarySearch(ArrayList elements, int target)\n",
- "{\n",
- " // min and max is the RANGE of the ArrayList\n",
- " int min = 0;\n",
- " int max = elements.size() - 1;\n",
- "\n",
- " // while loop will ensure the array continues to be split in half until target is found\n",
- " while (min <= max)\n",
- " {\n",
- " // this middle value is the INDEX not VALUE. \n",
- " int middle = (min + max) / 2;\n",
- "\n",
- " // now we check if the middle VALUE is less than the number we want. \n",
- " // *remember* the list is sorted so...\n",
- " // if middle is less than the target, you want to split the array into the UPPER HALF\n",
- " // if middle is more than the target, you want to split the array into the LOWER HALF\n",
- " if (elements.get(middle) < target) { // too low\n",
- " min = middle + 1;\n",
- " } else if (elements.get(middle) > target) { // too high\n",
- " max = middle - 1;\n",
- " } else if (elements.get(middle) == target) { // just right\n",
- " return middle;\n",
- " }\n",
- " }\n",
- "\n",
- " return -1;\n",
- "}\n",
- "\n",
- "ArrayList numbers = new ArrayList<>();\n",
- "numbers.add(-20);\n",
- "numbers.add(3);\n",
- "numbers.add(15);\n",
- "numbers.add(81);\n",
- "numbers.add(432);\n",
- "\n",
- "// binary searches HAVE to be sorted\n",
- "Collections.sort(numbers);\n",
- "\n",
- "\n",
- "int index = binarySearch(numbers, 15);\n",
- "System.out.println(index);\n",
- "\n",
- "index = binarySearch(numbers, -20);\n",
- "System.out.println(index);\n",
- "\n",
- "index = binarySearch(numbers, 432);\n",
- "System.out.println(index);\n",
- "\n",
- "index = binarySearch(numbers, 53);\n",
- "System.out.println(index);\n",
- "\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# Homework\n",
- "- Imagine you're an online E-store that sells video games. Use linear searching to help Aidan find if the game, Grand Theft Auto V, is offered in the E-store. If it is, tell him the price. If it isn't, tell him where he can find it"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "import java.util.ArrayList;\n",
- "\n",
- "public class searchString {\n",
- " public static void main(String[] args) {\n",
- " ArrayList videoGames = new ArrayList();\n",
- " videoGames.add(\"Roblox\");\n",
- " videoGames.add(\"Fortnite\");\n",
- " videoGames.add(\"Valorant\");\n",
- " videoGames.add(\"Apex Legends\");\n",
- " videoGames.add(\"GTA V\");\n",
- "\n",
- " // *code*\n",
- "}"
- ]
- }
- ],
- "metadata": {
- "kernelspec": {
- "display_name": "java (IJava/j!)",
- "language": "java",
- "name": "jbang-ijava"
- },
- "language_info": {
- "codemirror_mode": "java",
- "file_extension": ".jshell",
- "mimetype": "text/x-java-source",
- "name": "java",
- "pygments_lexer": "java",
- "version": "17.0.12+0"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_07/Period1/2024-09-23-unit_7_p1-7.6.ipynb b/_notebooks/CSA/units_1_to_10/unit_07/Period1/2024-09-23-unit_7_p1-7.6.ipynb
deleted file mode 100644
index a891f398..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_07/Period1/2024-09-23-unit_7_p1-7.6.ipynb
+++ /dev/null
@@ -1,277 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "toc: true\n",
- "title: 7.6 Sorting\n",
- "description: Sorting ArrayLists\n",
- "authors: Aidan Lau, Saathvik Gampa, Sri Surapaneni, Tanav Kambhampati\n",
- "categories: [AP CSA]\n",
- "type: ccc\n",
- "permalink: /csa/unit7-p1/unit7-6\n",
- "menu: nav/CSA_Units/csa_unit7_p1.html\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# 7.6 Sorting\n",
- "\n",
- "> Two of the following sorting algorithms will be on the AP exam.(merge sort is discussed in Unit 10)\n",
- "- Selection sort : Look for the smallest element, swap with first element. Look for the second smallest, swap with second element, etc…\n",
- "- Insertion sort : Build an increasingly large sorted front portion of array.\n",
- "#### All sorting algorithms have...\n",
- "- comparison-based sorting, which determines order of elements by comparing them to each other. Ways to compare are:\n",
- " - <, >, compareTo "
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Selection Sort \n",
- "\n",
- "> Process : Orders a list of values by repeatedly putting the smallest or largest unplaced value into its final position.\n",
- "- Look through the list to find the smallest value.\n",
- "- Swap it so that it is at index 0.\n",
- "- Look through the list to find the second-smallest value.\n",
- "- Swap it so that it is at index 1.\n",
- "- ...\n",
- "- Repeat until all values are in their proper places.\n",
- "\n",
- "> Visualize this diagram as you go through the code\n",
- "- ![Selection Sort GIF](https://github.com/user-attachments/assets/5887afde-3f2d-427d-bb7c-d7a30a7f876f)\n",
- "\n",
- "### Code Implementation:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 3,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "[3, 86, -20, 14, 40]\n",
- "[-20, 3, 14, 40, 86]\n"
- ]
- }
- ],
- "source": [
- "import java.util.ArrayList;\n",
- "\n",
- "public static void selectionSort(ArrayList elements)\n",
- "{\n",
- " // outer loop to iterate through every element in the ArrayList\n",
- " for (int j = 0; j < elements.size() - 1; j++)\n",
- " {\n",
- " // set the current value being compared \n",
- " int minIndex = j;\n",
- " // INNER LOOP TO ITERATE EVERY ELEMENT AFTER THE minIndex VALUE\n",
- " for (int k = j + 1; k < elements.size(); k++)\n",
- " {\n",
- " // FIND THE SMALLEST ELEMENT IN THE LIST AND SET IT TO THE minINDEX\n",
- " if (elements.get(k) < elements.get(minIndex))\n",
- " {\n",
- " minIndex = k;\n",
- " }\n",
- " }\n",
- " // swap minIndex value with new smaller value\n",
- " int temp = elements.get(j);\n",
- " elements.set(j, elements.get(minIndex));\n",
- " elements.set(minIndex, temp);\n",
- " }\n",
- "}\n",
- "\n",
- "// test cases\n",
- "ArrayList arr1 = new ArrayList<>();\n",
- "arr1.add(3);\n",
- "arr1.add(86);\n",
- "arr1.add(-20);\n",
- "arr1.add(14);\n",
- "arr1.add(40);\n",
- "System.out.println(arr1.toString());\n",
- "selectionSort(arr1);\n",
- "System.out.println(arr1.toString());"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Insertion Sort \n",
- "\n",
- "> Process : Shift each element into a sorted sub-array.\n",
- "- To sort a list of n elements.\n",
- " - Loop through indices i from 1 to n – 1:\n",
- " - For each value at position i, insert into correct position in the sorted list from index 0 to i – 1.\n",
- "\n",
- "> Visualize this GIF as you go through the code:\n",
- "- ![Insertion Sort GIF](https://github.com/user-attachments/assets/47646078-e11c-4b50-beb6-98982fc3758b)\n",
- "\n",
- "### Code Implementation:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 2,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "[3, 86, -20, 14, 40]\n",
- "[-20, 3, 14, 40, 86]\n"
- ]
- }
- ],
- "source": [
- "import java.util.ArrayList;\n",
- "\n",
- "\n",
- "public static void insertionSort(ArrayList elements)\n",
- "{\n",
- " // outer loop to iterate through every element in the list\n",
- " // notice how it starts at 1 because the 0 index is considered \"sorted\"\n",
- " for (int j = 1; j < elements.size(); j++) {\n",
- " // store current element in a temporary variable\n",
- " int temp = elements.get(j);\n",
- " // initialize the possible index where the current element might be inserted\n",
- " int possibleIndex = j;\n",
- " \n",
- " // shift elements to the right until the correct position for temp is found\n",
- " while (possibleIndex > 0 && temp < elements.get(possibleIndex - 1)) \n",
- " {\n",
- " // move previous element to the right\n",
- " elements.set(possibleIndex, elements.get(possibleIndex - 1));\n",
- " \n",
- " // decrement index to check values to the left\n",
- " possibleIndex--;\n",
- " }\n",
- " \n",
- " // insert current element into correct position\n",
- " elements.set(possibleIndex, temp);\n",
- " }\n",
- "}\n",
- "\n",
- "// test cases\n",
- "ArrayList arr1 = new ArrayList<>();\n",
- "arr1.add(3);\n",
- "arr1.add(86);\n",
- "arr1.add(-20);\n",
- "arr1.add(14);\n",
- "arr1.add(40);\n",
- "System.out.println(arr1.toString());\n",
- "insertionSort(arr1);\n",
- "System.out.println(arr1.toString());\n",
- "\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# Helpful Resources\n",
- "> Watch these if you're still unsure about selection and insertion sort. These helped me a lot. \n",
- "\n",
- "- [Selection Sort Walkthrough](https://www.youtube.com/watch?v=cqh8nQwuKNE)\n",
- "- [Insertion Sort Walkthrough](https://www.youtube.com/watch?v=lCDZ0IprFw4)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# Homework\n",
- "\n",
- "- You're a teacher for a computer science class at Rancho Bernardo. You have a list of all the grades of the students in your class but its hard to see who has the highest and lowest grade. Use either insertion sort or selection sort to sort the ArrayList so the grades are easy to see. \n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "import java.util.ArrayList;\n",
- "\n",
- "public class SortTest\n",
- "{\n",
- " public static void someSortingAlgorithm(ArrayList elements)\n",
- " { \n",
- " /* code */\n",
- " }\n",
- "\n",
- " public static void main(String[] args)\n",
- " {\n",
- " ArrayList arr1 = new ArrayList<>();\n",
- " arr1.add(85);\n",
- " arr1.add(92);\n",
- " arr1.add(76);\n",
- " arr1.add(88);\n",
- " arr1.add(67);\n",
- " arr1.add(94);\n",
- " arr1.add(73);\n",
- " arr1.add(89);\n",
- " arr1.add(91);\n",
- " arr1.add(82);\n",
- " arr1.add(78);\n",
- " arr1.add(88);\n",
- " arr1.add(95);\n",
- " arr1.add(60);\n",
- " arr1.add(84);\n",
- " arr1.add(77);\n",
- " arr1.add(91);\n",
- " arr1.add(68);\n",
- " arr1.add(97);\n",
- " arr1.add(83);\n",
- "\n",
- " /* code */\n",
- " }\n",
- "}"
- ]
- }
- ],
- "metadata": {
- "kernelspec": {
- "display_name": "java (IJava/j!)",
- "language": "java",
- "name": "jbang-ijava"
- },
- "language_info": {
- "codemirror_mode": "java",
- "file_extension": ".jshell",
- "mimetype": "text/x-java-source",
- "name": "Java",
- "pygments_lexer": "java",
- "version": "17.0.12+0"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_07/Period1/2024-09-23-unit_7_p1-7.7.ipynb b/_notebooks/CSA/units_1_to_10/unit_07/Period1/2024-09-23-unit_7_p1-7.7.ipynb
deleted file mode 100644
index 958226d7..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_07/Period1/2024-09-23-unit_7_p1-7.7.ipynb
+++ /dev/null
@@ -1,166 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "toc: true\n",
- "title: 7.7 - Ethical Issues around Data Collection\n",
- "description: Ethical issues around data collection with ArrayLists\n",
- "authors: Aidan Lau, Saathvik Gampa, Sri Surapaneni, Tanav Kambhampati\n",
- "categories: [AP CSA]\n",
- "type: ccc\n",
- "permalink: /csa/unit7-p1/unit7-7\n",
- "menu: nav/CSA_Units/csa_unit7_p1.html\n",
- "---"
- ]
- },
- {
- "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",
- "- Data Collection: Methods (cookies, tracking, etc.)\n",
- "- Ethical Data Use: Identifying Personal data (Personal Identifiable Information, Sensitive Personal Information)\n",
- "- Security Practices: Data Encryption, Data Anonymization, Data Minimization"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Privacy Protection mechanisms\n",
- "- Encryption: Encode data for only authorized users to access.\n",
- "- Anonymization: Remove personal information from data.\n",
- "- Data Minimization: Collect only necessary data.\n",
- "- User Control: Allowing users to control how their data is used\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 4,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Original Data: mySecretPassword123\n",
- "Hash Code: 1107444891\n",
- "Same Data Hash: 1107444891\n",
- "Modified Data: mySecretPassword124\n",
- "Modified Data Hash: 1107444892\n"
- ]
- }
- ],
- "source": [
- "// Example string data\n",
- "String originalData = \"mySecretPassword123\";\n",
- "\n",
- "// Generate a hash code for the string\n",
- "int hash = originalData.hashCode();\n",
- "\n",
- "// Display the original data and its hash\n",
- "System.out.println(\"Original Data: \" + originalData);\n",
- "System.out.println(\"Hash Code: \" + hash);\n",
- "\n",
- "// Demonstrate that the same string always produces the same hash\n",
- "String sameData = \"mySecretPassword123\";\n",
- "int sameHash = sameData.hashCode();\n",
- "System.out.println(\"Same Data Hash: \" + sameHash);\n",
- "\n",
- "// Demonstrate that a small change in data produces a different hash\n",
- "String modifiedData = \"mySecretPassword124\";\n",
- "int modifiedHash = modifiedData.hashCode();\n",
- "System.out.println(\"Modified Data: \" + modifiedData);\n",
- "System.out.println(\"Modified Data Hash: \" + modifiedHash);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Uses of Hashing\n",
- "- Hashing is used to store passwords securely but it is not enough for large scale industries.\n",
- "- Hashing is used to conceal sensitive information like credit card information but not enough to protect it entirely."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Hashing with Salt\n",
- "\n",
- "As we talked about earlier in the hashing section, hashing is a one-way function. This means that once you hash a value, you can't get the original value back. This is useful for storing passwords, but it also means that if two users have the same password, they will have the same hash. This is a problem because if an attacker gets access to the hash, they can use a rainbow table to look up the hash and find the original password.\n",
- "\n",
- "Thus, we use Hasing with Salt which means that even if 2 users have the same password, they will have different hashes because we add a random value to the password before hashing it. This random value is called a salt."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Homework"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Homework Problem: Exploring Hashing and Privacy Protection (Extra Credit)\n",
- "\n",
- "#### **Problem:**\n",
- "Write a Java program that simulates how hashing works in protecting passwords. You will implement the following tasks:\n",
- "\n",
- "1. **Task 1: Basic Password Hashing**\n",
- " - Write a program that accepts a user's password input and generates a hash using the **`hashCode()`** method.\n",
- " - Display the original password and the hash to show how the same input always produces the same hash.\n",
- "\n",
- "2. **Task 2: Salting the Password**\n",
- " - Enhance the program by generating a random **salt** for the password. Append the salt to the password before hashing, and display both the salt and the hashed password.\n",
- " - Store the salt separately and demonstrate that the same password with a different salt produces a different hash.\n",
- "\n",
- "3. **Task 3: Verifying the Password**\n",
- " - Write a method that simulates logging in by taking a password and salt as input, hashing them again, and comparing the result to the previously stored hash.\n",
- " - If the hash matches, display \"Login Successful\"; otherwise, display \"Login Failed.\"\n",
- "\n",
- "#### **Extra Challenge (Optional):**\n",
- "- Research and use the **`MessageDigest`** class in Java to implement password hashing with a more secure algorithm like **SHA-256**. Modify your program to use this instead of `hashCode()`.\n",
- "\n"
- ]
- }
- ],
- "metadata": {
- "kernelspec": {
- "display_name": "java (IJava/j!)",
- "language": "java",
- "name": "jbang-ijava"
- },
- "language_info": {
- "codemirror_mode": "java",
- "file_extension": ".jshell",
- "mimetype": "text/x-java-source",
- "name": "java",
- "pygments_lexer": "java",
- "version": "17.0.11+7-LTS-207"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_07/Period1/2024-09-23-unit_7_p1-homepage.ipynb b/_notebooks/CSA/units_1_to_10/unit_07/Period1/2024-09-23-unit_7_p1-homepage.ipynb
deleted file mode 100644
index 27fdd170..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_07/Period1/2024-09-23-unit_7_p1-homepage.ipynb
+++ /dev/null
@@ -1,58 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "raw",
- "metadata": {
- "vscode": {
- "languageId": "raw"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "toc: true\n",
- "title: Unit 7 ArrayLists P1 \n",
- "description: ArrayLists Home Page\n",
- "authors: Aidan Lau, Saathvik Gampa, Sri Surapaneni, Tanav Kambhampati\n",
- "categories: [AP CSA]\n",
- "courses: {'csa': {'week': 6}}\n",
- "type: ccc\n",
- "permalink: /csa/unit7-p1/unit7-homepage\n",
- "menu: nav/CSA_Units/csa_unit7_p1.html\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## AP Computer Science A - Unit 6 Home Page\n",
- "### Main Idea\n",
- "> ** ArrayLists are used to store data and algorithms and can be used to access, traverse, and sort through this data.**\n",
- "### Why ArrayLists?\n",
- "> ArrayLists don't have a fixed size like Arrays and we can add and remove items from them, making them more verstaile and having more functions\n",
- "### Key Topics:\n",
- "Topic 7.1 - Intro to Arraylists (Sri)\n",
- "Topic 7.2 - Methods with Arraylists (Sri & Saathvik)\n",
- "Topic 7.3 - Traversing ArrayLists (Tanav)\n",
- "Topic 7.4 - Developing Algorithms Using ArrayLists (Tanav)\n",
- "Topic 7.5 - Searching (Aidan)\n",
- "Topic 7.6 - Sorting (Aidan)\n",
- "Topic 7.7 - Ethical Issues Around Data Collection (Saathvik)\n",
- "### AP Exam Details\n",
- "- 2.5-7.5% of the test\n",
- "- 1 to 2 mc questions\n",
- "- Might be on an FRQ (making ArrayLists and ArrayList algorithms)\n",
- "\n",
- " "
- ]
- }
- ],
- "metadata": {
- "language_info": {
- "name": "python"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_07/Period3/2024-09-10-Unit7TeamTeach_Ethics.ipynb b/_notebooks/CSA/units_1_to_10/unit_07/Period3/2024-09-10-Unit7TeamTeach_Ethics.ipynb
deleted file mode 100644
index f6da9695..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_07/Period3/2024-09-10-Unit7TeamTeach_Ethics.ipynb
+++ /dev/null
@@ -1,92 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "source": [
- "---\n",
- "layout: post\n",
- "toc: true\n",
- "title: Unit 7 ArrayList P3 \n",
- "description: A Unit of documents that overview Array Lists in Java\n",
- "authors: Drishya, Arnav, Tanuj, Jason\n",
- "categories: [AP CSA]\n",
- "# courses: {'csa': {'week': 6}}\n",
- "type: ccc\n",
- "permalink: /csa/unit7-p3/unit7-5\n",
- "menu: nav/CSA_Units/csa_unit7_p3.html\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# 7.7:Ethical issues around data collection"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "- **Privacy Risks**: Personal data can be vulnerable to breaches or misuse when stored in systems. Programmers need to protect it.\n",
- " \n",
- "- **Protection Methods**:\n",
- " - **Delete Data**: Remove personal info when it’s no longer needed.\n",
- " - **Minimize Data**: Only collect essential information.\n",
- " - **Anonymize Data**: Use methods like `hashCode()` in Java to hide real info.\n",
- " - **Encrypt**: Secure data so it can’t be easily accessed even if stolen.\n",
- "\n",
- "The main goal? Keep personal data safe with smart coding practices."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# 7th mini Hack:\n",
- "What can be used in place of the blank to ensure the users data is cleared?"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "ArrayList userData = new ArrayList<>();\n",
- "userData.add(\"John Doe\");\n",
- "userData.add(\"john@example.com\");\n",
- "\n",
- "// Once you're done using the data\n",
- "userData.clear(); // Removes all entries\n",
- "userData = _____; //"
- ]
- }
- ],
- "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": "17.0.12+7"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_07/Period3/2024-09-10-Unit7TeamTeach_Searching&algorithms.ipynb b/_notebooks/CSA/units_1_to_10/unit_07/Period3/2024-09-10-Unit7TeamTeach_Searching&algorithms.ipynb
deleted file mode 100644
index 6eca3535..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_07/Period3/2024-09-10-Unit7TeamTeach_Searching&algorithms.ipynb
+++ /dev/null
@@ -1,342 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "layout: post\n",
- "toc: true\n",
- "title: Unit 7 ArrayList P3 \n",
- "description: A Unit of documents that overview Array Lists in Java\n",
- "authors: Drishya, Arnav, Tanuj, Jason\n",
- "categories: [AP CSA]\n",
- "# courses: {'csa': {'week': 6}}\n",
- "type: ccc\n",
- "permalink: /csa/unit7-p3/unit7-3\n",
- "menu: nav/CSA_Units/csa_unit7_p3.html\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 7.4 DEVELOPING ALGORITHMS USING ARRAY LISTS\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Essential Knowledge\n",
- "\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.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "List list1 = new ArrayList();\n",
- "list1.add(new Integer(1));\n",
- "list1.add(new Integer(2));\n",
- "list1.add(new Integer(3));\n",
- "list1.remove(1);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "A. [2, 3]\n",
- "\n",
- "B. [1, 2, 3]\n",
- "\n",
- "C. [1, 2]\n",
- "\n",
- "D. [1, 3]"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "List numList = new ArrayList();\n",
- "numList.add(new Integer(1));\n",
- "numList.add(new Integer(2));\n",
- "numList.add(new Integer(3));\n",
- "numList.set(2,new Integer(4));\n",
- "numList.add(1, new Integer(5));\n",
- "numList.add(new Integer(6));"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "A. [1, 2, 3, 4, 5]\n",
- "\n",
- "B. [1, 2, 4, 5, 6]\n",
- "\n",
- "C. [1, 2, 5, 4, 6]\n",
- "\n",
- "D. [1, 5, 2, 4, 6]"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class ArrayListExample {\n",
- "\n",
- " private double getMax(double[] numbers) {\n",
- " double highest = numbers[0];\n",
- " for (double num : numbers) {\n",
- " if (num > highest) {\n",
- " highest = num;\n",
- " }\n",
- " }\n",
- " return highest;\n",
- " }\n",
- "\n",
- " public static void main(String[] args) {\n",
- " double[] nums = {1.0, 3.8, 2.0, 2.0, 1.9, 70.2, 2.0, 4.0, 6.3, 2.1, 5.0, 10.7};\n",
- " ArrayListExample instance = new ArrayListExample();\n",
- " System.out.println(instance.getMax(nums));\n",
- " }\n",
- "}\n",
- "\n",
- "ArrayListExample.main(null);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "When you look at the code above you should pay attention to the getMax() method. What the method is doing is it accepts a list of doubles as input and then uses a for loop to determine the highest value in the list."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Now instead of using just a List of Doubles, lets use an ArrayList of Doubles. "
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "\n",
- "public class ArrayListExample {\n",
- "\n",
- " private double getMax(ArrayList numbers) {\n",
- " double highest = numbers.get(0);\n",
- " for (double num : numbers) {\n",
- " if (num > highest) {\n",
- " highest = num;\n",
- " }\n",
- " }\n",
- " return highest;\n",
- " }\n",
- "\n",
- " public static void main(String[] args) {\n",
- " ArrayList nums = new ArrayList<>(Arrays.asList(1.0, 3.8, 2.0, 2.0, 1.9, 70.2, 2.0, 4.0, 6.3, 2.1, 5.0, 10.7));\n",
- " ArrayListExample instance = new ArrayListExample();\n",
- " System.out.println(instance.getMax(nums));\n",
- " }\n",
- "}\n",
- "\n",
- "ArrayListExample.main(null);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Finish the code below so that it uses the findSum() method and it finds the sum of the numbers. "
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class ArrayListHacks {\n",
- " private int findSum(ArrayList values) {\n",
- " // Your code here\n",
- " return 0;\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"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## We will be learning about Sequential Searching but also known as Linear Searching. \n",
- "\n",
- "Linear search looks for a value in unsorted data by checking each element in order that the data is in. It then returns the index if found, or -1 if the value isn’t in the list."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class ArraySearcher {\n",
- "\n",
- " public static int sequentialSearch(int[] elements, int target) {\n",
- " for (int j = 0; j < elements.length; j++) {\n",
- " if (elements[j] == target) {\n",
- " return j;\n",
- " }\n",
- " }\n",
- " return -1;\n",
- " }\n",
- "\n",
- " public static void main(String[] args) {\n",
- " int[] numArray = {3, -2, 9, 38, -23};\n",
- " System.out.println(\"Tests of sequentialSearch\");\n",
- " System.out.println(sequentialSearch(numArray, 3)); \n",
- " System.out.println(sequentialSearch(numArray, 9)); // Expected output: 2\n",
- " System.out.println(sequentialSearch(numArray, -23)); // Expected output: 4\n",
- " System.out.println(sequentialSearch(numArray, 99)); // Expected output: -1\n",
- " }\n",
- "}\n",
- "\n",
- "\n",
- "ArraySearcher.main(null);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "You can also look for a String in an array or list, but be sure to use equals rather than ==. Remember that == is only true when the two references refer to the same String object, while equals returns true if the characters in the two String objects are the same.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "vscode": {
- "languageId": "java"
- }
- },
- "outputs": [],
- "source": [
- "public class SearchTest\n",
- "{\n",
- "\n",
- " public static int sequentialSearch(String[] elements, String target)\n",
- " {\n",
- " for (int j = 0; j < elements.length; j++)\n",
- " {\n",
- " if (elements[j].equals(target))\n",
- " {\n",
- " return j;\n",
- " }\n",
- " }\n",
- " return -1;\n",
- " }\n",
- "\n",
- " public static void main(String[] args)\n",
- " {\n",
- " String[] arr1 = {\"blue\", \"red\", \"purple\", \"green\"};\n",
- "\n",
- " // test when the target is in the array\n",
- " int index = sequentialSearch(arr1, \"red\");\n",
- " System.out.println(index);\n",
- "\n",
- " // test when the target is not in the array\n",
- " index = sequentialSearch(arr1, \"pink\");\n",
- " System.out.println(index);\n",
- " }\n",
- "}\n",
- "\n",
- "SearchTest.main(null)\n"
- ]
- }
- ],
- "metadata": {
- "language_info": {
- "name": "python"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_07/Period3/2024-09-10-Unit7TeamTeach_Sorting.ipynb b/_notebooks/CSA/units_1_to_10/unit_07/Period3/2024-09-10-Unit7TeamTeach_Sorting.ipynb
deleted file mode 100644
index 952d78ca..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_07/Period3/2024-09-10-Unit7TeamTeach_Sorting.ipynb
+++ /dev/null
@@ -1,344 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "layout: post\n",
- "toc: true\n",
- "title: Unit 7 ArrayList P3 \n",
- "description: A Unit of documents that overview Array Lists in Java\n",
- "authors: Drishya, Arnav, Tanuj, Jason\n",
- "categories: [AP CSA]\n",
- "# courses: {'csa': {'week': 6}}\n",
- "type: ccc\n",
- "permalink: /csa/unit7-p3/unit7-4\n",
- "menu: nav/CSA_Units/csa_unit7_p3.html\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# **7.6 - ArrayLists, Sorting**\n",
- "\n",
- "## Selection Sort. \n",
- "- The one of the easiest sorts to demonstrate. \n",
- "- 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 stroed at that index and continue. \n",
- "- This implementation uses a helper method to perform the swap operation since variables can hold **only one value at a time**!!!\n",
- "\n",
- "### Let’s use this array as an example: **arr[] = {64, 25, 12, 22, 11}**\n",
- "![picture 1 for selection sortin](https://i.ibb.co/0CLDsNx/Screenshot-2024-09-17-12-39-20.png)\n",
- "![picture 2 for selection sortin](https://i.ibb.co/cLVWs6T/Screenshot-2024-09-17-12-41-30.png)\n",
- "![picture 3 for selection sortin](https://i.ibb.co/T2KjMtR/Screenshot-2024-09-17-12-41-37.png)\n",
- "![picture 4 for selection sortin](https://i.ibb.co/109NWPk/Screenshot-2024-09-17-12-41-42.png)\n",
- "![picture 5 for selection sortin](https://i.ibb.co/h8vhKcQ/Screenshot-2024-09-17-12-41-57.png)\n",
- "\n",
- "\n",
- "\n",
- "\n",
- "## **College Board Example code below...**"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 1,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Sorted array:\n",
- "11 12 22 25 64 "
- ]
- }
- ],
- "source": [
- "public class SelectionSort {\n",
- " public static void main(String[] args) {\n",
- " int[] numbers = {64, 25, 12, 22, 11}; // Example array of numbers\n",
- "\n",
- " // Perform selection sort\n",
- " for (int outerLoop = 0; outerLoop < numbers.length - 1; outerLoop++) {\n",
- " // Start by assuming the current item is the smallest\n",
- " int minIndex = outerLoop;\n",
- "\n",
- " // Check the rest of the array for anything smaller\n",
- " for (int inner = outerLoop + 1; inner < numbers.length; inner++) {\n",
- " // If you find something smaller, update the index\n",
- " if (numbers[inner] < numbers[minIndex]) {\n",
- " minIndex = inner;\n",
- " }\n",
- " }\n",
- "\n",
- " // If the smallest item isn’t already in the right place, swap them\n",
- " if (minIndex != outerLoop) {\n",
- " // Swap numbers[outerLoop] and numbers[minIndex]\n",
- " int temp = numbers[outerLoop];\n",
- " numbers[outerLoop] = numbers[minIndex];\n",
- " numbers[minIndex] = temp;\n",
- " }\n",
- " }\n",
- "\n",
- " // Print the sorted array\n",
- " System.out.println(\"Sorted array:\");\n",
- " for (int num : numbers) {\n",
- " System.out.print(num + \" \");\n",
- " }\n",
- " }\n",
- "}\n",
- "\n",
- "SelectionSort.main(null);\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### How does the swapping actualy happen?\n",
- "- We use swap-item mothod.\n",
- "\n",
- "**Swap Algorithm**"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 2,
- "metadata": {},
- "outputs": [],
- "source": [
- "private void swapItems(int firstIndex, int secondIndex, Object[] arrayOfStuff)\n",
- "{\n",
- " // **thirdHand** temporarily holds the value from firstIndex so it doesn't get lost during the swap\n",
- " Object thirdHand = arrayOfStuff[firstIndex];\n",
- " \n",
- " // Move the value from secondIndex to firstIndex\n",
- " arrayOfStuff[firstIndex] = arrayOfStuff[secondIndex];\n",
- " \n",
- " // Place the value that was originally at firstIndex (stored in thirdHand) into secondIndex\n",
- " arrayOfStuff[secondIndex] = thirdHand;\n",
- "}\n",
- "// First you will see the three parameters as you can see below↓↓↓\n",
- "// **The firstIndex** = The index of the first item to be swapped.\n",
- "// **The secondIndex** = The index of the second item to be swapped.\n",
- "// **arrayOfStuff** = The array where the swapping takes place."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Some common questions:\n",
- "### ***Can an enhanced for loop be used?***\n",
- "- **Answer:** No, The Selection Sort algorithm needs to know the index of the item it is working with.\n",
- "### ***How does the swap occur?***\n",
- "- **Answer:** A third variable is needed to temporarily hold on to the swapped value from the array since variables can only hold one thing at a time."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- " "
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Inserting Sort\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",
- "![picture 1 for inserting sortin](https://media.geeksforgeeks.org/wp-content/uploads/20240802210251/Insertion-sorting.png)\n",
- "- Consider an array having elements : {23, 1, 10, 5, 2}\n",
- "\n",
- "\n",
- "\n",
- "***initial***:\n",
- "- Current element is ***23***\n",
- "- The first element in the array is assumed to be sorted.\n",
- "- The sorted part until ***0th*** index is : ***[23]***\n",
- "\n",
- "***First Pass***:\n",
- "- Compare ***1*** with ***23*** (current element with the sorted part).\n",
- "- Since ***1*** is smaller, insert ***1*** before ***23*** .\n",
- "- The sorted part until ***1st*** index is: ***[1, 23]***\n",
- "\n",
- "***Second Pass***:\n",
- "- Compare ***10*** with ***1*** and ***23*** (current element with the sorted part).\n",
- "- Since ***10*** is greater than ***1*** and smaller than ***23*** , insert ***10*** between ***1*** and ***23*** .\n",
- "- The sorted part until ***2nd*** index is: ***[1, 10, 23]***\n",
- "\n",
- "***Third Pass:***\n",
- "- Compare ***5*** with ***1*** , ***10***, and ***23*** (current element with the sorted part).\n",
- "- Since ***5*** is greater than ***1*** and smaller than ***10*** , insert ***5*** between ***1*** and ***10***\n",
- "- The sorted part until ***3rd*** index is : ***[1, 5, 10, 23]***\n",
- "\n",
- "***Fourth Pass:***\n",
- "- Compare ***2*** with ***1***, ***5***, ***10*** , and ***23*** (current element with the sorted part).\n",
- "- Since ***2*** is greater than ***1*** and smaller than ***5*** insert ***2*** between ***1*** and ***5*** .\n",
- "- The sorted part until ***4th*** index is: ***[1, 2, 5, 10, 23]***\n",
- "\n",
- "***Final Array:***\n",
- "- The sorted array is: ***[1, 2, 5, 10, 23]***"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## **College Board Example code below...**"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 3,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Original list: [23, 1, 10, 5, 2]\n",
- "Sorted list: [1, 2, 5, 10, 23]\n"
- ]
- }
- ],
- "source": [
- "import java.util.ArrayList;\n",
- "\n",
- "public class InsertionSortExample {\n",
- "\n",
- " // Method to perform Insertion Sort on the list\n",
- " public static void insertionSort(ArrayList randomList) {\n",
- " // Loop through each element in the list starting from the second element\n",
- " // (The first element is already considered sorted)\n",
- " for (int outer = 1; outer < randomList.size(); outer++) {\n",
- " \n",
- " // 'tested' is the current element we're trying to place in the correct position\n",
- " int tested = randomList.get(outer);\n",
- " \n",
- " // 'inner' represents the index of the last element in the sorted portion of the list\n",
- " int inner = outer - 1;\n",
- "\n",
- " // Move elements in the sorted part of the list to the right\n",
- " // until we find the correct position for 'tested'\n",
- " while (inner >= 0 && randomList.get(inner) > tested) {\n",
- " // Shift the element one position to the right to make space\n",
- " randomList.set(inner + 1, randomList.get(inner));\n",
- " inner--; // Move the 'inner' pointer to the left\n",
- " }\n",
- "\n",
- " // Place the 'tested' element in its correct position\n",
- " randomList.set(inner + 1, tested);\n",
- " }\n",
- " }\n",
- "\n",
- " public static void main(String[] args) {\n",
- " // Create an ArrayList to store the integers we want to sort\n",
- " ArrayList randomList = new ArrayList<>();\n",
- "\n",
- " // Adding elements {23, 1, 10, 5, 2} to the list\n",
- " randomList.add(23);\n",
- " randomList.add(1);\n",
- " randomList.add(10);\n",
- " randomList.add(5);\n",
- " randomList.add(2);\n",
- "\n",
- " // Print the original list before sorting\n",
- " System.out.println(\"Original list: \" + randomList);\n",
- "\n",
- " // Call the insertionSort method to sort the list\n",
- " insertionSort(randomList);\n",
- "\n",
- " // Print the sorted list after the insertion sort is completed\n",
- " System.out.println(\"Sorted list: \" + randomList);\n",
- " }\n",
- "}\n",
- "\n",
- "InsertionSortExample.main(null);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Another Example..."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# 6th PopCorn - Hack\n",
- "\n",
- "### **Problem: Sort the Ducks!**\n",
- "\n",
- "You have a list of ducks, and each duck has a **name** and **weight**. Your task is to sort these ducks by weight in **ascending order**.\n",
- "\n",
- "Choose **either Selection Sort or Insertion Sort** to do the sorting.\n",
- "\n",
- "### Example:\n",
- "Given this list:\n",
- "- Duck A (4.5 kg)\n",
- "- Duck B (2.1 kg)\n",
- "- Duck C (5.0 kg)\n",
- "- Duck D (1.9 kg)\n",
- "\n",
- "After sorting, the output should be:\n",
- "- Duck D (1.9 kg)\n",
- "- Duck B (2.1 kg)\n",
- "- Duck A (4.5 kg)\n",
- "- Duck C (5.0 kg)\n",
- "\n",
- "You can use this class for the ducks:\n",
- "\n",
- "```java\n",
- "class DebugDuck implements Comparable {\n",
- " String name;\n",
- " double weight;\n",
- "\n",
- " public DebugDuck(String name, double weight) {\n",
- " this.name = name;\n",
- " this.weight = weight;\n",
- " }\n",
- "\n",
- " @Override\n",
- " public int compareTo(DebugDuck other) {\n",
- " return Double.compare(this.weight, other.weight);\n",
- " }\n",
- "\n",
- " @Override\n",
- " public String toString() {\n",
- " return name + \" (\" + weight + \" kg)\";\n",
- " }\n",
- "}\n",
- "```\n",
- "\n",
- "### Task:\n",
- "- Implement **either** sorting algorithm to sort the ducks by weight.\n",
- "- Print the sorted list.\n"
- ]
- }
- ],
- "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": "17.0.12+7"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_07/Period3/2024-09-10-Unit7TeamTeach_hacks.ipynb b/_notebooks/CSA/units_1_to_10/unit_07/Period3/2024-09-10-Unit7TeamTeach_hacks.ipynb
deleted file mode 100644
index fe33fd2a..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_07/Period3/2024-09-10-Unit7TeamTeach_hacks.ipynb
+++ /dev/null
@@ -1,73 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "layout: post\n",
- "toc: true\n",
- "title: Unit 7 ArrayList P3 \n",
- "description: A Unit of documents that overview Array Lists in Java\n",
- "authors: Drishya, Arnav, Tanuj, Jason\n",
- "categories: [AP CSA]\n",
- "# courses: {'csa': {'week': 6}}\n",
- "type: ccc\n",
- "permalink: /csa/unit7-p3/unit7-6\n",
- "menu: nav/CSA_Units/csa_unit7_p3.html\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "vscode": {
- "languageId": "plaintext"
- }
- },
- "source": [
- "## **ArrayList Coding Activity**\n",
- "\n",
- "### **Objective:**\n",
- "Students will create, manipulate, and sort an `ArrayList` of integers.\n",
- "\n",
- "### **Activity Outline:**\n",
- "\n",
- "1. **Create an ArrayList:**\n",
- " - **Task:** Create an `ArrayList` of integers and add 5 elements of your choice.\n",
- " - **Hint:** Use the `ArrayList` class and the `.add()` method to add elements.\n",
- "\n",
- "2. **Modify an Element:**\n",
- " - **Task:** Change the second element (index 1) of the `ArrayList` to a new value (e.g., 100).\n",
- " - **Hint:** The `.set()` method allows you to update an element at a specific index.\n",
- "\n",
- "3. **Remove an Element:**\n",
- " - **Task:** Remove the third element (index 2) from the `ArrayList`.\n",
- " - **Hint:** Use the `.remove()` method to delete an element by its index.\n",
- "\n",
- "4. **Search for an Element:**\n",
- " - **Task:** Check if a specific number (e.g., 30) is in the `ArrayList` and print a message based on whether it is found or not.\n",
- " - **Hint:** The `.contains()` method can be used to check for the presence of an element.\n",
- "\n",
- "5. **Loop Through the ArrayList:**\n",
- " - **Task:** Use a `for` loop to print each element of the `ArrayList`.\n",
- " - **Hint:** You can use a traditional `for` loop or an enhanced `for` loop (`for-each`) to iterate through the elements.\n",
- "\n",
- "6. **Sort the ArrayList:**\n",
- " - **Task:** Sort the `ArrayList` in ascending order.\n",
- " - **Hint:** Use `Collections.sort()` to sort the `ArrayList`.\n",
- "\n",
- "7. **Print the Sorted ArrayList:**\n",
- " - **Task:** Print the sorted `ArrayList` to see the updated order of the elements.\n",
- " - **Hint:** Use `System.out.println()` to print the sorted list.\n"
- ]
- }
- ],
- "metadata": {
- "language_info": {
- "name": "python"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_07/Period3/2024-09-10-Unit7TeamTeach_homePage.ipynb b/_notebooks/CSA/units_1_to_10/unit_07/Period3/2024-09-10-Unit7TeamTeach_homePage.ipynb
deleted file mode 100644
index 4a023c29..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_07/Period3/2024-09-10-Unit7TeamTeach_homePage.ipynb
+++ /dev/null
@@ -1,118 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "layout: post\n",
- "toc: true\n",
- "title: Unit 7 ArrayList P3 \n",
- "description: A Unit of documents that overview Array Lists in Java\n",
- "authors: Drishya, Arnav, Tanuj, Jason\n",
- "categories: [AP CSA]\n",
- "courses: {'csa': {'week': 6}}\n",
- "type: ccc\n",
- "permalink: /csa/unit7-p3/home\n",
- "menu: nav/CSA_Units/csa_unit7_p3.html\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "**UNIT 7: ARRAYLISTS**\n",
- "\n",
- "- 7.1-7.2: Intro and Methods\n",
- "- 7.3: Traversing\n",
- "- 7.4-7.5: Searching & Algorithms\n",
- "- 7.6: Sorting\n",
- "- 7.7: Ethics\n",
- "- **Hacks**"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "\n",
- "\n",
- "\n",
- "\n",
- " \n",
- " \n",
- " ArrayList Bubbles \n",
- " \n",
- "\n",
- "\n",
- " ArrayList Bubbles \n",
- " \n",
- " \n",
- "
\n",
- " \n",
- " Add Bubble \n",
- " Remove Bubble \n",
- " Shuffle Bubbles \n",
- "
\n",
- " \n",
- "\n",
- "\n"
- ]
- }
- ],
- "metadata": {
- "language_info": {
- "name": "python"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/_notebooks/CSA/units_1_to_10/unit_07/Period3/2024-09-10-Unit7TeamTeach_traversing.ipynb b/_notebooks/CSA/units_1_to_10/unit_07/Period3/2024-09-10-Unit7TeamTeach_traversing.ipynb
deleted file mode 100644
index c7a58f6f..00000000
--- a/_notebooks/CSA/units_1_to_10/unit_07/Period3/2024-09-10-Unit7TeamTeach_traversing.ipynb
+++ /dev/null
@@ -1,255 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "layout: post\n",
- "toc: true\n",
- "title: Unit 7 ArrayList P3 \n",
- "description: A Unit of documents that overview Array Lists in Java\n",
- "authors: Drishya, Arnav, Tanuj, Jason\n",
- "categories: [AP CSA]\n",
- "# courses: {'csa': {'week': 6}}\n",
- "type: ccc\n",
- "permalink: /csa/unit7-p3/unit7-2\n",
- "menu: nav/CSA_Units/csa_unit7_p3.html\n",
- "---"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# 7.3: Traversing Arrays"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "functions to traverse an array\n",
- "- variable.get(i): retreives #i value.\n",
- "- variable.remove(i): removes #i value from a list.\n",
- "- variable.size(): retreives length of the array\n",
- "- swapConsecutive(ArrayList myList): swaps items in an ArrayList\n",
- "\n",
- "\n",
- "Possible strategies to iterate through a **for** loop:\n",
- "\n",
- "![Conditions](https://github.com/user-attachments/assets/1a70acbb-d6d8-4a86-b0a5-583b11da8570)\n",
- "\n",
- "regular while loops are syntaxed as follows:\n",
- "\n",
- "![image](https://github.com/user-attachments/assets/a0eb6ae3-6dde-45e5-806b-e71bd608fcb7)\n",
- "\n",
- "\n",
- "removing items within an array -> each item moves up a slot\n",
- "\n",
- "![image](https://github.com/user-attachments/assets/0e67a4fa-52fa-4da3-8968-d803abfbf2e3)\n",
- "\n",
- "Traversing backwards:\n",
- "\n",
- "![image](https://github.com/user-attachments/assets/e05f5ada-57ce-4e2c-bd54-b665c5a57da8)\n",
- "\n",
- "\n",
- "traversing using and enhanced for loop\n",
- " known as *for-each*\n",
- " goes from first to last order in an ArrayList\n",
- " easier to setup than for loop\n",
- "structure consists of:\n",
- "\n",
- "![image](https://github.com/user-attachments/assets/b47f5c6b-0509-40f2-b18e-ee9aae37a6b3)\n",
- "\n",
- "\n",
- "Using a for each loop for same objective as before:\n",
- "\n",
- "![image](https://github.com/user-attachments/assets/b7dd7f81-0c7e-4be8-a3bb-a726ba8867b5)\n",
- "\n",
- "**Notes:** \n",
- "- Adding items to a for each loop will result in an exception\n",
- "- modifying or adding items will not effect the Arraylist.\n",
- " Results in ConcurrentModificationException\n",
- "- attempting to access an item outside of the Array bounds results in: ArrayIndexOutOfBoundsException\n",
- "\n",
- "use this to make sure you can traverse ArrayLists"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "import java.util.ArrayList"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "\n",
- "\n",
- " Quick Quiz \n",
- " \n",
- "\n",
- "
\n",
- " \n",
- "\n",
- "\n",
- "\n",
- "\n",
- "