diff --git a/java-org/classes-and-objects/NOTES.md b/java-org/classes-and-objects/NOTES.md index 2efd16f..bb7c953 100644 --- a/java-org/classes-and-objects/NOTES.md +++ b/java-org/classes-and-objects/NOTES.md @@ -36,6 +36,7 @@ class Person { public Person(String name, int age) { this.name = name; // 'this' refers to the current object this.age = age; + return null; } // Methods - what a Person object can do diff --git a/java-org/classes-and-objects/README.md b/java-org/classes-and-objects/README.md index 441917f..a5ce6c2 100644 --- a/java-org/classes-and-objects/README.md +++ b/java-org/classes-and-objects/README.md @@ -69,8 +69,8 @@ After completing each exercise, test your classes and methods: ```java // Example tests -Person person = createPerson("Alice", 30); -System.out.println(person.introduce()); +Person Person = createPerson("Alice", 30); + return (person.introduce()); BankAccount account = createBankAccount("123456"); account.deposit(100.0); diff --git a/java-org/classes-and-objects/topic.jsh b/java-org/classes-and-objects/topic.jsh index 9957b66..2dbe1b0 100644 --- a/java-org/classes-and-objects/topic.jsh +++ b/java-org/classes-and-objects/topic.jsh @@ -4,106 +4,185 @@ 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 - +class Person { + 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 + String accountNumber; + double balance; - // Your deposit method here - - // Your withdraw method here - - // Your getBalance method here - - // Your getAccountInfo method here + public BankAccount(String accountNumber, double balance) { + this.accountNumber = accountNumber; + this.balance = 0.0; + } + + public void deposit(double amount) { + balance += amount; + } + + public void withdraw(double amount) { + if (balance >= amount) { + balance -= amount; + } else { + System.out.println("insufficient funds"); + } + } + + public double getBalance() { + return balance; + } + + public String getAccountInfo() { + return "Hello, " + accountNumber + " your balance is " + balance + " ."; + } } // Exercise 3: Object Creation and Usage // Create and return a Person object public Person createPerson(String name, int age) { - // Your code here - + return new Person(name ,age); } // Create and return a BankAccount object public BankAccount createBankAccount(String accountNumber) { - // Your code here + return new BankAccount(accountNumber,0.0); } // Demonstrate creating and using a Person object public void demonstratePersonUsage() { - // Your code here + Person person = new Person(name, age); + System.out.println(Person.introduce()); } // Exercise 4: Working with Multiple Objects // Create a Car class class Car { - // Your fields here - - // Your constructor here - - // Your getCarInfo method here - - // Your isClassic method here (car is classic if > 25 years old) - + String brand; + String model; + int year; + + public Car(String brand, String model, int year) { + this.brand = brand; + this.model = model; + this.year = year; + } + + public String getCarInfo() { + return " Car brand: " + brand + " , Model: " + model + " ,Year made: " + year + "."; + } + + public boolean isClassic() { + int currentYear = java.time.Year.now().getValue(); + 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; + } } // Exercise 5: Object State and Behavior // Create a Counter class that can increment/decrement class Counter { - // Your fields here - - // Your constructor here - - // Your increment method here - - // Your decrement method here - - // Your reset method here - - // Your getCount method here - + int count; + + public Counter() { + this.count = 0; + } + + public Counter(int count) { + this.count = count; + } + + public int increment() { + count++; + return count; + } + + public int decrement() { + count--; + return count; + } + + public void reset() { + count = 0; + } + + public int getCount() { + return count; + } } // Exercise 6: Class with Validation // Create a Student class with input validation class Student { - // Your fields here - - // Your constructor with validation here - - // Your isHonorStudent method here - - // Your getStudentInfo method here + String name; + int grade; + double gpa; + + public Student( String name, int grade, double gpa) { + this.name = name; + if (grade >= 1 && grade <= 12) { + this.grade = grade; + } else { + System.out.println("Grade must be between 1 and 12"); + this.grade = 1; + } + if (gpa >= 0.0 && gpa <= 4.0) { + this.gpa = gpa; + } else { + System.out.println("GPA must be between 0.0 and 4.0"); + this.gpa = 0.0; + } + } + + public boolean isHonorStudent() { + return gpa >= 3.5; + } + + public String getStudentInfo() { + return "Student record: Name: " + name + " Grade: " + grade + " GPA: " + gpa + "."; + } } // Exercise 7: Object Interaction // Create a Book class class Book { - // Your fields here + String title; + String author; + boolean isCheckedOut; - // Your constructor here + public Book(String title, String author, boolean isCheckedOut) { + this.title = title; + this.author = author; + this.isCheckedOut = isCheckedOut; + } // Add any helpful methods here @@ -111,22 +190,59 @@ class Book { // Create a Library class that manages books class Library { - // Your fields here - - // Your constructor here - - // Your addBook method here - - // Your checkOutBook method here - - // Your returnBook method here + ArrayList books; + String title; + + public Library() { + this.title = "Untitled Library"; + this.books = new ArrayList<>(); +} - // Your getAvailableBooks method here + public Library(String title) { + this.title = title; + this.books = new ArrayList<>(); + } + + public void addBook(Book book) { + books.add(book); + } + + public void checkOutBook(String title) { + for (Book book : books) { + if (book.title.equals(title) && !book.isCheckedOut) { + book.isCheckedOut = true; + break; + } + } + } + + public void returnBook(String title) { + for (Book book : books) { + if (book.title.equals(title) && book.isCheckedOut) { + book.isCheckedOut = false; + break; + } + } + + } + + public String getAvailableBooks() { + StringBuilder available = new StringBuilder(); + for (Book book : books) { + if (!book.isCheckedOut) { + if (available.length() > 0) { + available.append(", "); + } + available.append(book.title); + } + } + return available.toString(); + } } // 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 +308,4 @@ System.out.println("After checking out 1984: " + library.getAvailableBooks()); library.returnBook("1984"); System.out.println("After returning 1984: " + library.getAvailableBooks()); -*/ + diff --git a/java-org/instance-methods/topic.jsh b/java-org/instance-methods/topic.jsh index 66534a0..b1bd36d 100644 --- a/java-org/instance-methods/topic.jsh +++ b/java-org/instance-methods/topic.jsh @@ -7,32 +7,35 @@ 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) { + System.out.println("Can't divide by 0"); + return; + } + result /= value; } public double getResult() { - // TODO: Return the current result - return 0.0; + return result; } public void clear() { - // TODO: Reset result to 0.0 + result = 0.0; } } @@ -41,47 +44,43 @@ class TextProcessor { String text; public TextProcessor(String initialText) { - // TODO: Set the text field + this.text = initialText; } public void setText(String newText) { - // TODO: Update the text + text = newText; } public String getText() { - // TODO: Return the current text - return ""; + return text; } public int getLength() { - // TODO: Return length of text - return 0; + return text.length(); } public String toUpperCase() { - // TODO: Return text in uppercase (don't modify original) - return ""; + return text.toUpperCase(); } public String toLowerCase() { - // TODO: Return text in lowercase (don't modify original) - return ""; + return text.toLowerCase(); } public String reverse() { - // TODO: Return reversed text - return ""; + return new StringBuilder(text).reverse().toString(); } public boolean contains(String substring) { - // TODO: Check if text contains substring + if (text.contains(substring)) { + return true; + } return false; } public int getWordCount() { - // TODO: Return number of words in text - // Hint: Split by spaces and count non-empty parts - return 0; + if (text == null || text.trim().isEmpty()) return 0; + return text.trim().split("\\s+").length; } } @@ -91,42 +90,45 @@ class Counter { int step; public Counter(int initialCount, int stepValue) { - // TODO: Initialize count and step + this.count = initialCount; + this.step = stepValue; } public void increment() { - // TODO: Increase count by step + count += step; } public void decrement() { - // TODO: Decrease count by step + count -= step; } public void reset() { - // TODO: Set count back to 0 + count = 0; } public int getCount() { - // TODO: Return current count - return 0; + return count; } public void setStep(int newStep) { - // TODO: Change the step value + step = newStep; } public int getStep() { - // TODO: Return current step value - return 0; + return step; } public boolean isPositive() { - // TODO: Return true if count > 0 + if (count > 0) { + return true; + } return false; } public boolean isNegative() { - // TODO: Return true if count < 0 + if (count < 0) { + return true; + } return false; } } @@ -136,59 +138,67 @@ class Temperature { double celsius; public Temperature(double temp, String unit) { - // TODO: Convert temperature to Celsius and store - // unit can be "C", "F", or "K" - // Conversion formulas: - // F to C: (F - 32) * 5/9 - // K to C: K - 273.15 + if (unit.equalsIgnoreCase("C")) { + celsius = temp; + } else if (unit.equalsIgnoreCase("F")) { + celsius = (temp - 32) * 5.0 / 9.0; + } else if (unit.equalsIgnoreCase("K")) { + celsius = temp - 273.15; + } else { + celsius = 0.0; + } } public double getCelsius() { - // TODO: Return temperature in Celsius - return 0.0; + return celsius; } public double getFahrenheit() { - // TODO: Return temperature in Fahrenheit - // C to F: C * 9/5 + 32 - return 0.0; + return celsius * 9.0 / 5.0 + 32.0; } public double getKelvin() { - // TODO: Return temperature in Kelvin - // C to K: C + 273.15 - return 0.0; + return celsius + 273.15; } public void setCelsius(double temp) { - // TODO: Set temperature in Celsius + celsius = temp; } public void setFahrenheit(double temp) { - // TODO: Set temperature in Fahrenheit (convert to Celsius) + celsius = (temp - 32) * 5.0 / 9.0; } public void setKelvin(double temp) { - // TODO: Set temperature in Kelvin (convert to Celsius) + celsius = temp - 273.15; } public boolean isFreezingWater() { - // TODO: Return true if water would freeze (0°C or below) + if (celsius <= 0.0) { + return true; + } return false; } public boolean isBoilingWater() { - // TODO: Return true if water would boil (100°C or above) + if (celsius >= 100.0) { + return true; + } return false; } public String getTemperatureCategory() { - // TODO: Return category based on Celsius - // Below 0: "Cold" - // 0-20: "Mild" - // 21-35: "Hot" - // Above 35: "Extreme" - return ""; + if (celsius <= 0.0) { + return "Cold"; + } else if (celsius > 0 && celsius <= 20) { + return "Mild"; + } else if (celsius > 20 && celsius < 35) { + return "Hot"; + } else if (celsius >= 35) { + return "Extreme"; + } else { + return ""; + } } } @@ -198,49 +208,74 @@ class ShoppingCart { ArrayList prices; public ShoppingCart() { - // TODO: Initialize empty lists + items = new ArrayList<>(); + prices = new ArrayList<>(); } public void addItem(String item, double price) { - // TODO: Add item and price to respective lists + items.add(item); + prices.add(price); + } public void removeItem(String item) { - // TODO: Remove first occurrence of item and its corresponding price + int index = items.indexOf(item); + if (index != -1) { + items.remove(index); + prices.remove(index); + } } 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 sum =0.0; + for (double price : prices) { + sum += price; + } + return sum; } public double calculateAverage() { - // TODO: Return average price per item - return 0.0; + return prices.stream().mapToDouble(Double::doubleValue).average().orElse(0.0); } public String getMostExpensive() { - // TODO: Return name of most expensive item - return ""; + if (items.isEmpty()) return ""; + double maxPrice = prices.get(0); + int maxIndex = 0; + for (int i = 1; i < prices.size(); i++) { + if (prices.get(i) > maxPrice) { + maxPrice = prices.get(i); + maxIndex = i; + } + } + return items.get(maxIndex); } public String getCheapest() { - // TODO: Return name of cheapest item - return ""; + if (items.isEmpty()) return ""; + double minPrice = prices.get(0); + int minIndex = 0; + for (int i = 1; i < prices.size(); i++) { + if (prices.get(i) < minPrice) { + minPrice = prices.get(i); + minIndex = i; + } + } + return items.get(minIndex); } public boolean containsItem(String item) { - // TODO: Check if item exists in cart - return false; + return items.contains(item); + } public void clear() { - // TODO: Remove all items and prices + items.clear(); + prices.clear(); } } @@ -251,60 +286,66 @@ class BankAccount { 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 + if (amount > 0) { + balance += amount; + transactionHistory.add(String.format("Deposited $%.2f", amount)); + return true; + } 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 + if (amount > 0 && balance >= amount) { + balance -= amount; + transactionHistory.add(String.format("Withdrawal $%.2f", amount)); + return true; + } + transactionHistory.add(String.format("Withdrawal Failed $%.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 - return false; + if (amount > 0 && balance >= amount) { + balance -= amount; + transactionHistory.add(String.format("Transferred $%.2f to %s", amount, toAccount.accountNumber)); + toAccount.balance += amount; + toAccount.transactionHistory.add(String.format("Received $%.2f from %s", amount, this.accountNumber)); + return true; + } else { + transactionHistory.add(String.format("Transfer Failed $%.2f to %s", amount, toAccount.accountNumber)); + 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 transactionHistory; } 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; } } @@ -314,60 +355,102 @@ class StudentGradeBook { ArrayList grades; public StudentGradeBook(String name) { - // TODO: Set student name and initialize empty grades list + this.studentName = name; + grades = new ArrayList<>(); } public boolean addGrade(double grade) { // TODO: Add grade (validate 0-100 range) // Return true if valid and added + if (grade >= 0 && grade <= 100) { + grades.add(grade); + return true; + } return false; } public boolean removeLowestGrade() { - // TODO: Remove the lowest grade - // Return true if grade was removed - return false; + if (grades.isEmpty()) return false; + double min = grades.get(0); + int minIndex = 0; + for (int i = 1; i < grades.size(); i++) { + if (grades.get(i) < min) { + min = grades.get(i); + minIndex = i; + } + } + grades.remove(minIndex); + return true; } public int getGradeCount() { - // TODO: Return number of grades - return 0; + return grades.size(); } public double calculateAverage() { - // TODO: Return average of all grades - return 0.0; + if (grades.isEmpty()) return 0.0; + double sum = 0.0; + for (double grade : grades) { + sum += grade; + } + return sum / grades.size(); } + public double getHighestGrade() { - // TODO: Return highest grade - return 0.0; + if (grades.isEmpty()) return 0.0; + double max = grades.get(0); + for (double grade : grades) { + if (grade > max) { + max = grade; + } + } + return max; } public double getLowestGrade() { - // TODO: Return lowest grade - return 0.0; + if (grades.isEmpty()) return 0.0; + double min = grades.get(0); + for (double grade : grades) { + if (grade < min) { + min = grade; + } + } + return min; } public String getLetterGrade() { - // TODO: Return letter grade based on average - // A: 90-100, B: 80-89, C: 70-79, D: 60-69, F: below 60 - return ""; + double avg = calculateAverage(); + if (avg >= 90 && avg <= 100) { + return "A"; + } else if (avg >= 80) { + return "B"; + } else if (avg >= 70) { + return "C"; + } else if (avg >= 60) { + return "D"; + } else { + return "F"; + } } public boolean isPassingGrade() { - // TODO: Return true if average >= 60 - return false; + return calculateAverage() >= 60.0; } public String getGradesSummary() { - // TODO: Return string with key statistics - // Format: "Student: [name], Grades: [count], Average: [avg], Letter: [letter]" - return ""; + int count = getGradeCount(); + double avg = calculateAverage(); + String letter = getLetterGrade(); + return String.format("Student: %s, Grades: %d, Average: %.2f, Letter: %s.", studentName, count, avg, letter); } public boolean hasGradeAbove(double threshold) { - // TODO: Check if any grade exceeds threshold + for (double grade : grades) { + if (grade > threshold) { + return true; + } + } return false; } } diff --git a/java-org/parameters-and-return-values/topic.jsh b/java-org/parameters-and-return-values/topic.jsh index 35a3688..4e6335a 100644 --- a/java-org/parameters-and-return-values/topic.jsh +++ b/java-org/parameters-and-return-values/topic.jsh @@ -10,38 +10,79 @@ 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 ""; + if (email != null && email.contains("@") && email.contains(".")) { + return "Valid"; + } else { + return "Invalid"; + } } public boolean validatePassword(String password, int minLength, boolean requireSpecial) { - // TODO: Return true if password meets criteria - // Check length and special characters (!@#$%^&*) if required - return false; + if (password == null || password.length() < minLength) { + return false; + } + if (requireSpecial) { + String specialChars = "!@#$%^&*"; + boolean hasSpecial = false; + for (char c : password.toCharArray()) { + if (specialChars.indexOf(c) != -1) { + hasSpecial = true; + break; + } + } + if (!hasSpecial) return false; + } + return true; } public int validateAge(int age, int minAge, int maxAge) { - // TODO: Return -1 if too young, 0 if valid, 1 if too old - return 0; + if (age < minAge) { + return -1; + } else if (age > maxAge) { + return 1; + } else { + return 0; + } } public String validatePhoneNumber(String phone, String countryCode) { - // TODO: Return formatted number like "+1-555-123-4567" or "INVALID" - // Simple validation: remove non-digits, check length - return ""; + String digits = phone.replaceAll("\\D", ""); + if (digits.length() != 10) { + return "INVALID"; + } + String formatted = String.format("%s-%s-%s-%s", + countryCode, + digits.substring(0, 3), + digits.substring(3, 6), + digits.substring(6) + ); + return formatted; } public boolean[] validateCreditCard(String cardNumber, String expiryDate) { - // TODO: Return array [isValidNumber, isNotExpired] - // Simple check: 16 digits for number, MM/YY format for expiry (assume current year 2025) - return new boolean[2]; + boolean[] result = new boolean[2]; + + String digits = cardNumber.replaceAll("\\D",""); + result[0] = digits.length() == 16; + + result[1] = false; + if (expiryDate != null && expiryDate.matches("\\d{2}/\\d{2}")) { + String[] parts = expiryDate.split("/"); + int month = Integer.parseInt(parts[0]); + int year = Integer.parseInt(parts[1]) + 2000; + if (month >= 1 && month <= 12 && year >= 2025) { + result[1] = true; + } + } + return result; } public String getValidationSummary(String email, String password, int age) { - // TODO: Return summary string of all validations - // Format: "Email: [result], Password: [result], Age: [result]" - return ""; + String emailResult = validateEmail(email); + String passwordResult = validatePassword(password, 8, true) ? "Valid" : "Invalid"; + int ageResult = validateAge(age, 18, 65); + String ageStr = (ageResult == 0) ? "Valid" : (ageResult == -1 ? "Too Young" : "Too Old"); + return String.format("Email: %s, Password: %s, Age: %s", emailResult, passwordResult, ageStr); } } @@ -49,14 +90,35 @@ class DataValidator { class MathEngine { public double calculate(double a, double b, String operation) { - // TODO: Perform operation (+, -, *, /, %) - // Return 0.0 for invalid operation or division by zero - return 0.0; + switch (operation) { + case "+": + return a + b; + case "-": + return a - b; + case "*": + return a * b; + case "/": + if (b == 0.0) return 0.0; + return a / b; + case "%": + if (b == 0.0) return 0.0; + return a % b; + default: + return 0.0; + } } public double[] findRange(double[] numbers) { - // TODO: Return [min, max] or [0.0, 0.0] if empty array - return new double[2]; + if (numbers == null || numbers.length == 0) { + return new double[]{0.0, 0.0}; + } + double min = numbers[0]; + double max = numbers[0]; + for (int i = 1; i < numbers.length; i++) { + if (numbers[i] < min) min = numbers[i]; + if (numbers[i] > max) max = numbers[i]; + } + return new double[] {min,max}; } public String statisticalSummary(double[] values) { diff --git a/method-writing/arraylists/topic.jsh b/method-writing/arraylists/topic.jsh index 84c9cad..372dc04 100644 --- a/method-writing/arraylists/topic.jsh +++ b/method-writing/arraylists/topic.jsh @@ -6,138 +6,161 @@ import java.util.Collections; // Exercise 1: ArrayList Basics // Create and return a new ArrayList of Strings public ArrayList createStringList() { - // Your code here - + return new ArrayList<>(); } // Return size of ArrayList (handle null) public int getListSize(ArrayList list) { - // Your code here - + if (list == null) return 0; + return list.size(); } // Exercise 2: Adding Elements // Add item to the end of the list public void addToEnd(ArrayList list, String item) { - // Your code here + list.add(item); } // Add item to the beginning of the list public void addToBeginning(ArrayList list, String item) { - // Your code here + list.add(0, item); } // Add item at specific position public void addAtPosition(ArrayList list, int index, String item) { - // Your code here + list.add(index, item); } // Exercise 3: Accessing Elements // Return first item (null if empty) public String getFirstItem(ArrayList list) { - // Your code here - + if (list == null || list.isEmpty()) return null; + return list.get(0); } // Return last item (null if empty) public String getLastItem(ArrayList list) { - // Your code here - + if (list == null || list.isEmpty()) return null; + return list.get(list.size(0) - 1); } // Return item at specific index (null if out of bounds) public String getItemAt(ArrayList list, int index) { - // Your code here - + if (index >= 0 && index < list.size()) { + String item = list.get(index); + } + return list.get(index); } // Exercise 4: Searching and Contains // Return true if list contains the item public boolean containsItem(ArrayList list, String item) { - // Your code here + return list.contains(item); } // Return index of first occurrence (-1 if not found) public int findPosition(ArrayList list, String item) { - // Your code here - + if (list == null) return -1; + list.indexOf(item); } // Count how many times item appears in list public int countOccurrences(ArrayList list, String item) { - // Your code here - + if (list == null) return 0; + int count = 0; + for (String s : list) { + if (s != null && s.equals(item)) { + count++; + } + } + return count; } // Exercise 5: Removing Elements // Remove and return first item (null if empty) public String removeFirstItem(ArrayList list) { - // Your code here + if (list == null || list.isEmpty()) return null; + return list.remove(0); } // Remove and return last item (null if empty) public String removeLastItem(ArrayList list) { - // Your code here + if (list == null || list.isEmpty()) return null; + return list.remove(list.size() - 1); } // Remove item at specific index (null if out of bounds) public String removeAtPosition(ArrayList list, int index) { - // Your code here + if (list == null || list.isEmpty() || index < 0 || index >= list.size()) return null; + return list.remove(index); } // Remove all occurrences of an item public void removeAllOccurrences(ArrayList list, String item) { - // Your code here + if (list == null) return; + list.removeIf(s -> s != null && s.equals(item)); } // Exercise 6: List Operations // Remove all items from list public void clearList(ArrayList list) { - // Your code here - + list.clear(); } // Create a copy of the list public ArrayList copyList(ArrayList original) { - // Your code here + ArrayList copy = new ArrayList<>(original); + return copy; } // Combine two lists into one new list public ArrayList mergeLists(ArrayList list1, ArrayList list2) { - // Your code here - + ArrayList merged = new ArrayList<>(); + if (list1 != null) merged.addAll(list1); + if (list2 != null) merged.addAll(list2); + return merged; } + + // Exercise 7: List Analysis // Find and return the longest string in the list public String findLongestString(ArrayList list) { - // Your code here + if (list.isEmpty()) return null; + String longest = list.get(0); + for (String item : list) { + if (item.length() > longest.length()) { + longest = item; + } + } + return longest; } // Sort the list alphabetically (modifies the original list) public void sortList(ArrayList list) { - // Your code here + if (list == null) return; // Optional: handle null lists safely + Collections.sort(list); } // Convert ArrayList to String array public String[] convertToArray(ArrayList list) { - // Your code here + return list.toArray(new String[0]); } // 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 @@ -190,4 +213,4 @@ for (int i = 0; i < array.length; i++) { if (i < array.length - 1) System.out.print(", "); } System.out.println("]"); -*/ + diff --git a/method-writing/bool-and-boolean/topic.jsh b/method-writing/bool-and-boolean/topic.jsh index 3b9d7c0..45c2968 100644 --- a/method-writing/bool-and-boolean/topic.jsh +++ b/method-writing/bool-and-boolean/topic.jsh @@ -4,28 +4,26 @@ // Exercise 1: Basic Boolean Methods // Return true if person is 18 or older public boolean isAdult(int age) { - // Your code here - + return age >= 18; } // Exercise 2: Number Range Checker // Return true if number is between min and max (inclusive) public boolean isInRange(int number, int min, int max) { - // Your code here + return number >= min && number <= max; } // Exercise 3: String Validation // Return true if email contains both "@" and "." characters public boolean isValidEmail(String email) { - // Your code here - + return (email.contains("@") && email.contains(".")); } // 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; } @@ -33,29 +31,35 @@ public boolean isEven(int number) { // 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) { - // Your code here - + return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); } // 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.length() < 8) return false; + for (char c: password.toCharArray()) { + if (Character.isUpperCase(c)) { + return true; + } + } + return false; } // 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 > b + c) && (a + c > b); } // 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 + if (b1 == b2) return true; + if (b1 == null || b2 == null) return false; + return b1.equals(b2); } @@ -63,27 +67,27 @@ public boolean compareBoolean(Boolean b1, Boolean b2) { // Simulate basic logic gates public boolean andGate(boolean a, boolean b) { - // Your code here + return a && b; } public boolean orGate(boolean a, boolean b) { - // Your code here + return a || b; } public boolean notGate(boolean a) { - // Your code here + return !a == 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 -/* + 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 @@ -132,4 +136,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 b5a8955..4344792 100644 --- a/method-writing/double-and-double/topic.jsh +++ b/method-writing/double-and-double/topic.jsh @@ -4,118 +4,151 @@ // 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; } // 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 Math.abs(number); } // Round double to nearest integer public int roundToNearestInt(double number) { - // Your code here + return (int) Math.round(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 - y1; + 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 + return Math.max(min, Math.min(max, 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; + 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) { - // Your code here - + 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; } // 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; + for (double num : numbers) { + sum += num; + } + return sum / numbers.length; } // Calculate standard deviation of array public double calculateStandardDeviation(double[] numbers) { - // Your code here - // Hint: Standard deviation = √(Σ(x - mean)² / n) - + if (numbers == null || numbers.length == 0) { + throw new IllegalArgumentException("Array must not be empty"); + } + double mean = 0; + for (double num : numbers) { + mean += num; + } + mean /= numbers.length; + + double sumSquaredDiffs = 0; + for (double num : numbers) { + sumSquaredDiffs += Math.pow(num - mean, 2); + } + return Math.sqrt(sumSquaredDiffs / numbers.length); } // 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 @@ -157,4 +190,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 08e71d9..18d55d9 100644 --- a/method-writing/for-loops/topic.jsh +++ b/method-writing/for-loops/topic.jsh @@ -4,68 +4,97 @@ // Exercise 1: Number Sequence // Print all numbers from start to end (inclusive) public void printNumbers(int start, int end) { - // Your code here - + for(int i = start; i < end; i++) { + System.out.println(i); + } } // Exercise 2: Sum Calculator // Calculate the sum of all integers from 1 to n public int calculateSum(int n) { - // Your code here - + int sum = 0; + for(int i = 1; i <= n; i++) { + sum = sum +i; + } + return sum; } // 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 <= number; i++) { + for (int j = 1; j <= number; j++) { + System.out.print((i * j) + "\t"); + } + System.out.println(); +} } // Exercise 4: Even Numbers Only // Print all even numbers from 2 up to the limit (inclusive) public void printEvenNumbers(int limit) { - // Your code here + for (int i = 2; i <= limit; i += 2) { + System.out.println(i); +} } // Exercise 5: String Repeater // Return a string with the given text repeated the specified number of times public String repeatString(String text, int times) { - // Your code here - + StringBuilder result = new StringBuilder(); + for (int i =0; i < times; i++) { + result.append(text); + } + return result.toString(); } // Exercise 6: Factorial Calculator // Calculate n! (n factorial) using a for loop public long calculateFactorial(int n) { - // Your code here - + long result = 1; + for (int i = 2; i <= n;i++) { + result *= i; + } + return result; } // 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 num : numbers) { + sum += num; + } + 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) { - // Your code here - + for (int i = 1; i <= rows; i++) { + for (int j = 1; j <= i; j++) { + System.out.print("*"); + } + System.out.println(); + } } // Test your methods here - uncomment and modify as needed -/* + System.out.println("Testing printNumbers:"); printNumbers(1, 5); printNumbers(3, 7); @@ -107,4 +136,4 @@ System.out.println("\nTesting printStars:"); printStars(4); System.out.println(); printStars(2); -*/ + diff --git a/method-writing/if-else-statements/topic.jsh b/method-writing/if-else-statements/topic.jsh index b4c120e..064e797 100644 --- a/method-writing/if-else-statements/topic.jsh +++ b/method-writing/if-else-statements/topic.jsh @@ -4,40 +4,65 @@ // Exercise 1: Basic If Statement // Write a method that checks if someone is an adult (18 or older) public String checkAge(int age) { - // Your code here - + if (age >= 18) { + return "Adult"; + } else { + return "Minor"; + } } // 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 && score <= 89) { + return "Good"; + } else if (score >= 70 && score <= 79) { + return "Average"; + } else if (score <= 70); { + 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 "Zero"; + } else { + return "Negative"; + } } // 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 && temp <= 80) { + 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 - + if (username != null && !username.isEmpty() && password != null && !password.isEmpty()) { + return true; + } else { + return false; + } } // Test your methods here - uncomment and modify as needed -/* + System.out.println("Testing checkAge:"); System.out.println(checkAge(17)); // Should print "Minor" System.out.println(checkAge(18)); // Should print "Adult" @@ -64,4 +89,4 @@ System.out.println(validateLogin("user", "pass")); // Should print true System.out.println(validateLogin("", "pass")); // Should print false System.out.println(validateLogin("user", "")); // Should print false System.out.println(validateLogin(null, "pass")); // Should print false -*/ + diff --git a/method-writing/integer-and-int/topic.jsh b/method-writing/integer-and-int/topic.jsh index 40b670b..4127d97 100644 --- a/method-writing/integer-and-int/topic.jsh +++ b/method-writing/integer-and-int/topic.jsh @@ -4,66 +4,86 @@ // Exercise 1: Basic Math Operations // Return the sum of two integers public int calculateSum(int a, int b) { - // Your code here + return a + 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) { - // Your code here + return (a > b) ? a : b; } // Return the absolute value (always positive) public int findAbsoluteValue(int number) { - // Your code here + return Math.abs(number); } // Exercise 3: Digit Operations // 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 /= 10; + count++; + } + return count; } // Reverse the digits of a positive integer (123 becomes 321) public int reverseDigits(int number) { - // Your code here - + int reversed = 0; + while (number > 0) { + reversed = reversed * 10 + number % 10; + number /=10; + } + return reversed; } // Exercise 4: Number Classification // Return true if number is prime (only divisible by 1 and itself) public boolean isPrime(int number) { - // Your code here - + if (number <= 1) return false; + for (int i =2; i <= Math.sqrt(number); i++) { + if (number % i == 0) { + return false; + } + } + return true; } // Return true if number is a perfect square public boolean isPerfectSquare(int number) { - // Your code here - + return Math.sqrt(number) == (int)Math.sqrt(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) { - // Your code here - + int count = 0; + for (int i = number; i <= limit; i+= number) { + count++; + } + return count; } // Exercise 6: Integer Object Practice @@ -71,57 +91,93 @@ 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) { - // Your code here + if (num1 == num2) return 0; + if (num1 == null) return -1; + if (num2 == null) return 1; + return Integer.compare(num1, num2); + } // Try to parse string to Integer, return null if it fails public Integer parseIntegerSafely(String text) { - // Your code here - + try { + int number = Integer.parseInt(text); + System.out.println("Parsed: " + number); + return number; + } catch (NumberFormatException e) { + System.out.println("Invalid number format"); + return null; + } } // Exercise 7: Mathematical Sequences // Return the nth Fibonacci number (0, 1, 1, 2, 3, 5, 8, 13...) public int fibonacci(int n) { - // Your code here + 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; } // Calculate n! (n factorial) public long factorial(int n) { - // Your code here - + if (n < 0) return -1; + long result = 1; + for (int i =2; i<= n; i++) { + result *= i; + } + return result; } // Exercise 8: Number Conversion // Convert integer to binary string representation public String toBinaryString(int number) { - // Your code here + return Integer.toBinaryString(number); } // Convert binary string back to integer public int fromBinaryString(String binary) { - // Your code here + return Integer.parseInt(binary, 2); } // Exercise 9: Array Statistics // Find the maximum value in an array public int findMax(int[] numbers) { - // Your code here - + if (numbers == null || numbers.length == 0) { + throw new IllegalArgumentException("Array must not be empty"); + } + int max = numbers[0]; + for (int i = 1; i < numbers.length; i++) { + if (numbers[i] > max) { + max = numbers[i]; + } + } + return max; } // 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 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:"); System.out.println("5 + 3 = " + calculateSum(5, 3)); // Should print 8 System.out.println("4 * 6 = " + calculateProduct(4, 6)); // Should print 24 @@ -167,4 +223,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/object-references/topic.jsh b/method-writing/object-references/topic.jsh index af03712..fd829c0 100644 --- a/method-writing/object-references/topic.jsh +++ b/method-writing/object-references/topic.jsh @@ -5,140 +5,168 @@ import java.util.ArrayList; // Exercise 1: Reference Basics // Create and return array of 3 Strings public String[] createStringArray() { - // Your code here + return new String[] {"One", "Two", "Three"}; } // Check if two String references point to same object (using ==) public boolean areReferencesEqual(String str1, String str2) { - // Your code here - + return str1 == str2; } // Check if two String references have same content (using equals) public boolean areContentsEqual(String str1, String str2) { - // Your code here - + if (str1 == null && str2 == null) return true; + if (str1 == null || str2 == null) return false; + return str1.equals(str2); } // Exercise 2: Null Handling // Return true if reference is null public boolean isNullReference(Object obj) { - // Your code here - + if (obj != null) return false; + return true; } + + // 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) { - // Your code here - + if (str == null) return 0; + return str.length(); } // Exercise 3: Array References // Copy the reference (not content) of an array public int[] copyArrayReference(int[] original) { - // Your code here + return original; } // Create new array with same content public int[] copyArrayContent(int[] original) { - // Your code here - + int[] contentCopy = new int[original.length]; + for (int i = 0; i < original.length; i++) { + contentCopy[i] = original[i]; + } + return contentCopy; } // Change value in array at specified index public void modifyArray(int[] array, int index, int newValue) { - // Your code here - + array[index] = newValue; } // Exercise 4: Object State Changes // Create StringBuilder with initial text public StringBuilder createStringBuilder(String initial) { - // Your code here + return new StringBuilder(initial); } // 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) { - // Your code here - + if (sb == null) return null; + return sb.toString(); } // 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 (s != null && s.equals(target)) { + 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) { - // Your code here - + if (array == null) return; + for (int i = 0; i < array.length; i++) { + if (array[i] == null) { + array[i] = replacement; + } + } } // Exercise 6: Multiple References // Create two String literals and show they reference same object public boolean demonstrateStringPool() { - // Your code here - create two string literals with same value - // Return true if they reference the same object + String a = "Java"; + String b = "Java"; + return a == b; } // Create two String objects with 'new' and show they're different public boolean demonstrateNewString() { - // Your code here - create two strings with new String() - // Return true if they are different objects (but same content) - + String a = new String("Java"); + String b = new String("Java"); + return a != b && a.equals(b); } // Swap two references in an array public void swapReferences(StringBuilder[] array, int index1, int index2) { - // Your code here - + if (array == null || index1 < 0 || index2 < 0 || + index1 >= array.length || index2 >= array.length) { + return; + } + StringBuilder temp = array[index1]; + array[index1] = array[index2]; + array[index2] = temp; } // Exercise 7: Object Creation and References // Create and return new ArrayList public ArrayList createArrayList() { - // Your code here + return new ArrayList<>(); } // Add item to list public void addToList(ArrayList list, String item) { - // Your code here + if (list != null) { + list.add(item); + } } // Return the same list reference public ArrayList getListReference(ArrayList list) { - // Your code here + return list; } // 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 +224,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); -*/ + diff --git a/method-writing/strings/topic.jsh b/method-writing/strings/topic.jsh index 5c6fbd7..2f35581 100644 --- a/method-writing/strings/topic.jsh +++ b/method-writing/strings/topic.jsh @@ -4,122 +4,156 @@ // 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 - + if (str1 == null && str2 == null) return true; + if (str1 == null || str2 == null) return false; + return str1.equals(str2); } // Compare strings ignoring case differences public boolean compareStringsIgnoreCase(String str1, String str2) { - // Your code here - + if (str1 == null && str2 == null) return true; + if (str1 == null || str2 == null) return false; + return str1.equalsIgnoreCase(str2); } // Exercise 3: String Search and Contains // Return true if text contains the search string public boolean containsSubstring(String text, String search) { - // Your code here + if (text == null || search == null) return false; + return text.contains(search); } // Return index of first occurrence of search in text (-1 if not found) public int findFirstPosition(String text, String search) { - // Your code here + if (text == null || search == null) return -1; + return text.indexOf(search); } // Exercise 4: String Extraction // Return the first character of a string (handle empty strings) public char getFirstCharacter(String text) { - // Your code here - // Return a space ' ' for empty/null strings - + if (text == null || text.isEmpty()) return ' '; + return text.charAt(0); } // Return the last character of a string public char getLastCharacter(String text) { - // Your code here - // Return a space ' ' for empty/null strings - + if (text == null || text.isEmpty()) return ' '; + return text.charAt(text.length()-1); } // Return substring from start to end index public String getSubstring(String text, int start, int end) { - // Your code here + if (text == null || text.isEmpty()) return ""; + return text.substring(start, end); } // Exercise 5: String Modification // Convert string to uppercase (handle null) public String makeUpperCase(String text) { - // Your code here + if (text == null || text.isEmpty()) return ""; + return text.toUpperCase(); } // Convert string to lowercase (handle null) public String makeLowerCase(String text) { - // Your code here + if (text == null || text.isEmpty()) return ""; + return text.toLowerCase(); } // Remove leading and trailing spaces public String trimWhitespace(String text) { - // Your code here + if (text == null || text.isEmpty()) return ""; + return text.trim(); } // Exercise 6: String Building and Joining // Join two strings together (handle nulls) public String concatenateStrings(String str1, String str2) { - // Your code here + if (str1 == null || str2 == null || str1.isEmpty() || str2.isEmpty()) return ""; + return str1 + " " + str2; } // Repeat a string the specified number of times public String repeatString(String text, int count) { - // Your code here + StringBuilder result = new StringBuilder(); + for (int i = 0; i < count; i++) { + result.append(text); + } + return result.toString(); } // Join array of strings with a separator public String joinWithSeparator(String[] words, String separator) { - // Your code here - + if (words == null || words.length == 0) return ""; + StringBuilder result = new StringBuider(); + for (int i = 0; i < word.length; i++) { + if (word[i] != null) { + result.append(words[i]); + } + if (i < words.length -1) { + result.append(separator); + } + } + return result.toString(); } // Exercise 7: String Validation and Analysis // Return true if email contains "@" and "." characters public boolean isValidEmail(String email) { - // Your code here + boolean hasAt = email.contains("@"); + boolean hasDot = email.contains("."); + boolean validEmail = hasAt && hasDot; + return hasAt && hasDot; } // Count number of vowels (a, e, i, o, u) in string (case insensitive) public int countVowels(String text) { - // Your code here + int count = 0; + String vowels = "aeiouAEIOU"; + for (int i = 0; i < text.length(); i++) { + if (vowels.indexOf(text.charAt(i)) >= 0) { + count++; + } + } + return count; } // Return true if string reads same forwards and backwards (ignore case and spaces) public boolean isPalindrome(String text) { - // Your code here + String cleaned = text.toLowerCase().replace(" ", ""); + String reversed = new StringBuilder(cleaned).reverse().toString(); + return cleaned.equals(reversed); } // 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 +193,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 -*/ + diff --git a/method-writing/while-loops/topic.jsh b/method-writing/while-loops/topic.jsh index 12c0c61..c5a0286 100644 --- a/method-writing/while-loops/topic.jsh +++ b/method-writing/while-loops/topic.jsh @@ -4,54 +4,90 @@ // Exercise 1: Countdown // Print numbers from start down to 1, then print "Blast off!" public void countdown(int start) { - // Your code here - + while(start > 0) { + System.out.println("Count is: " + start); + start--; + } + System.out.print("Blast off!"); } // 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 = 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) { - // Your code here - + int step = 0; + while (start < target) { + start++; + step++; + } + return step; } // 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 digits = 0; + while (number != 0) { + number /= 10; + digits++; + } + return digits; } // Exercise 5: Password Strength Checker // Use a while loop to count characters and determine password strength public String checkPasswordStrength(String password) { - // Your code here - + int count = 0; + while (count < password.length()) { + count++; + } + if (count < 4) { + return "Weak"; + } else if (count < 5 && count >7) { + return "Medium"; + } else { + return "Strong"; + } } // Exercise 6: Factorial Calculator // Calculate n! (n factorial) using a while loop public long factorial(int n) { - // Your code here - + if (n < 0) return -1; + long 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; + int count = 0; + while (count < exponent) { + result *= base; + count++; + } + return result; } // Test your methods here - uncomment and modify as needed -/* + System.out.println("Testing countdown:"); countdown(5); @@ -83,4 +119,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 -*/ +