From 5c3e2259bb1a4e31adca41e0818b3bca882daa51 Mon Sep 17 00:00:00 2001 From: Jobonsu4 Date: Wed, 23 Jul 2025 14:26:13 -0400 Subject: [PATCH 1/8] for loop --- java-org/classes-and-objects/NOTES.md | 16 +- java-org/classes-and-objects/topic.jsh | 265 ++++++++++++++++---- method-writing/bool-and-boolean/topic.jsh | 40 +-- method-writing/double-and-double/topic.jsh | 95 +++++-- method-writing/for-loops/topic.jsh | 35 ++- method-writing/if-else-statements/topic.jsh | 44 +++- method-writing/integer-and-int/topic.jsh | 107 +++++++- method-writing/while-loops/topic.jsh | 78 +++++- 8 files changed, 548 insertions(+), 132 deletions(-) diff --git a/java-org/classes-and-objects/NOTES.md b/java-org/classes-and-objects/NOTES.md index 2efd16f..b96e6e9 100644 --- a/java-org/classes-and-objects/NOTES.md +++ b/java-org/classes-and-objects/NOTES.md @@ -202,21 +202,9 @@ class Thing { ### Single Responsibility Each class should have one clear purpose: -```java -// Good - Person class handles person data -class Person { - String name; - int age; - public String introduce() { ... } -} - -// Good - BankAccount class handles banking operations -class BankAccount { - double balance; - public void deposit(double amount) { ... } -} +`optopo=t ``` - +t ## Common Patterns ### State and Behavior Together diff --git a/java-org/classes-and-objects/topic.jsh b/java-org/classes-and-objects/topic.jsh index 9957b66..1f1a891 100644 --- a/java-org/classes-and-objects/topic.jsh +++ b/java-org/classes-and-objects/topic.jsh @@ -1,87 +1,164 @@ -// Classes and Objects Exercises - Complete the classes and methods below -// Save this file and load it in jshell with: /open topic.jsh + //Classes and Objects Exercises - Complete the classes and methods below + //Save this file and load it in jshell with: /open topic.jsh import java.util.ArrayList; // Exercise 1: Basic Class Creation // Create a Person class with name and age fields class Person { - // Your fields here - - // Your constructor here - - // Your introduce() method here + String name; + int age; + + + public Person(String name, int age) { + this.name = name; + this.age = age; + } + + public String introduce() { + return "Hello, I'm " + name + " and I'm " + age + " years old."; + } + + } + + + // Exercise 2: Class with Methods -// Create a BankAccount class with account operations class BankAccount { - // Your fields here - - // Your constructor here - - // Your deposit method here - - // Your withdraw method here - - // Your getBalance method here - - // Your getAccountInfo method here - + String accountNumber; + double balance; + + + public BankAccount(String accountNumber) { + this.accountNumber = accountNumber; + this.balance = 0.0; + } + public void deposit(double amount) { + if (amount > 0) { + balance += amount; + } else { + System.out.println("Deposit amount must be positive."); + } + } + + + public boolean withdraw(double amount) { + if (amount > 0 && balance >= amount) { + balance -= amount; + return true; + } else { + System.out.println("Insufficient funds or invalid amount."); + return false; + } + } + + + public double getBalance() { + return balance; + } + + + public String getAccountInfo() { + return "Account Number: " + accountNumber + ", Balance: $" + balance; + } } -// Exercise 3: Object Creation and Usage -// Create and return a Person object + +//Exercise 3: Object Creation and Usage +// Creates and returns a Person object public Person createPerson(String name, int age) { - // Your code here - + return new Person(name, age); } -// Create and return a BankAccount object +// Creates and returns a BankAccount object public BankAccount createBankAccount(String accountNumber) { - // Your code here - + return new BankAccount(accountNumber); } -// Demonstrate creating and using a Person object +// Demonstrates creating and using a Person object public void demonstratePersonUsage() { - // Your code here - + Person person = createPerson("Alice", 30); + String intro = person.introduce(); + System.out.println(intro); } + + // Exercise 4: Working with Multiple Objects // Create a Car class class Car { // Your fields here + String brand; + String model; + int year; // Your constructor here - + public Car(String brand, String model, int year) { + this.brand = brand; + this.model = model; + this.year = year; + } // Your getCarInfo method here + public String getCarInfo() { + return brand + " " + model + " (" + year + ")"; + } + // Your isClassic method here (car is classic if > 25 years old) - + public boolean isClassic() { + int currentYear = java.time.Year.now().getValue(); // Get current year + return (currentYear - year) > 25; +} } // Compare two cars and return which is older public Car compareCars(Car car1, Car car2) { // Your code here - + if (car1.year < car2.year) { + return car1; + } else if (car2.year < car1.year) { + return car2; + } else { + return null; // Both cars are the same year + } } + + // Exercise 5: Object State and Behavior // Create a Counter class that can increment/decrement class Counter { // Your fields here + private int count; + // Your constructor here + public Counter() { + this.count = 0; + } // Your increment method here + public void increment() { + count++; + } + // Your decrement method here + public void decrement() { + count--; + } // Your reset method here + public void reset() { + count = 0; + } // Your getCount method here + public int getCount() { + return count; + } } @@ -89,12 +166,40 @@ class Counter { // Create a Student class with input validation class Student { // Your fields here + private String name; + private int grade; + private double gpa; + // Your constructor with validation here + public Student(String name, int grade, double gpa) { + if (name == null || name.trim().isEmpty()) { + throw new IllegalArgumentException("Name cannot be null or empty."); + } + + if (grade < 1 || grade > 12) { + throw new IllegalArgumentException("Grade must be between 1 and 12."); + } + + if (gpa < 0.0 || gpa > 4.0) { + throw new IllegalArgumentException("GPA must be between 0.0 and 4.0."); + } + + this.name = name; + this.grade = grade; + this.gpa = gpa; + } // Your isHonorStudent method here + public boolean isHonorStudent() { + return gpa >= 3.5; + } + // Your getStudentInfo method here + public String getStudentInfo() { + return "Name: " + name + ", Grade: " + grade + ", GPA: " + gpa; + } } @@ -102,31 +207,97 @@ class Student { // Create a Book class class Book { // Your fields here - - // Your constructor here - + class Book { + String title; + String author; + boolean isCheckedOut; + + // Your constructor here + public Book(String title, String author) { + this.title = title; + this.author = author; + this.isCheckedOut = false; // default: available + } + + // Add any helpful methods here - + public void checkOut() { + isCheckedOut = true; + } + + public void returnBook() { + isCheckedOut = false; + } + + public boolean isAvailable() { + return !isCheckedOut; + } + + public String getInfo() { + return title + " by " + author + (isCheckedOut ? " [Checked Out]" : " [Available]"); + } +} } // Create a Library class that manages books class Library { - // Your fields here - - // Your constructor here + private ArrayList books; + + public Library() { + books = new ArrayList<>(); + } + - // Your addBook method here + public void addBook(Book book) { + books.add(book); + } + - // Your checkOutBook method here + public boolean checkOutBook(String title) { + for (Book book : books) { + if (book.title.equalsIgnoreCase(title) && book.isAvailable()) { + book.checkOut(); + return true; + } + } + return false; + } + - // Your returnBook method here + public boolean returnBook(String title) { + for (Book book : books) { + if (book.title.equalsIgnoreCase(title) && !book.isAvailable()) { + book.returnBook(); + return true; + } + } + return false; + } + + + public int getAvailableBooks() { + int count = 0; + for (Book book : books) { + if (book.isAvailable()) { + count++; + } + } + return count; + } + + public void listAllBooks() { + for (Book book : books) { + System.out.println(book.getInfo()); + } + } +} + - // Your getAvailableBooks method here -} + // Test your classes here - uncomment and modify as needed -/* + System.out.println("Testing Person class:"); Person person1 = createPerson("Alice", 30); Person person2 = new Person("Bob", 25); @@ -192,4 +363,4 @@ System.out.println("After checking out 1984: " + library.getAvailableBooks()); library.returnBook("1984"); System.out.println("After returning 1984: " + library.getAvailableBooks()); -*/ + diff --git a/method-writing/bool-and-boolean/topic.jsh b/method-writing/bool-and-boolean/topic.jsh index 3b9d7c0..472dc17 100644 --- a/method-writing/bool-and-boolean/topic.jsh +++ b/method-writing/bool-and-boolean/topic.jsh @@ -4,13 +4,15 @@ // Exercise 1: Basic Boolean Methods // Return true if person is 18 or older public boolean isAdult(int age) { - // Your code here - + return age >= 18; } + // Your code here + // Exercise 2: Number Range Checker // Return true if number is between min and max (inclusive) public boolean isInRange(int number, int min, int max) { + return number >= min && number <= max; // Your code here } @@ -18,6 +20,7 @@ public boolean isInRange(int number, int min, int max) { // Exercise 3: String Validation // Return true if email contains both "@" and "." characters public boolean isValidEmail(String email) { + return email != null && email.contains("@") && email.contains("."); // Your code here } @@ -25,14 +28,16 @@ public boolean isValidEmail(String email) { // Exercise 4: Even/Odd Checker // Return true if number is even, false if odd public boolean isEven(int number) { - // Your code here - + return number % 2 == 0; } + // Your code here + // Exercise 5: Leap Year Calculator // Return true if year is a leap year // Leap year: divisible by 4, but not by 100, unless also divisible by 400 public boolean isLeapYear(int year) { + return (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0)); // Your code here } @@ -40,47 +45,54 @@ public boolean isLeapYear(int year) { // Exercise 6: Password Strength Validator // Return true if password is at least 8 chars AND has at least one uppercase public boolean isStrongPassword(String password) { - // Your code here - + if (password == null || password.length() < 8) return false; + for (int i = 0; i < password.length(); i++) { + if (Character.isUpperCase(password.charAt(i))) { + return true; + } + } } // Exercise 7: Triangle Validator // Return true if three sides can form a valid triangle // Rule: sum of any two sides must be greater than the third side public boolean isValidTriangle(int a, int b, int c) { - // Your code here + return a + b > c && a + c > b && b + c > a; } // Exercise 8: Boolean Object Practice // Return true if both Boolean objects have the same value (handle nulls) public boolean compareBoolean(Boolean b1, Boolean b2) { - // Your code here - + return b1 == b2 || (b1 != null && b1.equals(b2)); } + // Exercise 9: Logic Gate Simulator // Simulate basic logic gates public boolean andGate(boolean a, boolean b) { - // Your code here - + return a && b; } + // Your code here + public boolean orGate(boolean a, boolean b) { + return a || b; // Your code here } public boolean notGate(boolean a) { - // Your code here + return !a; + } public boolean xorGate(boolean a, boolean b) { - // Your code here (true if exactly one input is true) - + return a != b; } + // Test your methods here - uncomment and modify as needed /* diff --git a/method-writing/double-and-double/topic.jsh b/method-writing/double-and-double/topic.jsh index b5a8955..33c7842 100644 --- a/method-writing/double-and-double/topic.jsh +++ b/method-writing/double-and-double/topic.jsh @@ -4,31 +4,36 @@ // Exercise 1: Basic Double Operations // Return the sum of two doubles public double calculateSum(double a, double b) { - // Your code here + return a + b; } // Return the average of three doubles public double calculateAverage(double a, double b, double c) { - // Your code here + return (a + b + c) / 3.0; + } // Exercise 2: Math Operations // Return the larger of two doubles public double findLarger(double a, double b) { - // Your code here + return (a > b) ? a : b; + } // Return the absolute value of a double public double calculateAbsolute(double number) { - // Your code here - + return (number < 0) ? -number : number; } + + + // Round double to nearest integer public int roundToNearestInt(double number) { + return (int) Math.round(number); // Your code here } @@ -36,80 +41,124 @@ public int roundToNearestInt(double number) { // Exercise 3: Precision and Comparison // Check if two doubles are equal within tolerance public boolean areDoublesEqual(double a, double b, double tolerance) { - // Your code here - + return Math.abs(a - b) <= tolerance; } + + + // Format double to string with 2 decimal places public String formatToTwoDecimals(double number) { - // Your code here - + return String.format("%.2f", number); } + + // Exercise 4: Mathematical Calculations // Calculate area of circle (π × r²) public double calculateCircleArea(double radius) { - // Your code here - + return Math.PI * radius * radius; } + // Calculate distance between two points using distance formula // √[(x2-x1)² + (y2-y1)²] public double calculateDistance(double x1, double y1, double x2, double y2) { - // Your code here + double dx = x2 - x1; + double dy = y2 - y; + return Math.sqrt(dx * dx + dy * dy); + } // Calculate compound interest: principal × (1 + rate)^years public double calculateCompoundInterest(double principal, double rate, int years) { - // Your code here - + return principal * Math.pow(1 + rate, years); } + // Exercise 5: Range and Validation // Check if value is between min and max (inclusive) public boolean isInRange(double value, double min, double max) { - // Your code here - + return value >= min && value <= max; } + + // Constrain value to be within min and max bounds public double clampValue(double value, double min, double max) { - // Your code here + if (value < min) return min; + if (value > max) return max; + return value; } // Exercise 6: Double Object Practice // Safely parse string to Double, return null if fails public Double parseDoubleSafely(String text) { - // Your code here - + try { + return Double.parseDouble(text); + } catch (NumberFormatException e) { + return null; + } } + // Safely compare Double objects (handle nulls) // Return: -1 if d1 < d2, 0 if equal, 1 if d1 > d2 // null is considered less than any number public int compareDoubles(Double d1, Double d2) { - // Your code here +if (d1 == d2) return 0; // both null or same object + if (d1 == null) return -1; + if (d2 == null) return 1; + return Double.compare(d1, d2); + } // Exercise 7: Array Statistics // Find maximum value in array public double findMaximum(double[] numbers) { + if (numbers == null || numbers.length == 0) { + throw new IllegalArgumentException("Array must not be empty"); + } + double max = numbers[0]; + for (int i = 1; i < numbers.length; i++) { + if (numbers[i] > max) { + max = numbers[i]; + } + } + return max; + // Your code here } // Calculate arithmetic mean (average) of array public double calculateMean(double[] numbers) { - // Your code here - + if (numbers == null || numbers.length == 0) { + throw new IllegalArgumentException("Array must not be empty"); + } + double sum = 0.0; + for (double num : numbers) { + sum += num; + } + return sum / numbers.length; } + + // Calculate standard deviation of array public double calculateStandardDeviation(double[] numbers) { - // Your code here + if (numbers == null || numbers.length == 0) { + throw new IllegalArgumentException("Array must not be empty"); + } + double mean = calculateMean(numbers); + double sumSq = 0.0; + for (double num : numbers) { + sumSq += (num - mean) * (num - mean); + } + return Math.sqrt(sumSq / numbers.length); // Hint: Standard deviation = √(Σ(x - mean)² / n) } diff --git a/method-writing/for-loops/topic.jsh b/method-writing/for-loops/topic.jsh index 08e71d9..97105ad 100644 --- a/method-writing/for-loops/topic.jsh +++ b/method-writing/for-loops/topic.jsh @@ -4,13 +4,20 @@ // Exercise 1: Number Sequence // Print all numbers from start to end (inclusive) public void printNumbers(int start, int end) { + for (int i = start; i <= end; i++) { + System.out.println(i); // Your code here - + } } // Exercise 2: Sum Calculator // Calculate the sum of all integers from 1 to n public int calculateSum(int n) { + int sum = 0; + for (int i = 1; i <= n; i++) { + sum = sum + i; + } + return sum; // Your code here } @@ -18,13 +25,20 @@ public int calculateSum(int n) { // Exercise 3: Multiplication Table // Print the multiplication table for the given number (1 through 10) public void multiplicationTable(int number) { - // Your code here - + for (int i = 1; i <= 10; i++) { + System.out.println(number + " x " + i + " = " + (number * i)); + } } + // Your code here + // Exercise 4: Even Numbers Only // Print all even numbers from 2 up to the limit (inclusive) public void printEvenNumbers(int limit) { + for (int i = 2; i <= limit; i += 2) { + System.out.println(i); +} +``` // Your code here } @@ -32,16 +46,27 @@ public void printEvenNumbers(int limit) { // Exercise 5: String Repeater // Return a string with the given text repeated the specified number of times public String repeatString(String text, int times) { + String result = ""; + for (int i = 0; i < times; i++) { + result += text; + } + return result; +} // Your code here -} + // Exercise 6: Factorial Calculator // Calculate n! (n factorial) using a for loop public long calculateFactorial(int n) { + int result = 1; + for (int i = 1; i <= n; i++) { + result *= i; + } + return result; +} // Your code here -} // Exercise 7: Array Sum // Calculate and return the sum of all numbers in an array diff --git a/method-writing/if-else-statements/topic.jsh b/method-writing/if-else-statements/topic.jsh index b4c120e..53d8760 100644 --- a/method-writing/if-else-statements/topic.jsh +++ b/method-writing/if-else-statements/topic.jsh @@ -4,6 +4,11 @@ // Exercise 1: Basic If Statement // Write a method that checks if someone is an adult (18 or older) public String checkAge(int age) { + if (age >= 18) { + return "Adult"; + } else { + return "Minor"; + } // Your code here } @@ -11,30 +16,53 @@ public String checkAge(int age) { // Exercise 2: Grade Classification // Classify a numeric grade into a category public String classifyGrade(int score) { - // Your code here - + if (score >= 90) { + return "Excellent"; + } else if (score >= 80) { + return "Good"; + } else if (score >= 70) { + return "Average"; + } else { + return "Below Average"; + } } + // Exercise 3: Number Sign // Determine if a number is positive, negative, or zero public String getSign(int number) { - // Your code here - + if (number > 0) { + return "Positive"; + } else if (number < 0){ + return "Negative"; + } else { + return "Zero"; + } } + + + // Exercise 4: Temperature Check // Classify temperature as hot, warm, or cold public String checkTemperature(double temp) { - // Your code here - + if (temp >= 80) { + return "Hot"; + } else if (temp >= 60) { + return "Warm"; + } else { + return "Cold"; + } } + // Exercise 5: Login Validation // Check if username and password are valid (not null and not empty) public boolean validateLogin(String username, String password) { - // Your code here - + return username != null && !username.isEmpty() && password != null && !password.isEmpty(); } + + // Test your methods here - uncomment and modify as needed /* diff --git a/method-writing/integer-and-int/topic.jsh b/method-writing/integer-and-int/topic.jsh index 40b670b..69b73be 100644 --- a/method-writing/integer-and-int/topic.jsh +++ b/method-writing/integer-and-int/topic.jsh @@ -4,6 +4,7 @@ // Exercise 1: Basic Math Operations // Return the sum of two integers public int calculateSum(int a, int b) { + return a + b; // Your code here } @@ -11,18 +12,21 @@ public int calculateSum(int a, int b) { // Return the product of two integers public int calculateProduct(int a, int b) { // Your code here + return a * b; } // Exercise 2: Number Analysis // Return the larger of two integers public int findLarger(int a, int b) { + return (a > b) ? a : b; // Your code here } // Return the absolute value (always positive) public int findAbsoluteValue(int number) { + return (number < 0) ? -number : number; // Your code here } @@ -30,12 +34,24 @@ public int findAbsoluteValue(int number) { // Exercise 3: Digit Operations // Count how many digits are in a positive integer public int countDigits(int number) { - // Your code here - + int count = 0; + do { + count++; + number /= 10; + } while (number > 0); + return count; } + + // Reverse the digits of a positive integer (123 becomes 321) public int reverseDigits(int number) { + int reversed = 0; + while (number > 0) { + reversed = reversed * 10 + (number % 10); + number /= 10; + } + return reversed; // Your code here } @@ -43,12 +59,23 @@ public int reverseDigits(int number) { // Exercise 4: Number Classification // Return true if number is prime (only divisible by 1 and itself) public boolean isPrime(int number) { + if (number <= 1) return false; + if (number == 2) return true; + if (number % 2 == 0) return false; + for (int i = 3; i * i <= number; i += 2) { + if (number % i == 0) return false; + } + return true; +} // Your code here -} + // Return true if number is a perfect square public boolean isPerfectSquare(int number) { + if (number < 0) return false; + int sqrt = (int) Math.sqrt(number); + return sqrt * sqrt == number; // Your code here } @@ -56,12 +83,20 @@ public boolean isPerfectSquare(int number) { // Exercise 5: Range Operations // Calculate sum of all integers from start to end (inclusive) public int sumRange(int start, int end) { - // Your code here - + int sum = 0; + for (int i = start; i <= end; i++) { + sum += i; + } + return sum; } + + + // Count how many multiples of 'number' exist up to 'limit' public int countMultiples(int number, int limit) { + if (number == 0) return 0; + return limit / number; // Your code here } @@ -71,38 +106,69 @@ public int countMultiples(int number, int limit) { // Return: -1 if num1 < num2, 0 if equal, 1 if num1 > num2 // Handle null cases: null is considered less than any number public int compareIntegers(Integer num1, Integer num2) { + if (num1 == null && num2 == null) return 0; + if (num1 == null) return -1; + if (num2 == null) return 1; + return Integer.compare(num1, num2); // Your code here } // Try to parse string to Integer, return null if it fails public Integer parseIntegerSafely(String text) { + try { + return Integer.parseInt(text); + } catch (NumberFormatException e) { + return null; + } +} // Your code here -} + // Exercise 7: Mathematical Sequences // Return the nth Fibonacci number (0, 1, 1, 2, 3, 5, 8, 13...) public int fibonacci(int n) { + if (n < 0) throw new IllegalArgumentException("n must be non-negative"); + if (n == 0) return 0; + if (n == 1) return 1; + int a = 0, b = 1; + for (int i = 2; i <= n; i++) { + int temp = a + b; + a = b; + b = temp; + } + return b; +} // Your code here -} + // Calculate n! (n factorial) public long factorial(int n) { + if (n < 0) throw new IllegalArgumentException("n must be non-negative"); + long result = 1; + for (int i = 2; i <= n; i++) { + result *= i; + } + return result; +} // Your code here -} + // Exercise 8: Number Conversion // Convert integer to binary string representation public String toBinaryString(int number) { + return Integer.toBinaryString(number); +} // Your code here -} + // Convert binary string back to integer public int fromBinaryString(String binary) { + return Integer.parseInt(binary, 2); // Your code here } @@ -110,16 +176,35 @@ public int fromBinaryString(String binary) { // Exercise 9: Array Statistics // Find the maximum value in an array public int findMax(int[] numbers) { + if (numbers == null || numbers.length == 0) { + throw new IllegalArgumentException("Array must not be null or empty"); + } + int max = numbers[0]; + for (int i = 1; i < numbers.length; i++) { + if (numbers[i] > max) { + max = numbers[i]; + } + } + return max; // Your code here } // Calculate the average as a double public double calculateAverage(int[] numbers) { - // Your code here - + if (numbers == null || numbers.length == 0) { + throw new IllegalArgumentException("Array must not be null or empty"); + } + double sum = 0; + for (int num : numbers) { + sum += num; + } + return sum / numbers.length; } + + + // Test your methods here - uncomment and modify as needed /* System.out.println("Testing Basic Math:"); diff --git a/method-writing/while-loops/topic.jsh b/method-writing/while-loops/topic.jsh index 12c0c61..b3a0731 100644 --- a/method-writing/while-loops/topic.jsh +++ b/method-writing/while-loops/topic.jsh @@ -4,20 +4,41 @@ // Exercise 1: Countdown // Print numbers from start down to 1, then print "Blast off!" public void countdown(int start) { - // Your code here - + int i = start; + while (i >= 1) { + System.out.println(i); + i--; + } + System.out.println("Blast off!"); } + // Your code here + + // Exercise 2: Sum Calculator // Calculate the sum of all integers from 1 to n public int sumUpTo(int n) { - // Your code here + int sum = 0; + int i = 1; + while (i <= n) { + sum += i; + i++; + } + return sum; + } // Exercise 3: Number Guessing Helper // Count how many steps it takes to get from start to target (adding 1 each time) public int findNumber(int target, int start) { + int steps = 0; + + while (start < target) { + start = start + 1; + steps++; + } + return steps; // Your code here } @@ -25,30 +46,67 @@ public int findNumber(int target, int start) { // Exercise 4: Digit Counter // Count how many digits are in a positive integer public int countDigits(int number) { - // Your code here - + if (number == 0) return 1; + + int count = 0; + while (number > 0) { + number = number / 10; + count++; + } + return count; } + // Exercise 5: Password Strength Checker // Use a while loop to count characters and determine password strength public String checkPasswordStrength(String password) { + + int length = 0; + int index = 0; + + while (index < password.length()) { + length++; + index++; + } + + if (length >= 8) { + return "Strong"; + } else if (length >= 5) { + return "Medium"; + } else { + return "Weak"; + } +} + + // Your code here -} // Exercise 6: Factorial Calculator // Calculate n! (n factorial) using a while loop public long factorial(int n) { - // Your code here - + int result = 1; + while (n > 1) { + result *= n; + n--; + } + return result; } + + // Exercise 7: Power Calculator // Calculate base^exponent using a while loop (don't use Math.pow) public int power(int base, int exponent) { - // Your code here - + + int result = 1; + while (exponent > 0) { + result *= base; + exponent--; + } + return result; } + // Test your methods here - uncomment and modify as needed /* From de31d16d52a643f8836c7eecfb80a9c10e398a49 Mon Sep 17 00:00:00 2001 From: Jobonsu4 Date: Wed, 23 Jul 2025 15:01:38 -0400 Subject: [PATCH 2/8] changes --- method-writing/for-loops/topic.jsh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/method-writing/for-loops/topic.jsh b/method-writing/for-loops/topic.jsh index 97105ad..8d1fd62 100644 --- a/method-writing/for-loops/topic.jsh +++ b/method-writing/for-loops/topic.jsh @@ -38,7 +38,7 @@ public void printEvenNumbers(int limit) { for (int i = 2; i <= limit; i += 2) { System.out.println(i); } -``` + // Your code here } From 9ef85465a9273e35599b50a3e829c77800b1f0ba Mon Sep 17 00:00:00 2001 From: Jobonsu4 Date: Wed, 23 Jul 2025 15:17:28 -0400 Subject: [PATCH 3/8] changes --- method-writing/bool-and-boolean/topic.jsh | 4 ++-- method-writing/double-and-double/topic.jsh | 4 ++-- method-writing/for-loops/topic.jsh | 25 ++++++++++++++++------ method-writing/integer-and-int/topic.jsh | 4 ++-- method-writing/while-loops/topic.jsh | 4 ++-- 5 files changed, 27 insertions(+), 14 deletions(-) diff --git a/method-writing/bool-and-boolean/topic.jsh b/method-writing/bool-and-boolean/topic.jsh index 472dc17..6e84d0c 100644 --- a/method-writing/bool-and-boolean/topic.jsh +++ b/method-writing/bool-and-boolean/topic.jsh @@ -95,7 +95,7 @@ public boolean xorGate(boolean a, boolean b) { // Test your methods here - uncomment and modify as needed -/* + System.out.println("Testing isAdult:"); System.out.println("Age 17: " + isAdult(17)); // Should print false System.out.println("Age 18: " + isAdult(18)); // Should print true @@ -144,4 +144,4 @@ System.out.println("OR true,false: " + orGate(true, false)); // Should prin System.out.println("NOT true: " + notGate(true)); // Should print false System.out.println("XOR true,false: " + xorGate(true, false)); // Should print true System.out.println("XOR true,true: " + xorGate(true, true)); // Should print false -*/ + diff --git a/method-writing/double-and-double/topic.jsh b/method-writing/double-and-double/topic.jsh index 33c7842..0f64573 100644 --- a/method-writing/double-and-double/topic.jsh +++ b/method-writing/double-and-double/topic.jsh @@ -164,7 +164,7 @@ public double calculateStandardDeviation(double[] numbers) { } // Test your methods here - uncomment and modify as needed -/* + System.out.println("Testing Basic Operations:"); System.out.println("3.5 + 2.7 = " + calculateSum(3.5, 2.7)); // Should print 6.2 System.out.println("Average of 1,2,3 = " + calculateAverage(1.0, 2.0, 3.0)); // Should print 2.0 @@ -206,4 +206,4 @@ System.out.println("Standard deviation: " + calculateStandardDeviation(testArray // Test edge cases double[] emptyArray = {}; // System.out.println("Mean of empty array: " + calculateMean(emptyArray)); // Test your error handling -*/ + diff --git a/method-writing/for-loops/topic.jsh b/method-writing/for-loops/topic.jsh index 8d1fd62..8c06db0 100644 --- a/method-writing/for-loops/topic.jsh +++ b/method-writing/for-loops/topic.jsh @@ -71,17 +71,30 @@ public long calculateFactorial(int n) { // Exercise 7: Array Sum // Calculate and return the sum of all numbers in an array public int sumArray(int[] numbers) { - // Your code here - + int sum = 0; + for (int i = 0; i < numbers.length; i++) { + sum += numbers[i]; + } + return sum; } + + // Exercise 8: Character Counter // Count how many times a specific character appears in a string public int countCharacter(String text, char target) { - // Your code here - + int count = 0; + for (int i = 0; i < text.length(); i++) { + if (text.charAt(i) == target) { + count++; + } + } + return count; } + + + // Exercise 9: Pattern Printer // Print a triangle pattern of stars public void printStars(int rows) { @@ -90,7 +103,7 @@ public void printStars(int rows) { } // Test your methods here - uncomment and modify as needed -/* + System.out.println("Testing printNumbers:"); printNumbers(1, 5); printNumbers(3, 7); @@ -132,4 +145,4 @@ System.out.println("\nTesting printStars:"); printStars(4); System.out.println(); printStars(2); -*/ + diff --git a/method-writing/integer-and-int/topic.jsh b/method-writing/integer-and-int/topic.jsh index 69b73be..ae92445 100644 --- a/method-writing/integer-and-int/topic.jsh +++ b/method-writing/integer-and-int/topic.jsh @@ -206,7 +206,7 @@ public double calculateAverage(int[] numbers) { // Test your methods here - uncomment and modify as needed -/* + System.out.println("Testing Basic Math:"); System.out.println("5 + 3 = " + calculateSum(5, 3)); // Should print 8 System.out.println("4 * 6 = " + calculateProduct(4, 6)); // Should print 24 @@ -252,4 +252,4 @@ System.out.println("\nTesting Array Statistics:"); int[] testArray = {1, 5, 3, 9, 2}; System.out.println("Max of [1,5,3,9,2]: " + findMax(testArray)); // Should print 9 System.out.println("Average of [1,5,3,9,2]: " + calculateAverage(testArray)); // Should print 4.0 -*/ + diff --git a/method-writing/while-loops/topic.jsh b/method-writing/while-loops/topic.jsh index b3a0731..de2a8fd 100644 --- a/method-writing/while-loops/topic.jsh +++ b/method-writing/while-loops/topic.jsh @@ -109,7 +109,7 @@ public int power(int base, int exponent) { // Test your methods here - uncomment and modify as needed -/* + System.out.println("Testing countdown:"); countdown(5); @@ -141,4 +141,4 @@ System.out.println("\nTesting power:"); System.out.println("2^3: " + power(2, 3)); // Should print 8 System.out.println("5^2: " + power(5, 2)); // Should print 25 System.out.println("3^0: " + power(3, 0)); // Should print 1 -*/ + From 5565970bfef8ad9430296ef51213dba5317d3129 Mon Sep 17 00:00:00 2001 From: Jobonsu4 Date: Thu, 24 Jul 2025 14:29:45 -0400 Subject: [PATCH 4/8] changes --- method-writing/arraylists/topic.jsh | 82 +++++++++++++++++++++++++--- method-writing/for-loops/topic.jsh | 10 +++- method-writing/strings/topic.jsh | 85 +++++++++++++++++++++++------ 3 files changed, 150 insertions(+), 27 deletions(-) diff --git a/method-writing/arraylists/topic.jsh b/method-writing/arraylists/topic.jsh index 84c9cad..154c40a 100644 --- a/method-writing/arraylists/topic.jsh +++ b/method-writing/arraylists/topic.jsh @@ -6,12 +6,19 @@ import java.util.Collections; // Exercise 1: ArrayList Basics // Create and return a new ArrayList of Strings public ArrayList createStringList() { + ArrayList list = new ArrayList<>(); + return new ArrayList<>(); // Your code here } // Return size of ArrayList (handle null) public int getListSize(ArrayList list) { + if (list == null) { + return 0; + } + return list.size(); + // Your code here } @@ -19,18 +26,26 @@ public int getListSize(ArrayList list) { // Exercise 2: Adding Elements // Add item to the end of the list public void addToEnd(ArrayList list, String item) { + if (list != null) { + list.add(item); + } // Your code here } // Add item to the beginning of the list public void addToBeginning(ArrayList list, String item) { + if (list != null) { + list.add(0, item); // Your code here - + } } // Add item at specific position public void addAtPosition(ArrayList list, int index, String item) { + if (list != null && index >= 0 && index <= list.size()) { + list.add(index, item); + } // Your code here } @@ -38,62 +53,90 @@ public void addAtPosition(ArrayList list, int index, String item) { // Exercise 3: Accessing Elements // Return first item (null if empty) public String getFirstItem(ArrayList list) { + if (list == null || list.isEmpty()) return null; + return list.get(0); // Your code here } // Return last item (null if empty) public String getLastItem(ArrayList list) { + if (list == null || list.isEmpty()) return null; + return list.get(list.size() - 1); +} // Your code here -} + // Return item at specific index (null if out of bounds) public String getItemAt(ArrayList list, int index) { + if (list == null || index < 0 || index >= list.size()) return null; + return list.get(index); +} // Your code here -} + // Exercise 4: Searching and Contains // Return true if list contains the item public boolean containsItem(ArrayList list, String item) { + return list != null && list.contains(item); // Your code here } // Return index of first occurrence (-1 if not found) public int findPosition(ArrayList list, String item) { + if (list == null) return -1; + return list.indexOf(item); // Your code here } // Count how many times item appears in list public int countOccurrences(ArrayList list, String item) { + int count = 0; + if (list != null) { + for (String str : list) { + if (str.equals(item)) { + count++; // Your code here - + } +} + } + return count; } // Exercise 5: Removing Elements // Remove and return first item (null if empty) public String removeFirstItem(ArrayList list) { + if (list == null || list.isEmpty()) return null; + return list.remove(0); + // Your code here } // Remove and return last item (null if empty) public String removeLastItem(ArrayList list) { + if (list == null || list.isEmpty()) return null; + return list.remove(list.size() - 1); // Your code here } // Remove item at specific index (null if out of bounds) public String removeAtPosition(ArrayList list, int index) { + if (list == null || index < 0 || index >= list.size()) return null; + return list.remove(index); // Your code here } // Remove all occurrences of an item public void removeAllOccurrences(ArrayList list, String item) { + if (list != null) { + list.removeIf(str -> str.equals(item)); // Your code here } @@ -101,18 +144,27 @@ public void removeAllOccurrences(ArrayList list, String item) { // Exercise 6: List Operations // Remove all items from list public void clearList(ArrayList list) { + if (list != null) { + list.clear(); + } // Your code here } // Create a copy of the list public ArrayList copyList(ArrayList original) { + if (original == null) return new ArrayList<>(); + return new ArrayList<>(original); // Your code here } // Combine two lists into one new list public ArrayList mergeLists(ArrayList list1, ArrayList list2) { + ArrayList result = new ArrayList<>(); + if (list1 != null) result.addAll(list1); + if (list2 != null) result.addAll(list2); + return result; // Your code here } @@ -120,24 +172,38 @@ public ArrayList mergeLists(ArrayList list1, ArrayList l // Exercise 7: List Analysis // Find and return the longest string in the list public String findLongestString(ArrayList list) { + if (list == null || list.isEmpty()) return null; + String longest = ""; + for (String str : list) { + if (str != null && str.length() > longest.length()) { + longest = str; + } + } + return longest; // Your code here } // Sort the list alphabetically (modifies the original list) public void sortList(ArrayList list) { + if (list != null) { + Collections.sort(list); + } + // Your code here } // Convert ArrayList to String array public String[] convertToArray(ArrayList list) { + if (list == null) return new String[0]; + return list.toArray(new String[0]); // Your code here } // Test your methods here - uncomment and modify as needed -/* + System.out.println("Testing ArrayList Basics:"); ArrayList list = createStringList(); System.out.println("Empty list size: " + getListSize(list)); // Should print 0 @@ -184,10 +250,10 @@ sortList(merged); System.out.println("Sorted list: " + merged); String[] array = convertToArray(merged); -System.out.print("Converted to array: ["); +System.out.print("Converted to array: "); for (int i = 0; i < array.length; i++) { System.out.print(array[i]); if (i < array.length - 1) System.out.print(", "); } -System.out.println("]"); -*/ +System.out.println(""); + diff --git a/method-writing/for-loops/topic.jsh b/method-writing/for-loops/topic.jsh index 8c06db0..f8f55fd 100644 --- a/method-writing/for-loops/topic.jsh +++ b/method-writing/for-loops/topic.jsh @@ -98,9 +98,15 @@ public int countCharacter(String text, char target) { // Exercise 9: Pattern Printer // Print a triangle pattern of stars public void printStars(int rows) { - // Your code here - + for (int i = 1; i <= rows; i++) { + for (int j = 1; j <= i; j++) { + System.out.print("*"); + } + System.out.println(); + } } + // Your code here + // Test your methods here - uncomment and modify as needed diff --git a/method-writing/strings/topic.jsh b/method-writing/strings/topic.jsh index 5c6fbd7..04b2d78 100644 --- a/method-writing/strings/topic.jsh +++ b/method-writing/strings/topic.jsh @@ -4,38 +4,45 @@ // Exercise 1: String Basics // Return the length of a string (handle null strings) public int getStringLength(String text) { - // Your code here - + if (text == null) { + return 0; + } + return text.length(); } + // Return true if string is null or empty public boolean isStringEmpty(String text) { - // Your code here + return text == null || text.isEmpty(); + } // Exercise 2: String Comparison // Safely compare two strings for equality (handle nulls) public boolean areStringsEqual(String str1, String str2) { - // Your code here - + return (str1 == null) ? str2 == null : str1.equals(str2); } + // Compare strings ignoring case differences public boolean compareStringsIgnoreCase(String str1, String str2) { - // Your code here + return (str1 == null || str2 == null) ? false : str1.equalsIgnoreCase(str2); + } // Exercise 3: String Search and Contains // Return true if text contains the search string public boolean containsSubstring(String text, String search) { + return (text != null && search != null) && text.contains(search); // Your code here } // Return index of first occurrence of search in text (-1 if not found) public int findFirstPosition(String text, String search) { + return (text != null && search != null) ? text.indexOf(search) : -1; // Your code here } @@ -43,6 +50,10 @@ public int findFirstPosition(String text, String search) { // Exercise 4: String Extraction // Return the first character of a string (handle empty strings) public char getFirstCharacter(String text) { + if (text == null || text.isEmpty()) { + throw new IllegalArgumentException("Input string is empty or null"); + } + return text.charAt(0); // Your code here // Return a space ' ' for empty/null strings @@ -50,32 +61,45 @@ public char getFirstCharacter(String text) { // Return the last character of a string public char getLastCharacter(String text) { + if (text == null || text.isEmpty()) { + throw new IllegalArgumentException("Input string is empty or null"); + } + return text.charAt(text.length() - 1); +} + // Your code here // Return a space ' ' for empty/null strings -} + // Return substring from start to end index public String getSubstring(String text, int start, int end) { - // Your code here - + if (text == null || start < 0 || end > text.length() || start > end) { + throw new IllegalArgumentException("Invalid input or range"); + } + return text.substring(start, end); } + // Your code here + // Exercise 5: String Modification // Convert string to uppercase (handle null) public String makeUpperCase(String text) { - // Your code here - + return (text != null) ? text.toUpperCase() : null; } + // Your code here + // Convert string to lowercase (handle null) public String makeLowerCase(String text) { + return (text != null) ? text.toLowerCase() : null; // Your code here } // Remove leading and trailing spaces public String trimWhitespace(String text) { + return (text != null) ? text.trim() : null; // Your code here } @@ -83,18 +107,27 @@ public String trimWhitespace(String text) { // Exercise 6: String Building and Joining // Join two strings together (handle nulls) public String concatenateStrings(String str1, String str2) { + return (str1 == null ? "" : str1) + (str2 == null ? "" : str2); // Your code here } // Repeat a string the specified number of times public String repeatString(String text, int count) { + if (text == null || count <= 0) return ""; + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < count; i++) { + sb.append(text); + } + return sb.toString(); // Your code here } // Join array of strings with a separator public String joinWithSeparator(String[] words, String separator) { + if (words == null || separator == null) return ""; + return String.join(separator, words); // Your code here } @@ -102,24 +135,42 @@ public String joinWithSeparator(String[] words, String separator) { // Exercise 7: String Validation and Analysis // Return true if email contains "@" and "." characters public boolean isValidEmail(String email) { + return (email != null && email.contains("@") && email.contains(".")); // Your code here } // Count number of vowels (a, e, i, o, u) in string (case insensitive) public int countVowels(String text) { - // Your code here - + if (text == null) return 0; + int count = 0; + String lower = text.toLowerCase(); + for (int i = 0; i < lower.length(); i++) { + char c = lower.charAt(i); + if ("aeiou".indexOf(c) != -1) { + count++; + } +} +return count++; } - // Return true if string reads same forwards and backwards (ignore case and spaces) public boolean isPalindrome(String text) { - // Your code here + if (text == null) return false; + String clean = text.replaceAll("\\s+", "").toLowerCase(); + int left = 0, right = clean.length() - 1; + while (left < right) { + if (clean.charAt(left) != clean.charAt(right)) return false; + left++; + right--; + } + return true; + + } // Test your methods here - uncomment and modify as needed -/* + System.out.println("Testing String Basics:"); System.out.println("Length of 'Hello': " + getStringLength("Hello")); // Should print 5 System.out.println("Length of null: " + getStringLength(null)); // Should print 0 @@ -159,4 +210,4 @@ System.out.println("'invalid' is valid email: " + isValidEmail("invalid")); System.out.println("Vowels in 'Hello': " + countVowels("Hello")); // Should print 2 System.out.println("'racecar' is palindrome: " + isPalindrome("racecar")); // Should print true System.out.println("'hello' is palindrome: " + isPalindrome("hello")); // Should print false -*/ + From e2e5b6240c3445b84530814976c059a547b01099 Mon Sep 17 00:00:00 2001 From: Jobonsu4 Date: Fri, 25 Jul 2025 10:24:15 -0400 Subject: [PATCH 5/8] changes --- java-org/instance-methods/topic.jsh | 86 +++++++++++++++------- method-writing/object-references/topic.jsh | 75 +++++++++++++++---- 2 files changed, 123 insertions(+), 38 deletions(-) diff --git a/java-org/instance-methods/topic.jsh b/java-org/instance-methods/topic.jsh index 66534a0..9bd658f 100644 --- a/java-org/instance-methods/topic.jsh +++ b/java-org/instance-methods/topic.jsh @@ -7,83 +7,96 @@ class Calculator { double result; public Calculator() { - // TODO: Initialize result to 0.0 + result = 0.0; + } public void add(double value) { - // TODO: Add value to result + result += value; + } public void subtract(double value) { - // TODO: Subtract value from result + result -= value; + } public void multiply(double value) { - // TODO: Multiply result by value + result *= value; } public void divide(double value) { - // TODO: Divide result by value (check for division by zero) + if (value != 0) { + result /= value; } public double getResult() { // TODO: Return the current result - return 0.0; + return result; } public void clear() { - // TODO: Reset result to 0.0 + return 0.0; } } +} // Exercise 2: Text processing with instance methods class TextProcessor { String text; public TextProcessor(String initialText) { + this.text = initialText; + // TODO: Set the text field } public void setText(String newText) { + this.text = newText; // TODO: Update the text } public String getText() { // TODO: Return the current text - return ""; + return text; } public int getLength() { // TODO: Return length of text - return 0; + return (text != null) ? text.length() : 0; } public String toUpperCase() { // TODO: Return text in uppercase (don't modify original) - return ""; + return (text != null) ? text.toUpperCase() : ""; } public String toLowerCase() { // TODO: Return text in lowercase (don't modify original) - return ""; + return (text != null) ? text.toUpperCase() : ""; } - public String reverse() { + StringBuilder sb = new StringBuilder(text); + return sb.reverse().toString(); // TODO: Return reversed text - return ""; } public boolean contains(String substring) { - // TODO: Check if text contains substring - return false; + if (text == null || substring == null) return false; + return text.contains(substring); + } public int getWordCount() { + if (text == null || text.trim().isEmpty()) { + return 0; + } + return text.trim().split("\\s+").length; + } // TODO: Return number of words in text // Hint: Split by spaces and count non-empty parts - return 0; } -} + // Exercise 3: Counter with state management class Counter { @@ -91,43 +104,49 @@ class Counter { int step; public Counter(int initialCount, int stepValue) { + this.count = initialCount; + this.step = stepValue; // TODO: Initialize count and step } public void increment() { + count += step; // TODO: Increase count by step } public void decrement() { + count -= step; // TODO: Decrease count by step } public void reset() { + count = 0; // TODO: Set count back to 0 } public int getCount() { // TODO: Return current count - return 0; + return count; } public void setStep(int newStep) { + step = newStep; // TODO: Change the step value } public int getStep() { // TODO: Return current step value - return 0; + return step; } public boolean isPositive() { // TODO: Return true if count > 0 - return false; + return count > 0; } public boolean isNegative() { // TODO: Return true if count < 0 - return false; + return count < 0; } } @@ -136,6 +155,17 @@ class Temperature { double celsius; public Temperature(double temp, String unit) { + public Temperature(double temp, String unit) { + if (unit.equalsIgnoreCase("C")) { + this.celsius = temp; + } else if (unit.equalsIgnoreCase("F")) { + this.celsius = (temp - 32) * 5.0 / 9.0; + } else if (unit.equalsIgnoreCase("K")) { + this.celsius = temp - 273.15; + } else { + throw new IllegalArgumentException("Invalid unit. Use 'C', 'F', or 'K'."); + } + } // TODO: Convert temperature to Celsius and store // unit can be "C", "F", or "K" // Conversion formulas: @@ -145,39 +175,45 @@ class Temperature { public double getCelsius() { // TODO: Return temperature in Celsius - return 0.0; + return this.celsius; } public double getFahrenheit() { // TODO: Return temperature in Fahrenheit // C to F: C * 9/5 + 32 - return 0.0; + return (this.celsius * 9.0 / 5.0) + 32; } public double getKelvin() { // TODO: Return temperature in Kelvin // C to K: C + 273.15 - return 0.0; + return this.celsius + 273.15; } public void setCelsius(double temp) { + this.celsius = temp; // TODO: Set temperature in Celsius } public void setFahrenheit(double temp) { + this.celsius = (temp - 32) * 5.0 / 9.0; + // TODO: Set temperature in Fahrenheit (convert to Celsius) } public void setKelvin(double temp) { + this.celsius = temp - 273.15; // TODO: Set temperature in Kelvin (convert to Celsius) } public boolean isFreezingWater() { + return this.celsius + 273.15; // TODO: Return true if water would freeze (0°C or below) - return false; + } public boolean isBoilingWater() { + // TODO: Return true if water would boil (100°C or above) return false; } diff --git a/method-writing/object-references/topic.jsh b/method-writing/object-references/topic.jsh index af03712..815b2e0 100644 --- a/method-writing/object-references/topic.jsh +++ b/method-writing/object-references/topic.jsh @@ -4,19 +4,20 @@ import java.util.ArrayList; // Exercise 1: Reference Basics // Create and return array of 3 Strings -public String[] createStringArray() { - // Your code here - +public String[] createStringArray(){ + return new String[] {"Apple", "Banana", "Cherry"}; } // Check if two String references point to same object (using ==) public boolean areReferencesEqual(String str1, String str2) { + return str1 == str2; // Your code here } // Check if two String references have same content (using equals) public boolean areContentsEqual(String str1, String str2) { + return str1 != null && str1.equals(str2); // Your code here } @@ -24,18 +25,20 @@ public boolean areContentsEqual(String str1, String str2) { // Exercise 2: Null Handling // Return true if reference is null public boolean isNullReference(Object obj) { + return obj == null; // Your code here } // Convert object to string, return "null" if object is null public String safeToString(Object obj) { - // Your code here + return (obj == null) ? "null" : obj.toString(); } // Return length of string, or 0 if null public int safeLength(String str) { + return (str == null) ? 0 : str.length(); // Your code here } @@ -43,37 +46,51 @@ public int safeLength(String str) { // Exercise 3: Array References // Copy the reference (not content) of an array public int[] copyArrayReference(int[] original) { + return original; // Your code here } // Create new array with same content public int[] copyArrayContent(int[] original) { - // Your code here + if (original == null) return null; + int[] copy = new int[original.length]; + for (int i = 0; i < original.length; i++) { + copy[i] = original[i]; + } + + return copy; } // Change value in array at specified index public void modifyArray(int[] array, int index, int newValue) { - // Your code here + if (array != null && index >= 0 && index < array.length) { + array[index] = newValue; + } + } // Exercise 4: Object State Changes // Create StringBuilder with initial text public StringBuilder createStringBuilder(String initial) { + return new StringBuilder(initial); // Your code here } // Add text to StringBuilder public void appendToBuilder(StringBuilder sb, String text) { - // Your code here + if (sb != null && text != null) { + sb.append(text); + } } // Get current content as String public String getBuilderContent(StringBuilder sb) { + return (sb == null) ? "" : sb.toString(); // Your code here } @@ -81,18 +98,34 @@ public String getBuilderContent(StringBuilder sb) { // Exercise 5: Reference Comparison // Find first String with same content as target public String findStringInArray(String[] array, String target) { - // Your code here + if (array == null || target == null) return null; + for (String s : array) { + if (target.equals(s)) return s; + } + return null; + } // Count how many elements are null public int countNullReferences(Object[] array) { - // Your code here + if (array == null) return 0; + int count = 0; + for (Object obj : array) { + if (obj == null) count++; + } + return count; } // Replace all null elements with replacement string public void replaceNulls(String[] array, String replacement) { + if (array == null || replacement == null) return; + for (int i = 0; i < array.length; i++) { + if (array[i] == null) { + array[i] = replacement; + } + } // Your code here } @@ -100,6 +133,9 @@ public void replaceNulls(String[] array, String replacement) { // Exercise 6: Multiple References // Create two String literals and show they reference same object public boolean demonstrateStringPool() { + String a = "hello"; + String b = "hello"; + return a == b; // Your code here - create two string literals with same value // Return true if they reference the same object @@ -107,6 +143,9 @@ public boolean demonstrateStringPool() { // Create two String objects with 'new' and show they're different public boolean demonstrateNewString() { + String a = new String("world"); + String b = new String("world"); + return a != b && a.equals(b); // Your code here - create two strings with new String() // Return true if they are different objects (but same content) @@ -114,31 +153,41 @@ public boolean demonstrateNewString() { // Swap two references in an array public void swapReferences(StringBuilder[] array, int index1, int index2) { + if (array != null && + index1 >= 0 && index1 < array.length && + index2 >= 0 && index2 < array.length) { + StringBuilder temp = array[index1]; + array[index1] = array[index2]; + array[index2] = temp; // Your code here - + } } // Exercise 7: Object Creation and References // Create and return new ArrayList public ArrayList createArrayList() { + return new ArrayList<>(); // Your code here } // Add item to list public void addToList(ArrayList list, String item) { - // Your code here + if (list != null && item != null) { + list.add(item); + } } // Return the same list reference public ArrayList getListReference(ArrayList list) { + return list; // Your code here } // Test your methods here - uncomment and modify as needed -/* + System.out.println("Testing Reference Basics:"); String[] array = createStringArray(); System.out.println("Array created with length: " + array.length); @@ -196,4 +245,4 @@ addToList(list1, "Second"); ArrayList list2 = getListReference(list1); System.out.println("Same list reference: " + (list1 == list2)); // Should be true System.out.println("List content: " + list1); -*/ + From 23752393bcb1e38a76b2565aa27d8a092f6e79e5 Mon Sep 17 00:00:00 2001 From: Jobonsu4 Date: Fri, 25 Jul 2025 11:11:31 -0400 Subject: [PATCH 6/8] changes --- java-org/instance-methods/topic.jsh | 54 ++++++++++++++++++----------- 1 file changed, 34 insertions(+), 20 deletions(-) diff --git a/java-org/instance-methods/topic.jsh b/java-org/instance-methods/topic.jsh index 9bd658f..940f881 100644 --- a/java-org/instance-methods/topic.jsh +++ b/java-org/instance-methods/topic.jsh @@ -28,18 +28,23 @@ class Calculator { public void divide(double value) { if (value != 0) { result /= value; + } else { + System.out.println("Error: Division by zero"); + } } + public double getResult() { // TODO: Return the current result return result; } public void clear() { - return 0.0; + result = 0.0; } } -} + + // Exercise 2: Text processing with instance methods class TextProcessor { @@ -155,13 +160,12 @@ class Temperature { double celsius; public Temperature(double temp, String unit) { - public Temperature(double temp, String unit) { if (unit.equalsIgnoreCase("C")) { - this.celsius = temp; + celsius = temp; } else if (unit.equalsIgnoreCase("F")) { - this.celsius = (temp - 32) * 5.0 / 9.0; + celsius = (temp - 32) * 5.0 / 9.0; } else if (unit.equalsIgnoreCase("K")) { - this.celsius = temp - 273.15; + celsius = temp - 273.15; } else { throw new IllegalArgumentException("Invalid unit. Use 'C', 'F', or 'K'."); } @@ -171,62 +175,71 @@ class Temperature { // Conversion formulas: // F to C: (F - 32) * 5/9 // K to C: K - 273.15 - } public double getCelsius() { // TODO: Return temperature in Celsius - return this.celsius; + return celsius; } public double getFahrenheit() { // TODO: Return temperature in Fahrenheit // C to F: C * 9/5 + 32 - return (this.celsius * 9.0 / 5.0) + 32; + return (celsius * 9.0 / 5.0) + 32; } public double getKelvin() { // TODO: Return temperature in Kelvin // C to K: C + 273.15 - return this.celsius + 273.15; + return celsius + 273.15; } public void setCelsius(double temp) { - this.celsius = temp; + celsius = temp; // TODO: Set temperature in Celsius } public void setFahrenheit(double temp) { - this.celsius = (temp - 32) * 5.0 / 9.0; - + celsius = (temp - 32) * 5.0 / 9.0; // TODO: Set temperature in Fahrenheit (convert to Celsius) } public void setKelvin(double temp) { - this.celsius = temp - 273.15; + celsius = temp - 273.15; // TODO: Set temperature in Kelvin (convert to Celsius) } public boolean isFreezingWater() { - return this.celsius + 273.15; + return celsius <= 0.0; // TODO: Return true if water would freeze (0°C or below) } public boolean isBoilingWater() { - + return celsius >= 100.0; // TODO: Return true if water would boil (100°C or above) - return false; } public String getTemperatureCategory() { + if (celsius < 0) { + return "Cold"; + } else if (celsius <= 20) { + return "Mild"; + } else if (celsius <= 35) { + return "Hot"; + } else { + return "Extreme"; + } + } +} // TODO: Return category based on Celsius // Below 0: "Cold" // 0-20: "Mild" // 21-35: "Hot" // Above 35: "Extreme" - return ""; - } -} + + + + // Exercise 5: Shopping cart with item management class ShoppingCart { @@ -234,6 +247,7 @@ class ShoppingCart { ArrayList prices; public ShoppingCart() { + // TODO: Initialize empty lists } From 28270ff229e37fd6247e87f257944349f378879c Mon Sep 17 00:00:00 2001 From: Jobonsu4 Date: Fri, 25 Jul 2025 15:41:45 -0400 Subject: [PATCH 7/8] changes --- java-org/instance-methods/topic.jsh | 210 ++++++++++++++++++++-------- 1 file changed, 154 insertions(+), 56 deletions(-) diff --git a/java-org/instance-methods/topic.jsh b/java-org/instance-methods/topic.jsh index 940f881..7106fd4 100644 --- a/java-org/instance-methods/topic.jsh +++ b/java-org/instance-methods/topic.jsh @@ -247,179 +247,277 @@ class ShoppingCart { ArrayList prices; public ShoppingCart() { - + items = new ArrayList<>(); + prices = new ArrayList<>(); // TODO: Initialize empty lists } public void addItem(String item, double price) { + items.add(item); + prices.add(price); + // TODO: Add item and price to respective lists } public void removeItem(String item) { + int index = items.indexOf(item); + + if (index != -1) { + items.remove(index); + prices.remove(index); // TODO: Remove first occurrence of item and its corresponding price } + public int getItemCount() { // TODO: Return total number of items - return 0; + return items.size(); } public double calculateTotal() { - // TODO: Return sum of all prices - return 0.0; + double total = 0.0; + for (double price : prices) { + total += price; + } + return total; } public double calculateAverage() { // TODO: Return average price per item - return 0.0; + if (prices.isEmpty()) { + return 0.0; + } + return calculateTotal() / prices.size(); } public String getMostExpensive() { // TODO: Return name of most expensive item - return ""; + if (prices.isEmpty()) return ""; + double maxPrice = prices.get(0); + int index = 0; + for (int i = 1; i < prices.size(); i++) { + if (prices.get(i) > maxPrice) { + maxPrice = prices.get(i); + index = i; + } + } + return items.get(index); } public String getCheapest() { + if (prices.isEmpty()) return ""; + double minPrice = prices.get(0); + int index = 0; + for (int i = 1; i < prices.size(); i++) { + if (prices.get(i) < minPrice) { + minPrice = prices.get(i); + index = i; + } + } + return items.get(index); // TODO: Return name of cheapest item - return ""; } public boolean containsItem(String item) { + return items.contains(item); // TODO: Check if item exists in cart - return false; } public void clear() { + items.clear(); + prices.clear(); // TODO: Remove all items and prices } } - +} + // Exercise 6: Bank account with transaction management class BankAccount { String accountNumber; double balance; ArrayList transactionHistory; - + public BankAccount(String accountNumber) { - // TODO: Initialize account number, set balance to 0, create empty history + this.accountNumber = accountNumber; + this.balance = 0.0; + this.transactionHistory = new ArrayList<>(); } - + public boolean deposit(double amount) { - // TODO: Add money (validate amount > 0) - // Add transaction to history: "Deposited $XX.XX" - // Return true if successful - return false; + if (amount > 0) { + balance += amount; + transactionHistory.add(String.format("Deposited $%.2f", amount)); + return true; + } else { + transactionHistory.add(String.format("Failed deposit $%.2f", amount)); + return false; + } } - + public boolean withdraw(double amount) { - // TODO: Remove money if sufficient funds (amount > 0 and balance >= amount) - // Add transaction to history: "Withdrew $XX.XX" or "Failed withdrawal $XX.XX" - // Return true if successful - return false; + if (amount > 0 && balance >= amount) { + balance -= amount; + transactionHistory.add(String.format("Withdrew $%.2f", amount)); + return true; + } else { + transactionHistory.add(String.format("Failed withdrawal $%.2f", amount)); + return false; + } } - + public boolean transfer(BankAccount toAccount, double amount) { - // TODO: Transfer money to another account - // Should withdraw from this account and deposit to other account - // Add transaction to history for both accounts - // Return true if successful + if (this.withdraw(amount)) { + boolean success = toAccount.deposit(amount); + if (success) { + transactionHistory.add(String.format("Transferred $%.2f to account %s", amount, toAccount.getAccountNumber())); + toAccount.transactionHistory.add(String.format("Received $%.2f from account %s", amount, this.accountNumber)); + return true; + } else { + // Rollback withdrawal if deposit fails + this.deposit(amount); + } + } + transactionHistory.add(String.format("Failed transfer $%.2f to account %s", amount, toAccount.getAccountNumber())); return false; } - + public double getBalance() { - // TODO: Return current balance - return 0.0; + return balance; } - + public String getAccountNumber() { - // TODO: Return account number - return ""; + return accountNumber; } - + public ArrayList getTransactionHistory() { - // TODO: Return copy of transaction history - return new ArrayList<>(); + return new ArrayList<>(transactionHistory); // Defensive copy } - + public int getTransactionCount() { - // TODO: Return number of transactions - return 0; + return transactionHistory.size(); } - + public boolean hasInsufficientFunds(double amount) { - // TODO: Check if withdrawal would overdraft - return false; + return balance < amount; } - + public double calculateInterest(double rate) { - // TODO: Return interest amount for given rate - // Interest = balance * rate - return 0.0; + return balance * rate; } } + + // Exercise 7: Student grade book class StudentGradeBook { String studentName; ArrayList grades; public StudentGradeBook(String name) { + studentName = name; + grades = new ArrayList<>(); // TODO: Set student name and initialize empty grades list } public boolean addGrade(double grade) { + if (grade >= 0 && grade <= 100) { + grades.add(grade); + return true; + } + return false; // TODO: Add grade (validate 0-100 range) // Return true if valid and added - return false; } public boolean removeLowestGrade() { + if (grades.isEmpty()) return false; + + double lowest = grades.get(0); + int index = 0; + for (int i = 1; i < grades.size(); i++) { + if (grades.get(i) < lowest) { + lowest = grades.get(i); + index = i; + } + } + grades.remove(index); + return true; + } // TODO: Remove the lowest grade // Return true if grade was removed - return false; - } + public int getGradeCount() { + return grades.size(); // TODO: Return number of grades - return 0; } public double calculateAverage() { // TODO: Return average of all grades - return 0.0; + if (grades.isEmpty()) return 0.0; + + double sum = 0.0; + for (double g : grades) { + sum += g; + } + return sum / grades.size(); } + public double getHighestGrade() { // TODO: Return highest grade - return 0.0; + if (grades.isEmpty()) return 0.0; + + double highest = grades.get(0); + for (double g : grades) { + if (g > highest) highest = g; + } + return highest; } public double getLowestGrade() { + if (grades.isEmpty()) return 0.0; + + double lowest = grades.get(0); + for (double g : grades) { + if (g < lowest) lowest = g; + } + return lowest; // TODO: Return lowest grade - return 0.0; } public String getLetterGrade() { + double avg = calculateAverage(); + if (avg >= 90) return "A"; + else if (avg >= 80) return "B"; + else if (avg >= 70) return "C"; + else if (avg >= 60) return "D"; + else return "F"; // TODO: Return letter grade based on average // A: 90-100, B: 80-89, C: 70-79, D: 60-69, F: below 60 - return ""; + } public boolean isPassingGrade() { + return calculateAverage() >= 60; // TODO: Return true if average >= 60 - return false; + } public String getGradesSummary() { + return String.format("Student: %s, Grades: %d, Average: %.2f, Letter: %s", + studentName, getGradeCount(), calculateAverage(), getLetterGrade()); // TODO: Return string with key statistics // Format: "Student: [name], Grades: [count], Average: [avg], Letter: [letter]" - return ""; } public boolean hasGradeAbove(double threshold) { - // TODO: Check if any grade exceeds threshold + for (double g : grades) { + if (g > threshold) return true; + } return false; } + // TODO: Check if any grade exceeds threshold } // Test your implementations below: From f200df6dfea6d3889d835093fb9d20e243573753 Mon Sep 17 00:00:00 2001 From: Jobonsu4 Date: Mon, 28 Jul 2025 13:28:42 -0400 Subject: [PATCH 8/8] changes --- java-org/parameters-and-return-values/topic.jsh | 5 ++++- method-writing/arraylists/topic.jsh | 1 + 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/java-org/parameters-and-return-values/topic.jsh b/java-org/parameters-and-return-values/topic.jsh index 35a3688..b006cb6 100644 --- a/java-org/parameters-and-return-values/topic.jsh +++ b/java-org/parameters-and-return-values/topic.jsh @@ -10,9 +10,12 @@ import java.util.Arrays; class DataValidator { public String validateEmail(String email) { + // TODO: Return "Valid" if email contains @ and ., otherwise return specific error message // Check for null, empty, missing @, missing . - return ""; + public boolean isValidEmail(String email) { + return email != null && email.contains("@") && email.contains("."); + } } public boolean validatePassword(String password, int minLength, boolean requireSpecial) { diff --git a/method-writing/arraylists/topic.jsh b/method-writing/arraylists/topic.jsh index 154c40a..a7bad05 100644 --- a/method-writing/arraylists/topic.jsh +++ b/method-writing/arraylists/topic.jsh @@ -140,6 +140,7 @@ public void removeAllOccurrences(ArrayList list, String item) { // Your code here } +} // Exercise 6: List Operations // Remove all items from list