From 0ac3930431358f7175959aa68e638f34cbc29a81 Mon Sep 17 00:00:00 2001 From: elena5100 <194572363+elena5100@users.noreply.github.com> Date: Wed, 15 Jan 2025 13:21:40 -0800 Subject: [PATCH 1/2] homework --- src/ArrayPractice.java | 37 +++++++++----- src/ListPractice.java | 80 +++++++++++++++++------------- src/MapPractice.java | 58 ++++++++++++++++------ src/NumberPractice.java | 41 ++++++++++------ src/Person.java | 106 ++++++++++++++++++++++------------------ src/SetPractice.java | 56 +++++++++++++-------- src/StringPractice.java | 85 ++++++++++++++++++++------------ toRefresh.md | 11 +++++ 8 files changed, 298 insertions(+), 176 deletions(-) diff --git a/src/ArrayPractice.java b/src/ArrayPractice.java index bc58c83..49479f9 100644 --- a/src/ArrayPractice.java +++ b/src/ArrayPractice.java @@ -1,22 +1,33 @@ + + public class ArrayPractice { public static void main(String[] args) { - // Create an array of Strings of size 4 + // Create an array of Strings of size 4 + String[] fruits = new String[4]; - // Set the value of the array at each index to be a different String - // It's OK to do this one-by-one + // Set the value of the array at each index to be a different String + fruits[0] = "Apple"; + fruits[1] = "Banana"; + fruits[2] = "Cherry"; + fruits[3] = "Date"; - // Get the value of the array at index 2 + // Get the value of the array at index 2 + System.out.println("Element at index 2: " + fruits[2]); // Expected: Cherry - // Get the length of the array + // Get the length of the array + System.out.println("Length of the array: " + fruits.length); // Expected: 4 - // Iterate over the array using a traditional for loop and print out each item + // Iterate over the array using a traditional for loop and print out each item + System.out.println("Using traditional for loop:"); + for (int i = 0; i < fruits.length; i++) { + System.out.println(fruits[i]); // Prints each fruit + } - // Iterate over the array using a for-each loop and print out each item - - /* - * Reminder! - * - * Arrays start at index 0 - */ + // Iterate over the array using a for-each loop and print out each item + System.out.println("Using for-each loop:"); + for (String fruit : fruits) { + System.out.println(fruit); // Prints each fruit + } } } + diff --git a/src/ListPractice.java b/src/ListPractice.java index f4de8e7..81b6e2c 100644 --- a/src/ListPractice.java +++ b/src/ListPractice.java @@ -1,36 +1,48 @@ +import java.util.ArrayList; +import java.util.List; +import java.util.Collections; public class ListPractice { - - public static void main(String[] args) { - // Create an empty ArrayList of Strings and assign it to a variable of type List - - // Add 3 elements to the list (OK to do one-by-one) - - // Print the element at index 1 - - // Replace the element at index 1 with a new value - // (Do not insert a new value. The length of the list should not change) - - // Insert a new element at index 0 (the length of the list will change) - - // Check whether the list contains a certain string - - // Iterate over the list using a traditional for-loop. - // Print each index and value on a separate line - - // Sort the list using the Collections library - - // Iterate over the list using a for-each loop - // Print each value on a second line - - /* - * Usage tip! - * - * Use a traditional for-loop when you need to use the index or you need to iterate in an - * unconventional order (e.g. backwards) - * - * Otherwise, if you're iterating the in the conventional order and don't need the - * index values a for-each loop is cleaner. - */ - } -} \ No newline at end of file + public static void main(String[] args) { + // Create an empty ArrayList of Strings and assign it to a variable of type List + List myList = new ArrayList<>(); + + // Add 3 elements to the list (OK to do one-by-one) + myList.add("Apple"); + myList.add("Banana"); + myList.add("Cherry"); + + // Print the element at index 1 + System.out.println("Element at index 1: " + myList.get(1)); // Expected: Banana + + // Replace the element at index 1 with a new value + myList.set(1, "Grapes"); // Replaces "Banana" with "Grapes" + System.out.println("List after replacement: " + myList); // Expected: [Apple, Grapes, Cherry] + + // Insert a new element at index 0 (the length of the list will change) + myList.add(0, "Orange"); // Inserts "Orange" at the beginning + System.out.println("List after insertion: " + myList); // Expected: [Orange, Apple, Grapes, Cherry] + + // Check whether the list contains a certain string + boolean containsApple = myList.contains("Apple"); + System.out.println("Does the list contain 'Apple'? " + containsApple); // Expected: true + + // Iterate over the list using a traditional for-loop. + // Print each index and value on a separate line + System.out.println("Using traditional for-loop:"); + for (int i = 0; i < myList.size(); i++) { + System.out.println("Index " + i + ": " + myList.get(i)); // Prints index and value + } + + // Sort the list using the Collections library + Collections.sort(myList); // Sorts the list alphabetically + System.out.println("List after sorting: " + myList); // Expected: [Apple, Cherry, Grapes, Orange] + + // Iterate over the list using a for-each loop + // Print each value on a second line + System.out.println("Using for-each loop:"); + for (String item : myList) { + System.out.println(item); // Prints each value on a new line + } + } +} diff --git a/src/MapPractice.java b/src/MapPractice.java index 7ebfeac..9ba9f81 100644 --- a/src/MapPractice.java +++ b/src/MapPractice.java @@ -1,28 +1,58 @@ - +import java.util.HashMap; +import java.util.Map; public class MapPractice { - public static void main(String[] args) { - // Create a HashMap with String keys and Integer values and - // assign it to a variable of type Map - // Put 3 different key/value pairs in the Map - // (it's OK to do this one-by-one) + // Method to create and return a Map + public static Map createMap() { + Map ages = new HashMap<>(); + ages.put("Elena", 27); + ages.put("Demon", 30); + ages.put("Shams", 23); + return ages; + } + + public static void main(String[] args) { + // Create the map and populate it + Map myMap = createMap(); + + // Get the value associated with a given key in the Map + System.out.println("Age of Elena: " + myMap.get("Elena")); + + // Find the size (number of key/value pairs) of the Map + System.out.println("Size of the map: " + myMap.size()); + // Replace the value associated with a given key + myMap.put("Demon", 31); // Changing Demon’s age to 31 + System.out.println("Updated map: " + myMap); - // Get the value associated with a given key in the Map + // Check whether the Map contains a given key + System.out.println("Does the map contain 'Shams'? " + myMap.containsKey("Shams")); - // Find the size (number of key/value pairs) of the Map + // Check whether the Map contains a given value + System.out.println("Does the map contain the value 30? " + myMap.containsValue(30)); - // Replace the value associated with a given key (the size of the Map shoukld not change) + // Iterate over the keys of the Map, printing each key + System.out.println("Keys in the map:"); + for (String key : myMap.keySet()) { + System.out.println(key); + } - // Check whether the Map contains a given key + // Iterate over the values of the map, printing each value + System.out.println("Values in the map:"); + for (Integer value : myMap.values()) { + System.out.println(value); + } - // Check whether the Map contains a given value + // Iterate over the entries in the map, printing each key and value + System.out.println("Entries in the map (key and value):"); + for (Map.Entry entry : myMap.entrySet()) { + System.out.println(entry.getKey() + ": " + entry.getValue()); + } + + - // Iterate over the keys of the Map, printing each key - // Iterate over the values of the map, printing each value - // Iterate over the entries in the map, printing each key and value /* * Usage tip! diff --git a/src/NumberPractice.java b/src/NumberPractice.java index bbec2fe..0ad6225 100644 --- a/src/NumberPractice.java +++ b/src/NumberPractice.java @@ -1,25 +1,34 @@ public class NumberPractice { public static void main(String args[]) { - // Create a float with a negative value and assign it to a variable + // Create a float with a negative value and assign it to a variable + float negativeFloat = -5.7f; + System.out.println("Negative float value: " + negativeFloat); // Using the variable - // Create an int with a positive value and assign it to a variable + // Create an int with a positive value and assign it to a variable + int positiveInt = 10; - // Use the modulo % operator to find the remainder when the int is divided by 3 + // Use the modulo % operator to find the remainder when the int is divided by 3 + int remainder = positiveInt % 3; + System.out.println("Remainder when " + positiveInt + " is divided by 3: " + remainder); - // Use the modulo % operator to determine whether the number is even - // (A number is even if it has a remainder of zero when divided by 2) - // Use an if-else to print "Even" if the number is even and "Odd" - // if the number is odd. + // Use the modulo % operator to determine whether the number is even + // A number is even if it has a remainder of zero when divided by 2 + if (positiveInt % 2 == 0) { + System.out.println(positiveInt + " is Even"); + } else { + System.out.println(positiveInt + " is Odd"); + } - // Divide the number by another number using integer division - - /* - * Reminder! - * - * When dividing ints, the result is rounded down. - * Example: - * 7 / 3 = 2 when performing int division - */ + // Divide the number by another number using integer division + int result = positiveInt / 3; + System.out.println("Result of integer division of " + positiveInt + " by 3: " + result); + /* + * Reminder! + * + * When dividing ints, the result is rounded down. + * Example: + * 7 / 3 = 2 when performing int division + */ } } diff --git a/src/Person.java b/src/Person.java index 8ab3f95..f53c4b1 100644 --- a/src/Person.java +++ b/src/Person.java @@ -1,66 +1,76 @@ -/* - * In this file you will follow the comments' instructions to complete - * the Person class. - */ - public class Person { // Declare a public String instance variable for the name of the person - // Declare a private int instance variable for the age of the person - + public String name; - // Create a constructor that takes the name and age of the person - // and assigns it to the instance variables + // Declare a private int instance variable for the age of the person + private int age; + // Create a constructor that takes the name and age of the person and assigns it to the instance variables + public Person(String name, int age) { + this.name = name; + this.age = age; + } // Create a toString method that gives the name and age of the person + @Override + public String toString() { + // This method returns a string that represents the Person object with their name and age + return name + " (" + age + " years old)"; + } - - // Implement the below public instance method "birthYear" - // There should NOT be any print statement in this method. + // Implement the public instance method "birthYear" + // This method returns the year the person was born /** * birthYear returns the year the person was born. * - * The birth year is calculated by subtracting the person's age from currentYear + * The birth year is calculated by subtracting the person's age from the currentYear * that's passed in as an int. It assumes that the person's birthday has already * passed this year. * * @param currentYear an int for the current year * @return The year the person was born */ - // (create the instance method here) - + public int birthYear(int currentYear) { + // Calculate the birth year by subtracting the person's age from the current year + return currentYear - age; + } public static void main(String[] args) { - // Create an instance of Person - - // Create another instance of Person with a different name and age and - // assign it to a different variable - - // Print the first person - - // Print the second person - - // Get the name of the first person and store it in a local variable - - // Using the birthYear method, get the birth year of the first person - // and store it in a local variable. Input the actual current year (e.g. 2025) - // as the argument. - - // In a separate statement, print the local variable holding the birth year. - - /** - * Terminology! - * - * A class is the overall definition, like a blueprint. - * An instance is a specific object made according to that definition. - * We use "instance" and "object" to mean the same thing. - * - * For example, if there is a Person class, we can make an instance of a specific person: Auberon. - * - * There can be many instances for the same class. For example: Auberon, Xinting, Baya are all - * different instances of the Person class. - * - * Each instance has its own instance variables: Auberon's age can be different from Baya's age. - */ - } -} + // Create an instance of Person with the name "Elena" and age 27 + Person person1 = new Person("Elena", 27); + + // Create another instance of Person with a different name and age + Person person2 = new Person("Demon", 30); + + // Print the first person (calls toString method) + System.out.println(person1); // This will print: Elena (27 years old) + + // Print the second person (calls toString method) + System.out.println(person2); // This will print: John (30 years old) + + // Get the name of the first person and store it in a local variable + String personName = person1.name; // personName will be "Elena" + + // Using the birthYear method, get the birth year of the first person + // and store it in a local variable. Input the current year (e.g., 2025) as the argument. + int birthYearOfPerson1 = person1.birthYear(2025); + + // In a separate statement, print the local variable holding the birth year. + System.out.println(personName + "'s birth year: " + birthYearOfPerson1); // This will print: Elena's birth year: 1998 + + /** + * Terminology! + * + * A class is the overall definition, like a blueprint. + * An instance is a specific object made according to that definition. + * We use "instance" and "object" to mean the same thing. + * + * For example, if there is a Person class, we can make an instance of a specific person: Auberon. + * + * There can be many instances for the same class. For example: Auberon, Xinting, Baya are all + * different instances of the Person class. + * + * Each instance has its own instance variables: Auberon's age can be different from Baya's age. + */ + } +} diff --git a/src/SetPractice.java b/src/SetPractice.java index d2fc1c9..10f0584 100644 --- a/src/SetPractice.java +++ b/src/SetPractice.java @@ -1,29 +1,43 @@ +import java.util.HashSet; +import java.util.Set; + public class SetPractice { - public static void main(String[] args) { - // Create a HashSet of Strings and assign it to a variable of type Set + public static void main(String[] args) { + // Create a HashSet of Strings and assign it to a variable of type Set + Set mySet = new HashSet<>(); - // Add 3 elements to the set - // (It's OK to do it one-by-one) + // Add 3 elements to the set (It's OK to do it one-by-one) + mySet.add("Strawberry"); + mySet.add("Grape"); + mySet.add("Banana"); - // Check whether the Set contains a given String + // Check whether the Set contains a given String + System.out.println("Does the set contain 'Strawberry'? " + mySet.contains("Strawberry")); // Expected: true + System.out.println("Does the set contain 'Apple'? " + mySet.contains("Apple")); // Expected: false - // Remove an element from the Set + // Remove an element from the Set + mySet.remove("Grape"); // Removes "Grape" from the set + System.out.println("Set after removing 'Grape': " + mySet); - // Get the size of the Set + // Get the size of the Set + System.out.println("Size of the set: " + mySet.size()); // Expected: 2 - // Iterate over the elements of the Set, printing each one on a separate line + // Iterate over the elements of the Set, printing each one on a separate line + System.out.println("Elements in the set:"); + for (String fruit : mySet) { + System.out.println(fruit); // Prints each fruit on a separate line + } - /* - * Warning! - * - * The iteration order over the items in a HashSet is NOT GUARANTEED. - * - * Even running the exact same program multiple times may give different results. - * Do not use a HashSet if order is important! You can use a TreeSet if you - * want items in sorted order, or an array or List if you want them in a specified - * order. - * - * Also remember that sets do NOT have duplicates. - */ - } + /* + * Warning! + * + * The iteration order over the items in a HashSet is NOT GUARANTEED. + * Even running the exact same program multiple times may give different results. + * Do not use a HashSet if order is important! You can use a TreeSet if you + * want items in sorted order, or an array or List if you want them in a specified + * order. + * + * Also remember that sets do NOT have duplicates. + */ + } } diff --git a/src/StringPractice.java b/src/StringPractice.java index 8d87617..8d90d05 100644 --- a/src/StringPractice.java +++ b/src/StringPractice.java @@ -1,32 +1,57 @@ -public class StringPractice { - public static void main(String[] args) { - // Create a string with at least 5 characters and assign it to a variable - - // Find the length of the string - - // Concatenate (add) two strings together and reassign the result - - // Find the value of the character at index 3 - - // Check whether the string contains a given substring (i.e. does the string have "abc" in it?) - - // Iterate over the characters of the string, printing each one on a separate line +import java.util.ArrayList; +import java.util.List; - // Create an ArrayList of Strings and assign it to a variable - - // Add multiple strings to the List (OK to do one-by-one) - - // Join all of the strings in the list together into a single string separated by commas - // Use a built-in method to achieve this instead of using a loop - - // Check whether two strings are equal - - /* - * Reminder! - * - * When comparing objects in Java we typically want to use .equals, NOT ==. - * - * We use == when comparing primitives (e.g. int or char). - */ - } +public class StringPractice { + public static void main(String[] args) { + // Create a string with at least 5 characters and assign it to a variable + String original = "Shams love Java"; + + // Find the length of the string + int length = original.length(); + System.out.println("Length of the string: " + length); + + // Concatenate (add) two strings together and reassign the result + String additionalText = " and more!"; + original = original + additionalText; // Concatenation + System.out.println("Concatenated string: " + original); + + // Find the value of the character at index 3 + char charAtIndex3 = original.charAt(3); + System.out.println("Character at index 3: " + charAtIndex3); + + // Check whether the string contains a given substring + boolean containsSubstring = original.contains("Java"); + System.out.println("Does the string contain 'Java'? " + containsSubstring); + + // Iterate over the characters of the string, printing each one on a separate line + System.out.println("Characters in the string:"); + for (int i = 0; i < original.length(); i++) { + System.out.println(original.charAt(i)); // Prints each character on a separate line + } + + // Create an ArrayList of Strings and assign it to a variable + List fruits = new ArrayList<>(); + + // Add multiple strings to the List (OK to do one-by-one) + fruits.add("Apple"); + fruits.add("Banana"); + fruits.add("Cherry"); + + // Join all of the strings in the list together into a single string separated by commas + String joinedFruits = String.join(", ", fruits); + System.out.println("Joined fruits: " + joinedFruits); + + // Check whether two strings are equal + String anotherString = "Shams love Java and more!"; + boolean areEqual = original.equals(anotherString); + System.out.println("Are the two strings equal? " + areEqual); + + /* + * Reminder! + * + * When comparing objects in Java we typically want to use .equals, NOT ==. + * + * We use == when comparing primitives (e.g. int or char). + */ + } } diff --git a/toRefresh.md b/toRefresh.md index 163dcab..536c687 100644 --- a/toRefresh.md +++ b/toRefresh.md @@ -2,4 +2,15 @@ As you work through this exercise, write down anything that you needed to look up or struggled to remember here. It can be just a word or two (e.g. "joining strings"). You can use this as a guide of what to make extra sure you're refreshed on before exams and interviews. + + How to use `ArrayList` methods (e.g., add, remove, contains). +- Difference between `HashMap` and `TreeMap`. +Removing duplicates using a HashSet. +- String methods: substring, indexOf, split. +-Arrays... +Finding the largest/smallest element in an array. +Sorting arrays using Arrays.sort(). +-Maps:Common HashMap methods (put, get, containsKey). + + - \ No newline at end of file From 9c71d66839ac470bb9655538d4959a755736aada Mon Sep 17 00:00:00 2001 From: elena5100 <194572363+elena5100@users.noreply.github.com> Date: Wed, 15 Jan 2025 13:23:23 -0800 Subject: [PATCH 2/2] testing terminal --- test | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 test diff --git a/test b/test new file mode 100644 index 0000000..e69de29