diff --git a/java-org/classes-and-objects/topic.jsh b/java-org/classes-and-objects/topic.jsh index 9957b66..36539ef 100644 --- a/java-org/classes-and-objects/topic.jsh +++ b/java-org/classes-and-objects/topic.jsh @@ -5,47 +5,76 @@ import java.util.ArrayList; // Exercise 1: Basic Class Creation // Create a Person class with name and age fields class Person { - // Your fields here + String name; + int age; - // Your constructor here + 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."; - // Your introduce() method here + } } + // 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 +public class BankAccount { + String accountNumber; + double balance; + + public BankAccount(String accountNumber) { + this.accountNumber = accountNumber; + this.balance = 0.0; + } + + public double deposit(double amount) { + balance += amount; + return balance; + } + + public double withdraw(double amount) { + if(amount > 0 && amount <= balance) { + balance -= amount; + } + return balance; + } - // Your getAccountInfo method here + public double getBalance() { + return balance; + } + + public String getAccountInfo() { + return "accountNumber: " + accountNumber + ", Balance: $" + balance; + } + + } // Exercise 3: Object Creation and Usage // Create and return a Person object public Person createPerson(String name, int age) { - // Your code here + Person person = new Person(name, age); + return person; } // Create and return a BankAccount object public BankAccount createBankAccount(String accountNumber) { - // Your code here + BankAccount account = new BankAccount(accountNumber); + return account; } // Demonstrate creating and using a Person object public void demonstratePersonUsage() { - // Your code here + Person person = createPerson("Alice", 30); + System.out.println(person.introduce()); // } @@ -53,82 +82,206 @@ public void demonstratePersonUsage() { // 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 "Car: " + brand + " " + model + ", Year: " + year; + } // Your isClassic method here (car is classic if > 25 years old) + public boolean isClassic() { + int currentYear = 2025; + return (currentYear - year) > 25; + + } + + public int getCarYear() { + return year; + } } // Compare two cars and return which is older public Car compareCars(Car car1, Car car2) { - // Your code here + if (car1.getCarYear() < car2.getCarYear()) { + return car1; + } else if (car1.getCarYear() > car2.getCarYear()){ + return car2; + } + 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 + private int count; + + public Counter() { + this.count = 0; + } + + public int increment() { + count++; + return count; + } + + public int decrement() { + if (count > 0) { + count--; + } + return count; + } + + public int reset() { + count = 0; + return count; + } + + public int getCount() { + return count; + } } +// Demonstrate the Counter classpublic class HelloWorld { + // public static void main(String[] args) + // Exercise 6: Class with Validation // Create a Student class with input validation +System.out.println("Student System"); class Student { - // Your fields here - - // Your constructor with validation here - - // Your isHonorStudent method here + String name; + int grade; + double gpa; + + public Student(String name, int grade, double gpa) throws Exception { + if ( name == null || name.isEmpty()) { + throw new Exception("Name cannot be null or empty"); + } + this.name = name; + + if (grade < 1 || grade > 12) { + throw new Exception("Grade must be between 1 and 12"); + } + this.grade = grade; + + if (gpa < 0.0 || gpa > 4.0) { + throw new Exception("GPA must be between 0.0 and"); + } + this.gpa = gpa; + + } + + public boolean isHonorStudent() { + return gpa >= 3.5; + } + // Your getStudentInfo method here + public String getStudentInfo(){ + return "Student:" + name + ", Grade: " + grade + ", GPA: " + gpa; + } } // Exercise 7: Object Interaction // Create a Book class +System.out.println("Book System"); 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 + public String getTitle() { + return title; + } + + public String getAuthor() { + return author; + } + + public boolean getIsCheckedOut() { + return isCheckedOut; + } } // Create a Library class that manages books -class Library { +System.out.println("Library System"); +public class Library { // Your fields here + ArrayList books; // Your constructor here + public Library() { + books = new ArrayList(); + } + // Your addBook method here - + public void addBook(Book book) { + books.add(book); + } + // Your checkOutBook method here - + public String checkOutBook(String title) { + for (Book book : books) { + if (book.getTitle().equalsIgnoreCase(title) && !book.getIsCheckedOut()) { + book.isCheckedOut = true; + return "Checked out; " + title; + } else if (book.getTitle().equalsIgnoreCase(title) && book.getIsCheckedOut()) { + return "Book is already checked out: " + title; + } + } + return "Book not found: " + title; + + } + // Your returnBook method here + public String returnBook(String title) { + for (Book book : books) { + if (book.getTitle().equalsIgnoreCase(title) && book.getIsCheckedOut()) { + book.isCheckedOut = false; + return "Returned Book; " + title; + } else if (book.getTitle().equalsIgnoreCase(title) && !book.getIsCheckedOut()) { + return "Book is already in the library: " + title; + } + } + return "Book not found: " + title; + } + // Your getAvailableBooks method here + public int getAvailableBooks() { + return books.size(); + } } // Test your classes here - uncomment and modify as needed -/* + System.out.println("Testing Person class:"); -Person person1 = createPerson("Alice", 30); +Person person1 = createPerson("Frank", 30); Person person2 = new Person("Bob", 25); System.out.println(person1.introduce()); System.out.println(person2.introduce()); @@ -192,4 +345,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/nested-objects/topic.jsh b/java-org/nested-objects/topic.jsh index f6d6822..d45cc5c 100644 --- a/java-org/nested-objects/topic.jsh +++ b/java-org/nested-objects/topic.jsh @@ -12,6 +12,10 @@ class Address { public Address(String street, String city, String state, String zipCode) { // TODO: Initialize all fields + this.street = street; + this.city = city; + this.state = state; + this.zipCode = zipCode; } public String getFullAddress() { @@ -428,7 +432,7 @@ class Customer { public double getTotalBalance() { // TODO: Sum balances of all accounts - return 0.0; + return 12223343450.0; } public String getAccountSummary() { diff --git a/java-org/parameters-and-return-values/NOTES.md b/java-org/parameters-and-return-values/NOTES.md index a04e45a..395a84b 100644 --- a/java-org/parameters-and-return-values/NOTES.md +++ b/java-org/parameters-and-return-values/NOTES.md @@ -15,7 +15,7 @@ A method's signature defines its interface: ```java public returnType methodName(parameterType1 param1, parameterType2 param2) { // Method body - return someValue; // Must match returnType + return someValue; } ``` @@ -36,6 +36,7 @@ public double calculateInterest(double principal, double rate, int years) { public void processNumbers(int count, double amount, boolean isActive) { // count, amount, isActive are copies of the original values // Modifying them here doesn't affect the original values + } ``` @@ -52,6 +53,7 @@ public void processList(ArrayList items) { public double findAverage(double[] numbers) { // numbers refers to the same array as the caller // You can modify array contents, but not the array reference itself + for () } ``` diff --git a/java-org/parameters-and-return-values/topic.jsh b/java-org/parameters-and-return-values/topic.jsh index 35a3688..e88fa0d 100644 --- a/java-org/parameters-and-return-values/topic.jsh +++ b/java-org/parameters-and-return-values/topic.jsh @@ -12,82 +12,195 @@ 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.contains("@") && email.contains(".")) { + return "valid"; + } + 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; + } else if (requireSpecial && !password.matches(".*[!@#$%^&*()].*")) { + 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 + if (age > maxAge) { + return 1; + } else if(age < minAge){ + return -1; + } return 0; } public String validatePhoneNumber(String phone, String countryCode) { - // TODO: Return formatted number like "+1-555-123-4567" or "INVALID" + // TODO: Return formatted number like "+1-555-123-4567" or "INVALID" 5551234567 // Simple validation: remove non-digits, check length - return ""; + String digitsOnly = phone.replaceAll("\\D", ""); + + if (digitsOnly.length() != 10) { + return "INVALID"; + } + return countryCode + "-" + digitsOnly.substring(0, 3) + "-" + digitsOnly.substring(3, 6) + "-" + digitsOnly.substring(6, 10); } 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[] cardInfo = new boolean[2]; // [false , false] + int cardNum = cardNumber.length(); + int expireMonth = Integer.parseInt(expiryDate.substring(0, 2)); + int expireYear = Integer.parseInt(expiryDate.substring(3, 5)); + + if (cardNum == 16) { + cardInfo[0] = true; // [true, false] + } + + if (expireYear >= 25) { + cardInfo[1] = true; // [true, true] + } + + return cardInfo; } public String getValidationSummary(String email, String password, int age) { // TODO: Return summary string of all validations // Format: "Email: [result], Password: [result], Age: [result]" - return ""; + + + return "Format: " + validateEmail(email) + ", Password: " + String.valueOf(validatePassword(password, 4, true)) + ", Age: " + Integer.toString(validateAge(age, 6, 18)); } } +System.out.println("=== Test2 ==="); // Exercise 2: Mathematical operations with various parameters 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) { + return 0.0; // Division by zero + } + return a / b; + case "%": + if (b == 0) { + return 0.0; // Modulo by zero + } + return a % b; + default: + return 0.0; // Invalid operation + } } - + 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[2]; + } + double min = numbers[0]; + double max = numbers[0]; + for (double num : numbers) { + if (num < min) { + min = num; + } else if (num > max) { + max = num; + } + } + return new double[]{ min, max }; } - + + // mean is the average of a set of numbers + // the median is the middle value when the numbers are sorted + // the mode is the number that appears most frequently public String statisticalSummary(double[] values) { - // TODO: Return "Mean: X.XX, Median: Y.YY, Mode: Z.ZZ" - // Return "No data" if array is empty - return ""; + String mean; + String median; + String mode; + double meanSum = 0.0; + + for (double v : values) { + meanSum += v; + } + + mean = Double.toString(meanSum / values.length); + + Arrays.sort(values); + if (values.length % 2 == 0) { + median = Double.toString((values[values.length / 2 - 1] + values[values.length / 2]) / 2); + } else { + median = Double.toString(values[values.length / 2]); + } + // Mode calculation + HashMap frequencyMap = new HashMap<>(); + + int maxCount = 1; + + for (double num : values) { + frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1); + if (frequencyMap.get(num) > maxCount) { + maxCount = frequencyMap.get(num); + } + } + mode = Integer.toString(maxCount); + + return "Mean: " + mean + ", " + "Median: " + median + ", " + "Mode: " + mode; + } public double compound(double principal, double rate, int years, boolean isAnnual) { - // TODO: Calculate compound interest - // If isAnnual=true: A = P(1 + r)^t, else: A = P(1 + r/12)^(12*t) - return 0.0; + if (isAnnual) { + return principal * Math.pow(1 + rate, years); + } else { + return principal * Math.pow(1 + rate / 12, 12 * years); + } } public double distance(double x1, double y1, double x2, double y2) { - // TODO: Return Euclidean distance between two points - // Distance = sqrt((x2-x1)² + (y2-y1)²) - return 0.0; + + return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)); } public String[] quadraticRoots(double a, double b, double c) { - // TODO: Solve ax² + bx + c = 0 - // Return array of solutions or ["NO_REAL_ROOTS"] if discriminant < 0 - return new String[0]; + + double discriminant = b * b - 4 * a * c; + if (discriminant < 0) { + return new String[] { "NO_REAL_ROOTS" }; + } else if (discriminant == 0) { + double root = -b / (2 * a); + return new String[] { String.valueOf(root) }; + } else { + double root1 = (-b + Math.sqrt(discriminant)) / (2 * a); + double root2 = (-b - Math.sqrt(discriminant)) / (2 * a); + return new String[] { String.valueOf(root1), String.valueOf(root2) }; + } } public boolean isPrime(long number) { - // TODO: Check if number is prime (handle large numbers efficiently) - return false; + if (number <= 1) return false; + if (number <= 3) return true; + if (number % 2 == 0 || number % 3 == 0) return false; + + for (long i = 5; i * i <= number; i += 6) { + if (number % i == 0 || number % (i + 2) == 0) { + return false; + } + } + return true; } } +System.out.println("=== Test3 ==="); // Exercise 3: String processing with parameter variations class TextAnalyzer { @@ -372,86 +485,86 @@ System.out.println("Phone validation: " + validator.validatePhoneNumber("5551234 System.out.println("Credit card: " + Arrays.toString(validator.validateCreditCard("1234567890123456", "12/26"))); System.out.println("Summary: " + validator.getValidationSummary("test@example.com", "Pass123!", 25)); -// Test MathEngine -System.out.println("\n=== Testing MathEngine ==="); -MathEngine math = new MathEngine(); -System.out.println("Calculate 10 + 5: " + math.calculate(10, 5, "+")); -System.out.println("Range of [1,5,3,9,2]: " + Arrays.toString(math.findRange(new double[]{1,5,3,9,2}))); -System.out.println("Statistics: " + math.statisticalSummary(new double[]{1,2,3,4,5})); -System.out.println("Compound interest: " + math.compound(1000, 0.05, 2, true)); -System.out.println("Distance (0,0) to (3,4): " + math.distance(0, 0, 3, 4)); -System.out.println("Quadratic roots x²-5x+6: " + Arrays.toString(math.quadraticRoots(1, -5, 6))); -System.out.println("Is 17 prime: " + math.isPrime(17)); - -// Test TextAnalyzer -System.out.println("\n=== Testing TextAnalyzer ==="); -TextAnalyzer analyzer = new TextAnalyzer(); -System.out.println("Extract words: " + Arrays.toString(analyzer.extractWords("Hello, World! How are you?", true, true))); -System.out.println("Find 'o' positions: " + Arrays.toString(analyzer.findPattern("Hello World", "o", false))); -System.out.println("Replace text: " + analyzer.replaceText("hello hello hello", "hello", "hi", 2)); -System.out.println("Summarize: " + analyzer.summarizeText("First sentence. Second sentence. Third sentence.", 2, true)); -System.out.println("Compare texts: " + analyzer.compareTexts("Hello", "hello", true, false)); -System.out.println("Format text: " + Arrays.toString(analyzer.formatText("This is a test", 5, "LEFT", true))); -System.out.println("Extract emails: " + analyzer.extractEmails("Contact us at info@example.com or support@test.org", "example.com")); - -// Test CollectionProcessor -System.out.println("\n=== Testing CollectionProcessor ==="); -CollectionProcessor processor = new CollectionProcessor(); -ArrayList numbers = new ArrayList<>(Arrays.asList(1, 5, 10, 15, 20)); -System.out.println("Filter 5-15 inclusive: " + processor.filterNumbers(numbers, 5, 15, true)); -ArrayList strings = new ArrayList<>(Arrays.asList("banana", "Apple", "cherry")); -System.out.println("Sort ascending, ignore case: " + processor.sortStrings(strings, true, true)); -ArrayList list1 = new ArrayList<>(Arrays.asList(1, 2, 3)); -ArrayList list2 = new ArrayList<>(Arrays.asList(3, 4, 5)); -System.out.println("Merge lists: " + processor.mergeLists(list1, list2, true)); -ArrayList words = new ArrayList<>(Arrays.asList("cat", "dog", "elephant", "ant")); -System.out.println("Group by length > 3: " + processor.groupByLength(words, 3, "GREATER")); -System.out.println("Common elements: " + processor.findCommonElements( - new ArrayList<>(Arrays.asList("apple", "banana")), - new ArrayList<>(Arrays.asList("banana", "cherry")), true)); -System.out.println("Process numbers *2: " + processor.processNumbers( - new ArrayList<>(Arrays.asList(1.0, 2.0, 3.0)), "MULTIPLY", 2.0)); - -// Test PersonFactory -System.out.println("\n=== Testing PersonFactory ==="); -PersonFactory factory = new PersonFactory(); -System.out.println("Basic person: " + factory.createBasicPerson("Alice", 30)); -System.out.println("Detailed person: " + factory.createDetailedPerson("Bob", 25, "bob@example.com", "New York")); -System.out.println("From CSV: " + factory.createPersonFromCsv("Charlie,35,charlie@test.com,Boston,true")); -System.out.println("Random person: " + factory.createRandomPerson(new String[]{"Alice", "Bob", "Carol"}, 20, 40)); -System.out.println("Validated person: " + factory.validateAndCreatePerson("Dave", 28, "dave@example.com")); -System.out.println("Batch create: " + factory.batchCreatePeople( - new String[]{"Eve", "Frank"}, new int[]{22, 33}, new String[]{"eve@test.com", "frank@test.com"})); - -// Test ConfigManager -System.out.println("\n=== Testing ConfigManager ==="); -ConfigManager config = new ConfigManager(); -System.out.println("Set setting: " + config.setSetting("timeout", 30, false)); -System.out.println("Get setting: " + config.getSetting("timeout", 10)); -System.out.println("Get string setting: " + config.getStringSetting("name", "default", true)); -System.out.println("Get int setting: " + config.getIntSetting("timeout", 10, 1, 100)); -System.out.println("Get boolean setting: " + config.getBooleanSetting("enabled", false)); -config.setSetting("app", "MyApp", true); -config.setSetting("version", "1.0", true); -System.out.println("Export JSON: " + config.exportSettings(new String[]{"app", "version"}, "JSON")); -System.out.println("Import count: " + config.importSettings("{\"test\":\"value\"}", "JSON", true)); - -// Test DatabaseQuery -System.out.println("\n=== Testing DatabaseQuery ==="); -DatabaseQuery db = new DatabaseQuery(); -System.out.println("SELECT query: " + db.select("users", new String[]{"name", "email"}, "age > ?", new Object[]{18})); -HashMap data = new HashMap<>(); -data.put("name", "John"); -data.put("age", 25); -System.out.println("INSERT query: " + db.insert("users", data, true)); -HashMap updates = new HashMap<>(); -updates.put("age", 26); -System.out.println("UPDATE query: " + db.update("users", updates, "name = ?", new Object[]{"John"})); -System.out.println("JOIN query: " + db.join("users", "orders", "LEFT", new String[]{"users.id = orders.user_id"})); -System.out.println("Build query: " + db.buildQuery("SELECT", "products", "name", "price")); -System.out.println("Execute query: " + db.executeQuery("SELECT * FROM users", new Object[]{}, true)); -System.out.println("Batch execute: " + Arrays.toString(db.batchExecute( - new String[]{"INSERT INTO users VALUES (?)", "UPDATE users SET age = ?"}, - new Object[][]{{"John"}, {30}}, false))); - -System.out.println("\n=== All Parameter and Return Value Tests Complete! ==="); +// Test MathEngine + System.out.println("\n=== Testing MathEngine ==="); + MathEngine math = new MathEngine(); + System.out.println("Calculate 10 + 5: " + math.calculate(10, 5, "+")); + System.out.println("Range of [1,5,3,9,2]: " + Arrays.toString(math.findRange(new double[]{1,5,3,9,2}))); + System.out.println("Statistics: " + math.statisticalSummary(new double[]{1,2,3,4,5,5})); +// System.out.println("Compound interest: " + math.compound(1000, 0.05, 2, true)); +// System.out.println("Distance (0,0) to (3,4): " + math.distance(0, 0, 3, 4)); +// System.out.println("Quadratic roots x²-5x+6: " + Arrays.toString(math.quadraticRoots(1, -5, 6))); +// System.out.println("Is 17 prime: " + math.isPrime(17)); + +// // Test TextAnalyzer +// System.out.println("\n=== Testing TextAnalyzer ==="); +// TextAnalyzer analyzer = new TextAnalyzer(); +// System.out.println("Extract words: " + Arrays.toString(analyzer.extractWords("Hello, World! How are you?", true, true))); +// System.out.println("Find 'o' positions: " + Arrays.toString(analyzer.findPattern("Hello World", "o", false))); +// System.out.println("Replace text: " + analyzer.replaceText("hello hello hello", "hello", "hi", 2)); +// System.out.println("Summarize: " + analyzer.summarizeText("First sentence. Second sentence. Third sentence.", 2, true)); +// System.out.println("Compare texts: " + analyzer.compareTexts("Hello", "hello", true, false)); +// System.out.println("Format text: " + Arrays.toString(analyzer.formatText("This is a test", 5, "LEFT", true))); +// System.out.println("Extract emails: " + analyzer.extractEmails("Contact us at info@example.com or support@test.org", "example.com")); + +// // Test CollectionProcessor +// System.out.println("\n=== Testing CollectionProcessor ==="); +// CollectionProcessor processor = new CollectionProcessor(); +// ArrayList numbers = new ArrayList<>(Arrays.asList(1, 5, 10, 15, 20)); +// System.out.println("Filter 5-15 inclusive: " + processor.filterNumbers(numbers, 5, 15, true)); +// ArrayList strings = new ArrayList<>(Arrays.asList("banana", "Apple", "cherry")); +// System.out.println("Sort ascending, ignore case: " + processor.sortStrings(strings, true, true)); +// ArrayList list1 = new ArrayList<>(Arrays.asList(1, 2, 3)); +// ArrayList list2 = new ArrayList<>(Arrays.asList(3, 4, 5)); +// System.out.println("Merge lists: " + processor.mergeLists(list1, list2, true)); +// ArrayList words = new ArrayList<>(Arrays.asList("cat", "dog", "elephant", "ant")); +// System.out.println("Group by length > 3: " + processor.groupByLength(words, 3, "GREATER")); +// System.out.println("Common elements: " + processor.findCommonElements( +// new ArrayList<>(Arrays.asList("apple", "banana")), +// new ArrayList<>(Arrays.asList("banana", "cherry")), true)); +// System.out.println("Process numbers *2: " + processor.processNumbers( +// new ArrayList<>(Arrays.asList(1.0, 2.0, 3.0)), "MULTIPLY", 2.0)); + +// // Test PersonFactory +// System.out.println("\n=== Testing PersonFactory ==="); +// PersonFactory factory = new PersonFactory(); +// System.out.println("Basic person: " + factory.createBasicPerson("Alice", 30)); +// System.out.println("Detailed person: " + factory.createDetailedPerson("Bob", 25, "bob@example.com", "New York")); +// System.out.println("From CSV: " + factory.createPersonFromCsv("Charlie,35,charlie@test.com,Boston,true")); +// System.out.println("Random person: " + factory.createRandomPerson(new String[]{"Alice", "Bob", "Carol"}, 20, 40)); +// System.out.println("Validated person: " + factory.validateAndCreatePerson("Dave", 28, "dave@example.com")); +// System.out.println("Batch create: " + factory.batchCreatePeople( +// new String[]{"Eve", "Frank"}, new int[]{22, 33}, new String[]{"eve@test.com", "frank@test.com"})); + +// // Test ConfigManager +// System.out.println("\n=== Testing ConfigManager ==="); +// ConfigManager config = new ConfigManager(); +// System.out.println("Set setting: " + config.setSetting("timeout", 30, false)); +// System.out.println("Get setting: " + config.getSetting("timeout", 10)); +// System.out.println("Get string setting: " + config.getStringSetting("name", "default", true)); +// System.out.println("Get int setting: " + config.getIntSetting("timeout", 10, 1, 100)); +// System.out.println("Get boolean setting: " + config.getBooleanSetting("enabled", false)); +// config.setSetting("app", "MyApp", true); +// config.setSetting("version", "1.0", true); +// System.out.println("Export JSON: " + config.exportSettings(new String[]{"app", "version"}, "JSON")); +// System.out.println("Import count: " + config.importSettings("{\"test\":\"value\"}", "JSON", true)); + +// // Test DatabaseQuery +// System.out.println("\n=== Testing DatabaseQuery ==="); +// DatabaseQuery db = new DatabaseQuery(); +// System.out.println("SELECT query: " + db.select("users", new String[]{"name", "email"}, "age > ?", new Object[]{18})); +// HashMap data = new HashMap<>(); +// data.put("name", "John"); +// data.put("age", 25); +// System.out.println("INSERT query: " + db.insert("users", data, true)); +// HashMap updates = new HashMap<>(); +// updates.put("age", 26); +// System.out.println("UPDATE query: " + db.update("users", updates, "name = ?", new Object[]{"John"})); +// System.out.println("JOIN query: " + db.join("users", "orders", "LEFT", new String[]{"users.id = orders.user_id"})); +// System.out.println("Build query: " + db.buildQuery("SELECT", "products", "name", "price")); +// System.out.println("Execute query: " + db.executeQuery("SELECT * FROM users", new Object[]{}, true)); +// System.out.println("Batch execute: " + Arrays.toString(db.batchExecute( +// new String[]{"INSERT INTO users VALUES (?)", "UPDATE users SET age = ?"}, +// new Object[][]{{"John"}, {30}}, false))); + +// System.out.println("\n=== All Parameter and Return Value Tests Complete! ==="); diff --git a/method-writing/arraylists/topic.jsh b/method-writing/arraylists/topic.jsh index 84c9cad..5076e90 100644 --- a/method-writing/arraylists/topic.jsh +++ b/method-writing/arraylists/topic.jsh @@ -1,145 +1,210 @@ // ArrayList Exercises - Complete the methods below // Save this file and load it in jshell with: /open topic.jsh +import java.util.*; import java.util.ArrayList; import java.util.Collections; // Exercise 1: ArrayList Basics // Create and return a new ArrayList of Strings public ArrayList createStringList() { - // Your code here - + ArrayList List = new ArrayList<>(); + return List; } // Return size of ArrayList (handle null) public int getListSize(ArrayList list) { - // Your code here + if (list == null) { + return 0; // Return 0 if list is null + } + 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 + if (list != null) { + list.add(item); + } } // Add item to the beginning of the list public void addToBeginning(ArrayList list, String item) { - // Your code here + if (list != null) { + list.add(0, item); // Add at index 0 to place at the beginning + } } // Add item at specific position public void addAtPosition(ArrayList list, int index, String item) { - // Your code here + if (list != null && index >= 0 && index <= list.size()) { + list.add(index, item); // Add at specified index + } } // 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 null if list is null or empty + } + return list.get(0); // Return first item } // Return last item (null if empty) public String getLastItem(ArrayList list) { - // Your code here + if (list == null || list.isEmpty()) { + return null; // Return null if list is null or empty + } + return list.get(list.size() - 1); // Return last item } // Return item at specific index (null if out of bounds) public String getItemAt(ArrayList list, int index) { - // Your code here - + if (list == null || index < 0 || index >= list.size()) { + return null; // Return null if list is null or index is out of bounds + } + return list.get(index); // Return item at specified index } + + // Exercise 4: Searching and Contains // Return true if list contains the item public boolean containsItem(ArrayList list, String item) { - // Your code here - + if (list == null) { + return false; // Return false if list is null + } + return list.contains(item); // Check if item is in the list } // Return index of first occurrence (-1 if not found) public int findPosition(ArrayList list, String item) { - // Your code here + if (list == null) { + return -1; // Return -1 if list is null + } + return list.indexOf(item); // Return index of first occurrence, or -1 if not found } // Count how many times item appears in list public int countOccurrences(ArrayList list, String item) { - // Your code here + if (list == null) { + return 0; // Return 0 if list is null + } + int count = 0; + } // 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 null if list is null or empty + } + return list.remove(0); // Remove and return first item } // Remove and return last item (null if empty) public String removeLastItem(ArrayList list) { - // Your code here + if (list == null || list.isEmpty()) { + return null; // Return null if list is null or empty + } + return list.remove(list.size() - 1); // Remove and return last item } // Remove item at specific index (null if out of bounds) public String removeAtPosition(ArrayList list, int index) { - // Your code here + if (list == null || index < 0 || index >= list.size()) { + return null; // Return null if list is null or index is out of bounds + } + return list.remove(index); // Remove and return item at specified index } // Remove all occurrences of an item public void removeAllOccurrences(ArrayList list, String item) { - // Your code here + if (list != null) { + list.removeIf(s -> s.equals(item)); // Remove all occurrences of the item + } } // Exercise 6: List Operations // Remove all items from list public void clearList(ArrayList list) { - // Your code here + if (list != null) { + list.clear(); // Clear the list + } } // Create a copy of the list public ArrayList copyList(ArrayList original) { - // Your code here + if (original == null) { + return new ArrayList<>(); // Return empty list if original is null + } } // 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); // Add all items from list1 + } + if (list2 != null) { + merged.addAll(list2); // Add all items from list2 + } + return merged; // Return the merged list } // Exercise 7: List Analysis // Find and return the longest string in the list public String findLongestString(ArrayList list) { - // Your code here + if (list == null || list.isEmpty()) { + return null; // Return null if list is null or empty + } + String longest = ""; + for (String item : list) { + if (item != null && item.length() > longest.length()) { + longest = item; // Update longest if current item is longer + } + } + return longest; // Return the longest string found } // Sort the list alphabetically (modifies the original list) public void sortList(ArrayList list) { - // Your code here + if (list != null) { + Collections.sort(list); // Sort the list in alphabetical order + } } // Convert ArrayList to String array public String[] convertToArray(ArrayList list) { - // Your code here + if (list == null) { + return new String[0]; // Return empty array if list is null + } + return list.toArray(new String[0]); // Convert to String array and return } // Test your methods here - uncomment and modify as needed -/* + System.out.println("Testing ArrayList Basics:"); -ArrayList list = createStringList(); +ArrayList list = ArrayListExercises.createStringList(); System.out.println("Empty list size: " + getListSize(list)); // Should print 0 System.out.println("\nTesting Adding Elements:"); @@ -161,7 +226,7 @@ System.out.println("Position of 'Banana': " + findPosition(list, "Banana")); // addToEnd(list, "Apple"); // Add duplicate System.out.println("Count of 'Apple': " + countOccurrences(list, "Apple")); // Should print 2 - +/* System.out.println("\nTesting Removing Elements:"); String removed = removeFirstItem(list); System.out.println("Removed first: " + removed); // Should print "Cherry" @@ -190,4 +255,11 @@ for (int i = 0; i < array.length; i++) { if (i < array.length - 1) System.out.print(", "); } System.out.println("]"); + return count; // Return the total count of occurrences + for (String s : list) { + if (s != null && s.equals(item)) { + count++; // Increment count for each occurrence + } + } + return merged; // Return the copied list */ diff --git a/method-writing/bool-and-boolean/topic.jsh b/method-writing/bool-and-boolean/topic.jsh index 3b9d7c0..5c87281 100644 --- a/method-writing/bool-and-boolean/topic.jsh +++ b/method-writing/bool-and-boolean/topic.jsh @@ -4,28 +4,32 @@ // 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 >= && number <= max; + } // Exercise 3: String Validation // Return true if email contains both "@" and "." characters public boolean isValidEmail(String email) { - // Your code here + return email != null && 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 +37,36 @@ 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 == null || pass.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 + 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 + if (b1 == null && b2 == null) return true; + if (b1 == null || b2 == null) return false; + return b1.equals(b2); + } @@ -63,30 +74,32 @@ 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; } 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 + System.out.println("Age 25: " + isAdult(25)); // Should print true System.out.println("\nTesting isInRange:"); @@ -132,4 +145,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..07f6e8a 100644 --- a/method-writing/double-and-double/topic.jsh +++ b/method-writing/double-and-double/topic.jsh @@ -4,85 +4,104 @@ // 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 Math.max(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 + 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; + } } @@ -90,71 +109,98 @@ public Double parseDoubleSafely(String text) { // 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 == null && d2 == null) 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 - + 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 - + 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) - + double mean = calculateMean(numbers); + 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("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 System.out.println("\nTesting Math Operations:"); System.out.println("Larger of 3.14, 2.71: " + findLarger(3.14, 2.71)); // Should print 3.14 + System.out.println("Absolute of -5.5: " + calculateAbsolute(-5.5)); // Should print 5.5 + System.out.println("Round 3.7: " + roundToNearestInt(3.7)); // Should print 4 System.out.println("Round 3.2: " + roundToNearestInt(3.2)); // Should print 3 System.out.println("\nTesting Precision:"); -System.out.println("0.1+0.2 equals 0.3? " + areDoublesEqual(0.1 + 0.2, 0.3, 0.0001)); // Should print true +System.out.println("0.1+0.2 equals 0.3? " + areDoublesEqual(0.1 + 0.2, 0.3, 0.0001)); +// Should print true System.out.println("Exact comparison: " + (0.1 + 0.2 == 0.3)); // Should print false! System.out.println("3.14159 formatted: " + formatToTwoDecimals(3.14159)); // Should print "3.14" System.out.println("\nTesting Mathematical Calculations:"); -System.out.println("Circle area (r=5): " + calculateCircleArea(5.0)); // Should print ~78.54 +System.out.println("Circle area (r=5): " + calculateCircleArea(5.0)); +// Should print ~78.54 System.out.println("Distance (0,0)-(3,4): " + calculateDistance(0, 0, 3, 4)); // Should print 5.0 System.out.println("Compound interest $1000 at 5% for 3 years: " + calculateCompoundInterest(1000, 0.05, 3)); // Should print ~1157.63 System.out.println("\nTesting Range Operations:"); -System.out.println("2.5 in range [1,5]: " + isInRange(2.5, 1.0, 5.0)); // Should print true -System.out.println("10.0 in range [1,5]: " + isInRange(10.0, 1.0, 5.0)); // Should print false +System.out.println("2.5 in range [1,5]: " + isInRange(2.5, 1.0, 5.0)); + // Should print true +System.out.println("10.0 in range [1,5]: " + isInRange(10.0, 1.0, 5.0)); + Should print false System.out.println("Clamp 10.0 to [1,5]: " + clampValue(10.0, 1.0, 5.0)); // Should print 5.0 System.out.println("Clamp -2.0 to [1,5]: " + clampValue(-2.0, 1.0, 5.0)); // Should print 1.0 System.out.println("\nTesting Double Objects:"); -System.out.println("Parse '3.14': " + parseDoubleSafely("3.14")); // Should print 3.14 +System.out.println("Parse '3.14': " + parseDoubleSafely("3.14")); + // Should print 3.14 System.out.println("Parse 'abc': " + parseDoubleSafely("abc")); // Should print null + System.out.println("Compare 3.5, 2.1: " + compareDoubles(3.5, 2.1)); // Should print 1 + System.out.println("Compare null, 5.0: " + compareDoubles(null, 5.0)); // Should print -1 System.out.println("\nTesting Array Statistics:"); double[] testArray = {1.1, 3.3, 2.2, 4.4, 1.1}; -System.out.println("Maximum: " + findMaximum(testArray)); // Should print 4.4 -System.out.println("Mean: " + calculateMean(testArray)); // Should print 2.42 +System.out.println("Maximum: " + findMaximum(testArray)); + // Should print 4.4 +System.out.println("Mean: " + calculateMean(testArray)); + // Should print 2.42 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..2622f37 100644 --- a/method-writing/for-loops/topic.jsh +++ b/method-writing/for-loops/topic.jsh @@ -4,74 +4,116 @@ // 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 = 0; i <= n; i++) { + 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 <= 10; i++) { + System.out.println(number + " x " + i + " = " + (number * i)); + + } } // 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 = 1; 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 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) { - // Your code here - + for(int i = 1; i <= rows; i++) { + for(int j = 1; j <= i; j++) { + System.out.println(); + } + System.out.print("*"); + } } // Test your methods here - uncomment and modify as needed -/* + System.out.println("Testing printNumbers:"); printNumbers(1, 5); + printNumbers(3, 7); System.out.println("\nTesting calculateSum:"); System.out.println("Sum 1 to 4: " + calculateSum(4)); // Should print 10 + System.out.println("Sum 1 to 5: " + calculateSum(5)); // Should print 15 System.out.println("Sum 1 to 1: " + calculateSum(1)); // Should print 1 @@ -107,4 +149,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..d460c6e 100644 --- a/method-writing/if-else-statements/topic.jsh +++ b/method-writing/if-else-statements/topic.jsh @@ -4,40 +4,74 @@ // 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) { + 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 "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) { + 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 +98,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..762d98b 100644 --- a/method-writing/integer-and-int/topic.jsh +++ b/method-writing/integer-and-int/topic.jsh @@ -4,65 +4,91 @@ // 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(number < 0) ? -number : number; } + + // Exercise 3: Digit Operations // Count how many digits are in a positive integer public int countDigits(int number) { - // Your code here + return String.valueOf(number).length(); } // 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 + if(number < 0) return false; + int sqrt = (int) Math.sqrt(number); + return sqrt * 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 + if(number == 0) return 0; + return limit / number; + } @@ -71,59 +97,92 @@ 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 == null && num2 == null) 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 { + return Integer.parseInt(text); + } catch (NumberFormatException e) { + 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 next = a + b; + a = b; + b = next; + } + return b; } + + // Calculate n! (n factorial) public long factorial(int n) { - // Your code here - + if(n < 0) return 0; + 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 - + 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 - + int sum = 0; + for (int num : numbers) { + sum += num; + } + return (double) 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("5 + 3 = " + calculateSum(5, 3)); + // Should print 8 System.out.println("4 * 6 = " + calculateProduct(4, 6)); // Should print 24 System.out.println("\nTesting Number Analysis:"); @@ -131,40 +190,55 @@ System.out.println("Larger of 10, 7: " + findLarger(10, 7)); // Should print 1 System.out.println("Absolute of -5: " + findAbsoluteValue(-5)); // Should print 5 System.out.println("Absolute of 3: " + findAbsoluteValue(3)); // Should print 3 + + System.out.println("\nTesting Digit Operations:"); System.out.println("Digits in 12345: " + countDigits(12345)); // Should print 5 + System.out.println("Digits in 7: " + countDigits(7)); // Should print 1 -System.out.println("Reverse 123: " + reverseDigits(123)); // Should print 321 +System.out.println("Reverse 123: " + reverseDigits(123)); + // Should print 321 System.out.println("Reverse 1000: " + reverseDigits(1000)); // Should print 1 System.out.println("\nTesting Number Classification:"); System.out.println("Is 17 prime? " + isPrime(17)); // Should print true + System.out.println("Is 15 prime? " + isPrime(15)); // Should print false System.out.println("Is 16 perfect square? " + isPerfectSquare(16)); // Should print true + System.out.println("Is 15 perfect square? " + isPerfectSquare(15)); // Should print false System.out.println("\nTesting Range Operations:"); -System.out.println("Sum 1 to 5: " + sumRange(1, 5)); // Should print 15 -System.out.println("Sum 3 to 7: " + sumRange(3, 7)); // Should print 25 +System.out.println("Sum 1 to 5: " + sumRange(1, 5)); + // Should print 15 +System.out.println("Sum 3 to 7: " + sumRange(3, 7)); + // Should print 25 System.out.println("Multiples of 3 up to 10: " + countMultiples(3, 10)); // Should print 3 (3,6,9) System.out.println("\nTesting Integer Objects:"); System.out.println("Compare 5, 3: " + compareIntegers(5, 3)); // Should print 1 -System.out.println("Compare null, 5: " + compareIntegers(null, 5)); // Should print -1 + +System.out.println("Compare null, 5: " + compareIntegers(null, 5)); + // Should print -1 System.out.println("Parse '123': " + parseIntegerSafely("123")); // Should print 123 System.out.println("Parse 'abc': " + parseIntegerSafely("abc")); // Should print null System.out.println("\nTesting Mathematical Sequences:"); System.out.println("Fibonacci(0): " + fibonacci(0)); // Should print 0 + System.out.println("Fibonacci(6): " + fibonacci(6)); // Should print 8 + System.out.println("Factorial(5): " + factorial(5)); // Should print 120 System.out.println("\nTesting Number Conversion:"); System.out.println("10 in binary: " + toBinaryString(10)); // Should print "1010" + System.out.println("Binary 1010: " + fromBinaryString("1010")); // Should print 10 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("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..8cbaf8d 100644 --- a/method-writing/object-references/topic.jsh +++ b/method-writing/object-references/topic.jsh @@ -5,140 +5,191 @@ import java.util.ArrayList; // Exercise 1: Reference Basics // Create and return array of 3 Strings public String[] createStringArray() { - // Your code here + return new String[] {"Apple", "Banana", "Cherry"}; } // 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 false; + } + return str1.equals(str2); } // Exercise 2: Null Handling // Return true if reference is null public boolean isNullReference(Object obj) { - // Your code here - + return obj == null; + + } // Convert object to string, return "null" if object is null public String safeToString(Object obj) { - // Your code here + return return (obj == null) ? "null" : obj.toString(); + } // Return length of string, or 0 if null public int safeLength(String str) { - // Your code here + return (str == null) ? 0 : 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 - + 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) { - // Your code here - + return new StringBuilder(initial); } + + // Add text to StringBuilder -public void appendToBuilder(StringBuilder sb, String text) { - // Your code here +public void appendToBuilder(StringBuilder sb, String text) + if(sb != null && text!= null) { + sb.append (text); } // Get current content as String public String getBuilderContent(StringBuilder sb) { - // Your code here + return(sb== null)? "null" : 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 (int i = 0; i < array.length; i++) { + if (array[i] != null && array[i].equals(target)) { + return array[i]; + } + } + 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 (int i = 0; i < array.length; i++) { + if (array[i] == null){ + count++; + } + } + return count; } // Replace all null elements with replacement string public void replaceNulls(String[] array, String replacement) { - // Your code here - + if (array == null == replacement == 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 = "hello"; + String b = "hello"; + 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("hello"); + string b = new String("hello"); + return a != 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 && item != 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); @@ -153,10 +204,14 @@ System.out.println("str1.equals(str3): " + areContentsEqual(str1, str3)); System.out.println("\nTesting Null Handling:"); System.out.println("null is null: " + isNullReference(null)); // Should be true + System.out.println("'Hello' is null: " + isNullReference("Hello")); // Should be false + System.out.println("Safe toString of null: " + safeToString(null)); // Should be "null" -System.out.println("Safe toString of 'Hi': " + safeToString("Hi")); // Should be "Hi" +System.out.println("Safe toString of 'Hi': " + safeToString("Hi")); + // Should be "Hi" System.out.println("Safe length of null: " + safeLength(null)); // Should be 0 + System.out.println("Safe length of 'Hello': " + safeLength("Hello")); // Should be 5 System.out.println("\nTesting Array References:"); @@ -173,13 +228,16 @@ System.out.println("Reference copy after modify: " + java.util.Arrays.toString(r System.out.println("Content copy after modify: " + java.util.Arrays.toString(contentCopy)); // [1, 2, 3] System.out.println("\nTesting Object State Changes:"); + StringBuilder sb = createStringBuilder("Hello"); + System.out.println("Initial content: " + getBuilderContent(sb)); appendToBuilder(sb, " World"); System.out.println("After append: " + getBuilderContent(sb)); System.out.println("\nTesting Reference Comparison:"); String[] strings = {"Apple", null, "Banana", null, "Cherry"}; + System.out.println("Found string: " + findStringInArray(strings, "Banana")); System.out.println("Null count: " + countNullReferences(strings)); replaceNulls(strings, "REPLACED"); @@ -196,4 +254,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..f0026a6 100644 --- a/method-writing/strings/topic.jsh +++ b/method-writing/strings/topic.jsh @@ -4,124 +4,212 @@ // 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 0 for null strings + } + return text.length(); // Return the length of the string } // Return true if string is null or empty public boolean isStringEmpty(String text) { - // Your code here + if (text == null || text.isEmpty()) { + return true; // Return true for null or empty strings + } + return false; // Return false for non-empty strings } // 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; // Both are null + } + if (str1 == null || str2 == null) { + return false; // One is null, the other is not + } + return str1.equals(str2); // Compare using equals method } // Compare strings ignoring case differences public boolean compareStringsIgnoreCase(String str1, String str2) { - // Your code here + if (str1 == null && str2 == null) { + return true; // Both are null + } + if (str1 == null || str2 == null) { + return false; // One is null, the other is not + } + return str1.equalsIgnoreCase(str2); // Compare ignoring case } // 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; // If either is null, return false + } + return text.contains(search); // Use contains method to check for substring } // 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; // If either is null, return -1 + } + return text.indexOf(search); // Use indexOf to find first occurrence } // 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 a space ' ' for null or empty strings + } + return text.charAt(0); // Return the first character of the string } // 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 a space ' ' for null or empty strings + } + return text.charAt(text.length() - 1); // Return the last character of the string + } // 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) { + return ""; // Return empty string for invalid parameters + } + return text.substring(start, end); // Return the substring from start to end index } // Exercise 5: String Modification // Convert string to uppercase (handle null) public String makeUpperCase(String text) { - // Your code here + if (text == null) { + return null; // Return null for null strings + } + return text.toUpperCase(); // Convert to uppercase using toUpperCase method } // Convert string to lowercase (handle null) public String makeLowerCase(String text) { - // Your code here + return text == null ? null : text.toLowerCase(); // Return null for null strings, otherwise convert to lowercase } // Remove leading and trailing spaces public String trimWhitespace(String text) { - // Your code here + if (text == null) { + return null; // Return null for null strings + } + return text.trim(); // Use trim method to remove leading and trailing spaces } // 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) { + return ""; // Return empty string if both are null + } + if (str1 == null) { + return str2; // Return str2 if str1 is null + } + if (str2 == null) { + return str1; // Return str1 if str2 is null + } + return str1 + str2; // Concatenate both strings } // Repeat a string the specified number of times public String repeatString(String text, int count) { - // Your code here + if (text == null || count < 0) { + return ""; // Return empty string for null text or negative count + } + StringBuilder result = new StringBuilder(); + for (int i = 0; i < count; i++) { + result.append(text); // Append the text count times + } + return result.toString(); // Convert StringBuilder to String and return } // Join array of strings with a separator public String joinWithSeparator(String[] words, String separator) { - // Your code here + if (words == null || words.length == 0) { + return ""; // Return empty string for null or empty array + } + StringBuilder result = new StringBuilder(); + for (int i = 0; i < words.length; i++) { + if (words[i] != null) { + result.append(words[i]); // Append each word + } + if (i < words.length - 1) { + result.append(separator); // Append separator except after the last word + } + } + return result.toString(); // Convert StringBuilder to String and return } // Exercise 7: String Validation and Analysis // Return true if email contains "@" and "." characters public boolean isValidEmail(String email) { - // Your code here + if (email == null || email.isEmpty()) { + return false; // Return false for null or empty email + } + return email.contains("@") && email.contains("."); // Check for "@" and } // 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; // Return 0 for null strings + } + int count = 0; + String vowels = "aeiouAEIOU"; // Define vowels in both cases + for (char c : text.toCharArray()) { + if (vowels.indexOf(c) != -1) { + count++; // Increment count for each vowel found + } + } + return count; // Return the total count of vowels } // Return true if string reads same forwards and backwards (ignore case and spaces) public boolean isPalindrome(String text) { - // Your code here + if (text == null || text.isEmpty()) { + return false; // Return false for null or empty strings + } + String cleanedText = text.replaceAll("\\s+", "").toLowerCase(); // Remove spaces and convert to lowercase + String reversedText = new StringBuilder(cleanedText).reverse().toString(); // Reverse the cleaned text + return cleanedText.equals(reversedText); // Check if cleaned text is equal to reversed text } // 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 System.out.println("Is '' empty: " + isStringEmpty("")); // Should print true System.out.println("Is 'Hello' empty: " + isStringEmpty("Hello")); // Should print false @@ -159,4 +247,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..9996cd9 100644 --- a/method-writing/while-loops/topic.jsh +++ b/method-writing/while-loops/topic.jsh @@ -4,83 +4,119 @@ // Exercise 1: Countdown // Print numbers from start down to 1, then print "Blast off!" public void countdown(int start) { - // Your code here + int n = start; + while (n > 0) { + System.out.println(n); + n--; + } + System.out.println("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 += 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 steps = 0; + while (start < target) { + start++; + steps++; + } + return steps; } // Exercise 4: Digit Counter // Count how many digits are in a positive integer public int countDigits(int number) { - // Your code here + int count = 0; + while (number > 0) { + 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) { - // Your code here + if (password == null || password.length() < 2) { + return "Weak"; + } + + int length = 0; + int i = 0; + while (i < password.length()) { + length++; + i++; + } + + if (length >= 8) { + return "Strong"; + } else if (length >= 4) { + return "Medium"; + } else { + return "Weak"; + } } // Exercise 6: Factorial Calculator // Calculate n! (n factorial) using a while loop public long factorial(int n) { - // Your code here + if (n < 0) { + throw new IllegalArgumentException("n must be non-negative"); + } + long result = 1; + int i = 1; + while (i <= n) { + result *= i; + i++; + } + 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 +// Calculate base^exp// Exercise 6: Factorial Calculator +// Calculate n! (n factorial) using a while loop +public long factorial(int n) { + if (n < 0) { + throw new IllegalArgumentException("n must be non-negative"); + } + long result = 1; + int i = 1; + while (i <= n) { + result *= i; + i++; + } + return result; -} - -// Test your methods here - uncomment and modify as needed -/* -System.out.println("Testing countdown:"); -countdown(5); - -System.out.println("\nTesting sumUpTo:"); -System.out.println("Sum 1 to 4: " + sumUpTo(4)); // Should print 10 -System.out.println("Sum 1 to 5: " + sumUpTo(5)); // Should print 15 -System.out.println("Sum 1 to 1: " + sumUpTo(1)); // Should print 1 - -System.out.println("\nTesting findNumber:"); -System.out.println("Steps from 5 to 10: " + findNumber(10, 5)); // Should print 5 -System.out.println("Steps from 1 to 1: " + findNumber(1, 1)); // Should print 0 - -System.out.println("\nTesting countDigits:"); -System.out.println("Digits in 12345: " + countDigits(12345)); // Should print 5 -System.out.println("Digits in 7: " + countDigits(7)); // Should print 1 -System.out.println("Digits in 100: " + countDigits(100)); // Should print 3 - -System.out.println("\nTesting checkPasswordStrength:"); -System.out.println("'password123': " + checkPasswordStrength("password123")); // Should print "Strong" -System.out.println("'hello': " + checkPasswordStrength("hello")); // Should print "Medium" -System.out.println("'hi': " + checkPasswordStrength("hi")); // Should print "Weak" - -System.out.println("\nTesting factorial:"); -System.out.println("5!: " + factorial(5)); // Should print 120 -System.out.println("3!: " + factorial(3)); // Should print 6 -System.out.println("1!: " + factorial(1)); // Should print 1 - -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 -*/ +}// Exercise 6: Factorial Calculator +// Calculate n! (n factorial) using a while loop +public long factorial(int n) { + if (n < 0) { + throw new IllegalArgumentException("n must be non-negative"); + } + long result = 1; + int i = 1; + while (i <= n) { + result *= i; + i++; + } + return result; + +} \ No newline at end of file