diff --git a/Learn-Java-with-Projects.iml b/Learn-Java-with-Projects.iml index b107a2d..674648e 100644 --- a/Learn-Java-with-Projects.iml +++ b/Learn-Java-with-Projects.iml @@ -1,6 +1,6 @@ - + diff --git a/ch14/MethodReferenceTypes.java b/ch14/MethodReferenceTypes.java index ab6bbf1..4b78e9c 100644 --- a/ch14/MethodReferenceTypes.java +++ b/ch14/MethodReferenceTypes.java @@ -1,4 +1,4 @@ -package lets_get_certified.lambdas; +package ch14; import java.util.ArrayList; import java.util.Arrays; @@ -11,139 +11,70 @@ import java.util.function.Supplier; public class MethodReferenceTypes { - public static void main(String[] args) { -// boundMethodReferences(); // bound -// unboundMethodReferences(); // unbound + public static void main(String[] args) { + boundMethodReferences(); // bound + unboundMethodReferences(); // unbound constructorMethodReferences(); // constructor -// staticMethodReferences(); // static + staticMethodReferences(); // static } + public static void boundMethodReferences(){ String name = "Mr. Joe Bloggs"; - // Supplier - // T get() - Supplier lowerL = () -> name.toLowerCase(); // lambda - Supplier lowerMR = name::toLowerCase; // method reference - - // No need to say which instance to call it on - the supplier is bound to name - System.out.println(lowerL.get()); // mr. joe bloggs - System.out.println(lowerMR.get());// mr. joe bloggs - + + // Supplier + // T get() + Supplier lowerMR = name::toLowerCase; // method reference + System.out.println(lowerMR.get()); // mr. Joe Bloggs + // Predicate - // boolean test(T t) - // Even though startsWith is overloaded, boolean startsWith(String) and - // boolean startsWith(String, int), because we are creating a Predicate which - // has a functional method of test(T t), the startsWith(String) is used. - // This is where "context" is important. - Predicate titleL = (title) -> name.startsWith(title); + // boolean test(T t) Predicate titleMR = name::startsWith; - - System.out.println(titleL.test("Mr.")); // true - System.out.println(titleMR.test("Ms."));// false + System.out.println(titleMR.test("Mr.")); // true + System.out.println(titleMR.test("Ms.")); // false } public static void unboundMethodReferences(){ - // Function - // R apply(T) - // String apply(String) - Function upperL = s -> s.toUpperCase(); - Function upperMR = String::toUpperCase; - // The function is unbound, so you need to specify which instance to call it on - System.out.println(upperL.apply("sean")); // SEAN - System.out.println(upperMR.apply("sean")); // SEAN - - // Function - // R apply(T t, U u) - // String apply(String, String) - BiFunction concatL = (s1, s2) -> s1.concat(s2); - BiFunction concatMR = String::concat; - System.out.println(concatL.apply("Sean ", "Kennedy"));// Sean Kennedy - - // 1st parameter is used for executing the instance method - // "Sean ".concat("Kennedy") - System.out.println(concatMR.apply("Sean ", "Kennedy"));// Sean Kennedy + // Function + // R apply(T t) + Function upperMR = String::toUpperCase; + System.out.println(upperMR.apply("sean")); // SEAN + + // BiFunction + // R apply(T t, U u) + BiFunction concatMR = String::concat; + System.out.println(concatMR.apply("Sean ", "Kennedy")); // Sean Kennedy } - - - - - - - + public static void constructorMethodReferences(){ - // Supplier - // T get() - Supplier sbL = () -> new StringBuilder(); // lambda - Supplier sbMR = StringBuilder::new; // method reference - StringBuilder sb1 = sbL.get(); sb1.append("lambda version"); System.out.println(sb1); - StringBuilder sb2 = sbMR.get(); sb2.append("method reference version"); System.out.println(sb2); - - // Function - // R apply(T) - // List apply(Integer) - // ArrayList(int initialCapacity) - Function> alL = x -> new ArrayList(x); - Function> alMR = ArrayList::new; - List ls1 = alL.apply(100); // initial capacity 100 - ls1.add("21"); - System.out.println(ls1);//[21] - List ls2 = alMR.apply(200); // initial capacity 200 - ls2.add("88"); - System.out.println(ls2);//[88] + // Supplier + // T get() + Supplier sbMR = StringBuilder::new; // method reference + StringBuilder sb = sbMR.get(); + sb.append("method reference version"); + System.out.println(sb); + + // Function + // R apply(T t) + Function> alMR = ArrayList::new; + List ls = alMR.apply(200); // initial capacity 200 + ls.add("88"); + System.out.println(ls); // [88] } - - - - - - - - - - + public static void staticMethodReferences(){ - // Static method references are considered UNBOUND also. An example static method - // is Collections.sort(List) - // Consumer - // void accept(T t) - // void accept(List) - // NB: Consumer takes one parameter => sort(List) is used, as opposed to sort(List, Comparator) - Consumer> sortL = list -> Collections.sort(list); + // Consumer + // void accept(T t) Consumer> sortMR = Collections::sort; - List listOfNumbers = Arrays.asList(2,1,5,4,9); - sortL.accept(listOfNumbers);// execution - System.out.println(listOfNumbers); // [1, 2, 4, 5, 9] - - listOfNumbers = Arrays.asList(8,12,4,3,7); - sortMR.accept(listOfNumbers);// execution - System.out.println(listOfNumbers); // [3, 4, 7, 8, 12] + List listOfNumbers = Arrays.asList(8, 12, 4, 3, 7); + sortMR.accept(listOfNumbers); // execution + System.out.println(listOfNumbers); // [3, 4, 7, 8, 12] } - - } - - - - - - - - - - - -class X implements Consumer{ - - @Override - public void accept(Object arg0) { - System.out.println("----"+arg0); - } - -} /* X x = new X(); x.accept("abc"); diff --git a/ch16/Optionals.java b/ch16/Optionals.java index ec53c1b..70890b4 100644 --- a/ch16/Optionals.java +++ b/ch16/Optionals.java @@ -1,117 +1,80 @@ package ch16; +import java.util.NoSuchElementException; import java.util.Optional; import java.util.OptionalDouble; import java.util.OptionalInt; import java.util.stream.IntStream; public class Optionals { - + public static void main(String[] args) { -// doOptionalPrimitiveAverage(); + doOptionalPrimitiveAverage(); doOptionalAPI(); -// createOptionals(); -// doOptionalNull(); + createOptionals(); + doOptionalNull(); } - public static void createOptionals(){ - Optional opt1 = Optional.empty(); -// System.out.println(opt1.get()); // NoSuchElementException - opt1.ifPresent(o -> System.out.println("opt1: "+o)); // no exception - Optional opt2 = Optional.of(23); -// Optional.of(null); // NullPointerException - opt2.ifPresent(o -> System.out.println("opt2: "+o)); // opt2: 23 + public static void createOptionals() { + Optional opt1 = Optional.empty(); + opt1.ifPresent(System.out::println); + + Optional opt2 = Optional.of(23); + opt2.ifPresent(System.out::println); - Optional opt3 = Optional.ofNullable(23); - opt3.ifPresent(o -> System.out.println("opt3: "+o)); // opt3: 23 + Optional opt3 = Optional.of(23); + opt3.ifPresent(System.out::println); - Optional opt4 = Optional.ofNullable(null); - opt4.ifPresent(o -> System.out.println("opt4: "+o)); - if(opt4.isEmpty()){ - System.out.println("opt4 is empty!"); // opt4 is empty! + Optional opt4 = Optional.empty(); + opt4.ifPresent(System.out::println); + if (opt4.isEmpty()) { + System.out.println("opt4 is empty!"); // opt4 is empty! } } - - public static void doOptionalPrimitiveAverage(){ + + public static void doOptionalPrimitiveAverage() { OptionalDouble optAvg = IntStream.rangeClosed(1, 10).average(); - optAvg.ifPresent(d -> System.out.println(d));// 5.5 - System.out.println(optAvg.getAsDouble());// 5.5 - double dblAvg = optAvg.orElseGet(() -> Double.NaN); - System.out.println(dblAvg);// 5.5 + optAvg.ifPresent(System.out::println); // 5.5 + if (optAvg.isPresent()) { + System.out.println(optAvg.getAsDouble()); // 5.5 + } + double dblAvg = optAvg.orElse(Double.NaN); // Directly use orElse + System.out.println(dblAvg); // 5.5 OptionalInt optInt = OptionalInt.of(35); - int age = optInt.orElseGet(() -> 0); - System.out.println(age);// 35 - System.out.println(optInt.getAsInt());// 35 - - + int age = optInt.orElse(0); + System.out.println(age); // 35 + System.out.println(optInt.getAsInt()); // 35 } - - public static void doOptionalNull(){ + + public static void doOptionalNull() { Optional optSK = howToDealWithNull("SK"); - optSK.ifPresent(System.out::println);// SK + optSK.ifPresent(System.out::println); // SK Optional emptyOpt = howToDealWithNull(null); - System.out.println( - emptyOpt.orElseGet( - () -> "Empty optional"));// Empty optional - } - public static Optional howToDealWithNull(String param){ - // return param == null ? Optional.empty() : Optional.of(param); - return Optional.ofNullable(param); // same as line above + System.out.println(emptyOpt.orElseGet(Optionals::getEmptyOptionalMessage)); // Empty optional } - public static void doOptionalAPI(){ - Optional valueInOptional = Optional.ofNullable(60.0); - if(valueInOptional.isPresent()){ - System.out.println(valueInOptional.get()); // 60.0 - } - valueInOptional.ifPresent(System.out::println);// 60.0 - System.out.println(valueInOptional.orElse(Double.NaN)); // 60.0 - - Optional emptyOptional = Optional.ofNullable(null); - System.out.println(emptyOptional.orElse(Double.NaN)); // NaN - System.out.println(emptyOptional.orElseGet(() -> Math.random())); // 0.8524556508038182 - System.out.println(emptyOptional.orElseThrow()); // NoSuchElementException -// System.out.println(emptyOptional.orElseThrow(() -> -// new RuntimeException())); // RuntimeException + public static Optional howToDealWithNull(String param) { + return Optional.ofNullable(param); } -} -/* -save - public static void doOptionalPrimitiveAverage(){ - OptionalDouble optAvg = IntStream.rangeClosed(1, 10) - .average(); - // DoubleConsumer - functional interface; functional method is: - // void accept(double value) - optAvg.ifPresent((d) -> System.out.println(d));// 5.5 - System.out.println(optAvg.getAsDouble());// 5.5 - // DoubleSupplier - functional interface; functional method is: - // double getAsDouble() - System.out.println(optAvg.orElseGet(() -> Double.NaN));// 5.5 - } - - // a long way to calculate average (just for showing Optional) - public static Optional calcAverage(int... grades){ - if(grades.length == 0) return Optional.empty(); - int total=0; - for(int grade:grades) total += grade; - return Optional.of((double)total / grades.length); - } - public static void doOptionalAverage(){ - Optional valueInOptional = calcAverage(50, 60, 70); - if(valueInOptional.isPresent()){ - System.out.println(valueInOptional.get()); // 60.0 - } - valueInOptional.ifPresent(System.out::println);// 60.0 + public static void doOptionalAPI() { + Optional valueInOptional = Optional.of(60.0); + valueInOptional.ifPresent(System.out::println); // 60.0 System.out.println(valueInOptional.orElse(Double.NaN)); // 60.0 - Optional emptyOptional = calcAverage();// will return an empty Optional + Optional emptyOptional = Optional.empty(); System.out.println(emptyOptional.orElse(Double.NaN)); // NaN - System.out.println(emptyOptional.orElseGet(() -> Math.random())); // 0.8524556508038182 -// System.out.println(emptyOptional.orElseThrow()); // NoSuchElementException - System.out.println(emptyOptional.orElseThrow(() -> new RuntimeException())); // RuntimeException + System.out.println(emptyOptional.orElseGet(Math::random)); // Random number + try { + System.out.println(emptyOptional.orElseThrow(NoSuchElementException::new)); // NoSuchElementException + } catch (NoSuchElementException e) { + System.out.println("Exception caught: " + e); + } } - */ \ No newline at end of file + private static String getEmptyOptionalMessage() { + return "Empty optional"; + } +} diff --git a/ch17/VoteCounter1.java b/ch17/VoteCounter1.java index 21c9252..a43665b 100644 --- a/ch17/VoteCounter1.java +++ b/ch17/VoteCounter1.java @@ -1,22 +1,38 @@ package ch17; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; +import java.util.concurrent.*; public class VoteCounter1 { + private static final ExecutorService executorService = Executors.newSingleThreadExecutor(); + public static void main(String[] args) { - ExecutorService executor = Executors.newSingleThreadExecutor(); + try { + Future vote1 = getRandomVote(1); + Future vote2 = getRandomVote(2); + Future vote3 = getRandomVote(3); + Future vote4 = getRandomVote(4); + + // Wait for all tasks to complete + executorService.shutdown(); + executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); - // Submitting tasks - for(int i=1; i<=4; i++) { - int voteId = i; - executor.execute(() -> { - System.out.println("Vote " + voteId + " counted by " + Thread.currentThread().threadId()); - }); + int totalVotes = vote1.get() + vote2.get() + vote3.get() + vote4.get(); + System.out.println("Total votes: " + totalVotes); + } catch (InterruptedException | ExecutionException e) { + e.printStackTrace(); + } finally { + if (!executorService.isTerminated()) { + executorService.shutdownNow(); + } } + } - // Remember to shutdown the executor - executor.shutdown(); + public static Future getRandomVote(int i) { + return executorService.submit(() -> { + Thread.sleep(1000); // simulate delay + System.out.println("Vote " + i + " counted by " + Thread.currentThread().threadId()); + return 1; // each vote counts as 1 + }); } -} +} \ No newline at end of file diff --git a/ch17/VoteCounter2.java b/ch17/VoteCounter2.java index 9c38d90..d3b7f1e 100644 --- a/ch17/VoteCounter2.java +++ b/ch17/VoteCounter2.java @@ -2,7 +2,6 @@ import java.util.concurrent.*; - public class VoteCounter2 { private static final ExecutorService executorService = Executors.newSingleThreadExecutor(); @@ -13,17 +12,14 @@ public static void main(String[] args) { Future vote3 = getRandomVote(3); Future vote4 = getRandomVote(4); - // wait until all tasks are done - while (!(vote1.isDone() && vote2.isDone() && vote3.isDone() && vote4.isDone())) { - Thread.sleep(10); // sleep for 10ms then try again - } + // Wait for all tasks to complete + executorService.shutdown(); + executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); int totalVotes = vote1.get() + vote2.get() + vote3.get() + vote4.get(); System.out.println("Total votes: " + totalVotes); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); - } finally { - executorService.shutdown(); } } @@ -34,5 +30,5 @@ public static Future getRandomVote(int i) { return 1; // each vote counts as 1 }); } -} +} diff --git a/ch17/VoteCounter4.java b/ch17/VoteCounter4.java index e136384..e3a333c 100644 --- a/ch17/VoteCounter4.java +++ b/ch17/VoteCounter4.java @@ -5,20 +5,10 @@ public class VoteCounter4 { public static void main(String[] args) { - ExecutorService executorService = Executors.newFixedThreadPool(3); + Thread thread = new Thread(() -> { + System.out.println("Thread ID: " + Thread.currentThread().threadId()); + }); - for (int i = 0; i < 100; i++) { - final int stationId = i; - executorService.submit(() -> { - try { - System.out.println("Counting votes at station: " + stationId + ", Thread id: " + Thread.currentThread().threadId()); - Thread.sleep((int) (Math.random() * 200)); - } catch (InterruptedException e) { - e.printStackTrace(); - } - }); - } - executorService.shutdown(); + thread.start(); } - } diff --git a/ch17/VoteCounter5.java b/ch17/VoteCounter5.java index 16e762a..a4772d5 100644 --- a/ch17/VoteCounter5.java +++ b/ch17/VoteCounter5.java @@ -3,22 +3,26 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -public class VoteCounter5 { - public static void main(String[] args) { - ExecutorService executorService = Executors.newCachedThreadPool(); +import java.util.concurrent.atomic.AtomicInteger; - for (int i = 0; i < 100; i++) { - final int stationId = i; - executorService.submit(() -> { - try { - System.out.println("Counting votes at station: " + stationId + ", Thread id: " + Thread.currentThread().threadId()); - Thread.sleep((int) (Math.random() * 200)); - } catch (InterruptedException e) { - e.printStackTrace(); - } - }); +public class VoteCounter5 implements Runnable { + private AtomicInteger count = new AtomicInteger(0); + + public void run() { + int iterations = 1_000_000; + for (int i = 0; i < iterations; i++) { + voteForCandidate(); } - executorService.shutdown(); + long threadId = Thread.currentThread().threadId(); // Use threadId() instead of getId() + System.out.println("Thread " + threadId + " voted " + count + " times"); } + private void voteForCandidate() { + int currentValue; + int newValue; + do { + currentValue = count.get(); + newValue = currentValue + 1; + } while (!count.compareAndSet(currentValue, newValue)); + } } diff --git a/ch17/dataraceandlock/Count.java b/ch17/dataraceandlock/Count.java index 3b67aae..897464c 100644 --- a/ch17/dataraceandlock/Count.java +++ b/ch17/dataraceandlock/Count.java @@ -4,19 +4,15 @@ import java.util.concurrent.locks.ReentrantLock; public class Count { - static int counter = 0; - static Lock lock = new ReentrantLock(); + private int count = 0; - static void incrementCounter() { - try { - lock.lock(); - int current = counter; - System.out.println("Before: " + counter + ", Current thread: " + Thread.currentThread().threadId()); - counter = current + 1; - System.out.println("After: " + counter); - } finally { - lock.unlock(); - } + public synchronized void increment() { + count++; + System.out.println("Thread ID: " + Thread.currentThread().threadId() + " - Count: " + count); + } + + public int getCount() { + return count; } } @@ -41,3 +37,4 @@ static void incrementCounter() { } } } + diff --git a/ch17/dataraceandlock/Main.java b/ch17/dataraceandlock/Main.java index 748a655..2fc34da 100644 --- a/ch17/dataraceandlock/Main.java +++ b/ch17/dataraceandlock/Main.java @@ -3,7 +3,7 @@ public class Main { public static void main(String[] args) { for (int i = 0; i < 10; i++) { - new Thread(Count::incrementCounter).start(); + new Thread(Count2::incrementCounter).start(); } } } diff --git a/ch17/dataraceandsynchronized/Count.java b/ch17/dataraceandsynchronized/Count.java index 33d0c24..a878987 100644 --- a/ch17/dataraceandsynchronized/Count.java +++ b/ch17/dataraceandsynchronized/Count.java @@ -1,13 +1,16 @@ package ch17.dataraceandsynchronized; public class Count { - static int counter = 0; + private int count = 0; - static synchronized void incrementCounter() { - int current = counter; - System.out.println("Before: " + counter + ", Current thread: " + Thread.currentThread().threadId()); - counter = current + 1; - System.out.println("After: " + counter); + public synchronized void increment() { + count++; + System.out.println("Thread ID: " + Thread.currentThread().threadId() + " - Count: " + count); + } + + public int getCount() { + return count; } } + diff --git a/ch17/dataraceandsynchronized/Main.java b/ch17/dataraceandsynchronized/Main.java index 9069db4..d8a9ab5 100644 --- a/ch17/dataraceandsynchronized/Main.java +++ b/ch17/dataraceandsynchronized/Main.java @@ -2,9 +2,29 @@ public class Main { public static void main(String[] args) { - for (int i = 0; i < 10; i++) { - new Thread(Count::incrementCounter).start(); + Count count = new Count(); + + Runnable task = () -> { + for (int i = 0; i < 100; i++) { + count.increment(); + } + }; + + Thread thread1 = new Thread(task); + Thread thread2 = new Thread(task); + + thread1.start(); + thread2.start(); + + try { + thread1.join(); + thread2.join(); + } catch (InterruptedException e) { + e.printStackTrace(); } + + System.out.println("Final count: " + count.getCount()); } } + diff --git a/ch17/examplerunnableinterface/Main.java b/ch17/examplerunnableinterface/Main.java index f22fed5..8866d89 100644 --- a/ch17/examplerunnableinterface/Main.java +++ b/ch17/examplerunnableinterface/Main.java @@ -2,10 +2,9 @@ public class Main { public static void main(String[] args) { - System.out.println("Hello from main: " + Thread.currentThread().threadId()); MyRunnable myRunnable = new MyRunnable(); Thread thread = new Thread(myRunnable); - thread.run(); // starts the new thread + thread.start(); } } diff --git a/ch17/examplerunnableinterface/MyRunnable.java b/ch17/examplerunnableinterface/MyRunnable.java index 9ad1852..12f49f2 100644 --- a/ch17/examplerunnableinterface/MyRunnable.java +++ b/ch17/examplerunnableinterface/MyRunnable.java @@ -1,9 +1,9 @@ package ch17.examplerunnableinterface; -class MyRunnable implements Runnable { +public class MyRunnable implements Runnable { @Override public void run() { - System.out.println("Hello from thread: " + Thread.currentThread().threadId()); + System.out.println("Thread ID: " + Thread.currentThread().threadId()); } } diff --git a/ch4/_myexercises/Exercise4_4.java b/ch4/_myexercises/Exercise4_4.java new file mode 100644 index 0000000..25b8a2a --- /dev/null +++ b/ch4/_myexercises/Exercise4_4.java @@ -0,0 +1,14 @@ +package ch4._myexercises; + +public class Exercise4_4 { + public static void main(String[] args) { + int safetyLevel = 3; // change this variable to test the code + + if (safetyLevel < 5) { + System.out.println("The safety level is too low."); + throw new IllegalStateException("Safety level is below the acceptable threshold."); + } else { + System.out.println("The safety level is acceptable."); + } + } +} diff --git a/ch4/_myexercises/Exercise4_5.java b/ch4/_myexercises/Exercise4_5.java new file mode 100644 index 0000000..ca091a5 --- /dev/null +++ b/ch4/_myexercises/Exercise4_5.java @@ -0,0 +1,73 @@ +package ch4._myexercises; +public class Exercise4_5 { + public static void main(String[] args) { + String dinosaur1 = "T-Rex"; + String dinosaur2 = "Stegosaurus"; + String dinosaur3 = "Little Velociraptor"; + String dinosaur4 = "Pterodactyl"; + + String size1 = "Large"; + String size2 = "Medium"; + String size3 = "X-Small"; + String size4 = "Small"; + + String housingUnit1 = assignHousingUnit(size1); + String housingUnit2 = assignHousingUnit(size2); + String housingUnit3 = assignHousingUnit(size3); + String housingUnit4 = assignHousingUnit(size4); + + int feedingTimes1 = assignFeedingTimes(size1); + int feedingTimes2 = assignFeedingTimes(size2); + int feedingTimes3 = assignFeedingTimes(size3); + int feedingTimes4 = assignFeedingTimes(size4); + + System.out.println(dinosaur1 + " (" + size1 + ") will be housed in " + housingUnit1 + " and fed " + feedingTimes1 + " times per day."); + System.out.println(dinosaur2 + " (" + size2 + ") will be housed in " + housingUnit2 + " and fed " + feedingTimes2 + " times per day."); + System.out.println(dinosaur3 + " (" + size3 + ") will be housed in " + housingUnit3 + " and fed " + feedingTimes3 + " times per day."); + System.out.println(dinosaur4 + " (" + size4 + ") will be housed in " + housingUnit4 + " and fed " + feedingTimes4 + " times per day."); + } + + public static String assignHousingUnit(String size) { + String housingUnit; + switch (size) { + case "Large": + housingUnit = "Large Enclosure"; + break; + case "Medium": + housingUnit = "Medium Enclosure"; + break; + case "Small": + housingUnit = "Small Enclosure"; + break; + case "X-Small": + housingUnit = "Terrarium"; + break; + default: + housingUnit = "Unknown Housing Unit"; + break; + } + return housingUnit; + } + + public static int assignFeedingTimes(String size) { + int feedingTimes; + switch (size) { + case "Large": + feedingTimes = 4; + break; + case "Medium": + feedingTimes = 3; + break; + case "Small": + feedingTimes = 2; + break; + case "X-Small": + feedingTimes = 1; + break; + default: + feedingTimes = 0; + break; + } + return feedingTimes; + } +} diff --git a/ch4/_myexercises/RatingProgram.java b/ch4/_myexercises/RatingProgram.java new file mode 100644 index 0000000..e5d1b8e --- /dev/null +++ b/ch4/_myexercises/RatingProgram.java @@ -0,0 +1,184 @@ +package ch4._myexercises; + +import java.util.Random; + +public class RatingProgram { + private static final int MAX_VISITORS = 1000; + private static final int MAX_DINOSAURS = 20; + private static final int MAX_STAFF = 50; + private static final double SICK_STAFF_PROBABILITY = 0.2; + + public static void main(String[] args) { + String dinosaur1 = "T-Rex"; + String dinosaur2 = "Stegosaurus"; + String dinosaur3 = "Little Velociraptor"; + String dinosaur4 = "Pterodactyl"; + + String size1 = "Large"; + String size2 = "Medium"; + String size3 = "X-Small"; + String size4 = "Small"; + + String housingUnit1 = assignHousingUnit(size1); + String housingUnit2 = assignHousingUnit(size2); + String housingUnit3 = assignHousingUnit(size3); + String housingUnit4 = assignHousingUnit(size4); + + int feedingTimes1 = assignFeedingTimes(size1); + int feedingTimes2 = assignFeedingTimes(size2); + int feedingTimes3 = assignFeedingTimes(size3); + int feedingTimes4 = assignFeedingTimes(size4); + + int numDinosaurs = 4; + int numStaff = generateRandomStaff(); + int numVisitors = 0; + int weekNumber = 1; + double parkSafetyRating = 5.0; + + System.out.println("Week " + weekNumber + ":"); + System.out.println("Number of dinosaurs: " + numDinosaurs); + System.out.println("Number of staff: " + numStaff); + System.out.println("Number of visitors: " + numVisitors); + System.out.println("Park safety rating: " + parkSafetyRating); + printStaffRoles(numStaff); + System.out.println(); + + System.out.println(dinosaur1 + " (" + size1 + ") will be housed in " + housingUnit1 + " and fed " + feedingTimes1 + " times per day."); + System.out.println(dinosaur2 + " (" + size2 + ") will be housed in " + housingUnit2 + " and fed " + feedingTimes2 + " times per day."); + System.out.println(dinosaur3 + " (" + size3 + ") will be housed in " + housingUnit3 + " and fed " + feedingTimes3 + " times per day."); + System.out.println(dinosaur4 + " (" + size4 + ") will be housed in " + housingUnit4 + " and fed " + feedingTimes4 + " times per day."); + + for (int i = 2; i <= 10; i++) { + weekNumber = i; + numVisitors = generateRandomVisitors(numVisitors); + parkSafetyRating = calculateParkSafetyRating(numDinosaurs, numStaff, numVisitors); + numStaff = adjustStaffing(numStaff, parkSafetyRating); + + System.out.println("\nWeek " + weekNumber + ":"); + System.out.println("Number of dinosaurs: " + numDinosaurs); + System.out.println("Number of staff: " + numStaff); + System.out.println("Number of visitors: " + numVisitors); + System.out.println("Park safety rating: " + parkSafetyRating); + printStaffRoles(numStaff); + } + } + + public static String assignHousingUnit(String size) { + String housingUnit; + switch (size) { + case "Large": + housingUnit = "Large Enclosure"; + break; + case "Medium": + housingUnit = "Medium Enclosure"; + break; + case "Small": + housingUnit = "Small Enclosure"; + break; + case "X-Small": + housingUnit = "Terrarium"; + break; + default: + housingUnit = "Unknown Housing Unit"; + break; + } + return housingUnit; + } + + public static int assignFeedingTimes(String size) { + int feedingTimes; + switch (size) { + case "Large": + feedingTimes = 4; + break; + case "Medium": + feedingTimes = 3; + break; + case "Small": + feedingTimes = 2; + break; + case "X-Small": + feedingTimes = 1; + break; + default: + feedingTimes = 0; + break; + } + return feedingTimes; + } + + public static int generateRandomStaff() { + Random random = new Random(); + return random.nextInt(MAX_STAFF) + 1; + } + + public static int generateRandomVisitors(int currentVisitors) { + Random random = new Random(); + int newVisitors = currentVisitors + random.nextInt(MAX_VISITORS / 10); + return Math.min(newVisitors, MAX_VISITORS); + } + + public static double calculateParkSafetyRating(int numDinosaurs, int numStaff, int numVisitors) { + double dinosaurToStaffRatio = (double) numDinosaurs / numStaff; + double visitorToStaffRatio = (double) numVisitors / numStaff; + double safetyRating = 5.0; + + if (dinosaurToStaffRatio > 2.0 || visitorToStaffRatio > 50.0) { + safetyRating -= 1.0; + } + + if (dinosaurToStaffRatio > 4.0 || visitorToStaffRatio > 100.0) { + safetyRating -= 1.0; + } + + if (dinosaurToStaffRatio > 6.0 || visitorToStaffRatio > 200.0) { + safetyRating -= 1.0; + } + + if (dinosaurToStaffRatio > 8.0 || visitorToStaffRatio > 300.0) { + safetyRating -= 1.0; + } + + if (dinosaurToStaffRatio > 10.0 || visitorToStaffRatio > 400.0) { + safetyRating -= 1.0; + } + + return Math.max(safetyRating, 1.0); + } + + public static int adjustStaffing(int currentStaff, double parkSafetyRating) { + Random random = new Random(); + int sickStaff = 0; + int adjustedStaff = currentStaff; + + for (int i = 0; i < currentStaff; i++) { + if (random.nextDouble() < SICK_STAFF_PROBABILITY) { + sickStaff++; + } + } + + adjustedStaff -= sickStaff; + + if (parkSafetyRating < 3.0) { + adjustedStaff += 5; + } else if (parkSafetyRating < 4.0) { + adjustedStaff += 3; + } + + return Math.min(adjustedStaff, MAX_STAFF); + } + + public static void printStaffRoles(int numStaff) { + int feeders = numStaff / 4; + int cleaners = numStaff / 4; + int securityGuards = numStaff / 4; + int tourGuides = numStaff - feeders - cleaners - securityGuards; + + System.out.println("Staff roles:"); + System.out.println("Feeders: " + feeders); + System.out.println("Cleaners: " + cleaners); + System.out.println("Security Guards: " + securityGuards); + System.out.println("Tour Guides: " + tourGuides); + } +} + diff --git a/ch4/exercises/Exercise4_1.java b/ch4/exercises/Exercise4_1.java index 097e1d3..28ba526 100644 --- a/ch4/exercises/Exercise4_1.java +++ b/ch4/exercises/Exercise4_1.java @@ -2,8 +2,10 @@ public class Exercise4_1 { public static void main(String[] args) { - boolean isCarnivore = true; // change this variable to test the code + boolean isCarnivore; // change this variable to test the code + isCarnivore = getRandomBoolean(); + System.out.println(isCarnivore + " is the result of getRandomBoolean()."); if (isCarnivore) { System.out.println("The dinosaur is a carnivore."); } else { @@ -11,4 +13,14 @@ public static void main(String[] args) { } } + + public static boolean getRandomBoolean() { + // Get the current time in milliseconds since the Unix epoch + long currentTime = System.currentTimeMillis(); + + // Use the least significant bit of the current time as the random boolean + boolean randomBoolean = (currentTime & 1) == 1; + + return randomBoolean; + } } diff --git a/ch5/_myexercises/DinoMealPlanner.java b/ch5/_myexercises/DinoMealPlanner.java new file mode 100644 index 0000000..cafb33d --- /dev/null +++ b/ch5/_myexercises/DinoMealPlanner.java @@ -0,0 +1,43 @@ +package ch5._myexercises; + +public class DinoMealPlanner { + public static void main(String[] args) { + // Feeding times for different dinosaur species + int[] tRexFeedingTimes = {8, 14, 20}; + int[] brachiosaurusFeedingTimes = {7, 11, 15, 19}; + + // Meal portions for different dinosaur species + int tRexMealPortion = 100; // kg + int brachiosaurusMealPortion = 250; // kg + + // Loop through the 24 hours of the day + for (int currentTime = 0; currentTime < 24; currentTime++) { + boolean isTRexFeedingTime = false; + boolean isBrachiosaurusFeedingTime = false; + + // Check if it's feeding time for T-Rex + for (int feedingTime : tRexFeedingTimes) { + if (currentTime == feedingTime) { + System.out.println("It's " + currentTime + ":00 - Feeding time for T-Rex with " + tRexMealPortion + "kg of food"); + isTRexFeedingTime = true; + break; + } + } + + // Check if it's feeding time for Brachiosaurus + for (int feedingTime : brachiosaurusFeedingTimes) { + if (currentTime == feedingTime) { + System.out.println("It's " + currentTime + ":00 - Feeding time for Brachiosaurus with " + brachiosaurusMealPortion + "kg of food"); + isBrachiosaurusFeedingTime = true; + break; + } + } + + // If it's not feeding time for either dinosaur + if (!isTRexFeedingTime && !isBrachiosaurusFeedingTime) { + System.out.println("It's " + currentTime + ":00 - It's not time to feed the T-Rex or the Brachiosaurus"); + } + } + } +} + diff --git a/ch5/_myexercises/Exercise5_1.java b/ch5/_myexercises/Exercise5_1.java new file mode 100644 index 0000000..751eb6f --- /dev/null +++ b/ch5/_myexercises/Exercise5_1.java @@ -0,0 +1,9 @@ +package ch5._myexercises; + +public class Exercise5_1 { + public static void main(String[] args) { + for (int i = 1; i <= 100; i++) { + System.out.println("dino" + i); + } + } +} diff --git a/ch5/_myexercises/Exercise5_2.java b/ch5/_myexercises/Exercise5_2.java new file mode 100644 index 0000000..c8af287 --- /dev/null +++ b/ch5/_myexercises/Exercise5_2.java @@ -0,0 +1,70 @@ +package ch5._myexercises; +import java.util.Random; +import java.util.Scanner; + +public class Exercise5_2 { + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + Random random = new Random(); + int totalPoundsFed = 0; + String dinoSize = getDinoSize(random); + int recommendedAmount = getPoundsToFeed(dinoSize); + + do { + System.out.println("Is the dinosaur still hungry? (Enter 'full' if not)"); + String input = scanner.nextLine().toLowerCase(); + + if (input.equals("full")) { + System.out.println("Total pounds of meat fed: " + totalPoundsFed); + break; + } + + int poundsToFeed = getPoundsToFeed(dinoSize); + totalPoundsFed += poundsToFeed; + System.out.println("Feed the " + dinoSize + " dinosaur " + poundsToFeed + " pounds of meat."); + System.out.println("Total pounds of meat fed so far: " + totalPoundsFed); + + if (totalPoundsFed > recommendedAmount) { + System.out.println("You have exceeded the recommended amount; the dinosaur is getting sick. Please enter 'full'"); + } + + } while (true); + + scanner.close(); + } + + private static String getDinoSize(Random random) { + int size = random.nextInt(5); + switch (size) { + case 0: + return "x-small"; + case 1: + return "small"; + case 2: + return "medium"; + case 3: + return "large"; + case 4: + return "x-large"; + default: + return "unknown"; + } + } + + private static int getPoundsToFeed(String dinoSize) { + switch (dinoSize) { + case "x-small": + return 5; + case "small": + return 10; + case "medium": + return 20; + case "large": + return 50; + case "x-large": + return 75; + default: + return 0; + } + } +} diff --git a/ch5/_myexercises/Exercise5_3.java b/ch5/_myexercises/Exercise5_3.java new file mode 100644 index 0000000..3652ca1 --- /dev/null +++ b/ch5/_myexercises/Exercise5_3.java @@ -0,0 +1,39 @@ +package ch5._myexercises; +import java.util.Random; + +public class Exercise5_3 { + public static void main(String[] args) { + Random random = new Random(); + int parkStartHour = 8 + random.nextInt(2); // Random hour between 8 and 9 + int parkStartMinute = random.nextInt(60); // Random minute between 0 and 59 + int currentHour = 7; // Start at 7 AM + int currentMinute = random.nextInt(60 * (parkStartHour - currentHour) + parkStartMinute); // Random minute before park start time + + while (currentHour < parkStartHour || (currentHour == parkStartHour && currentMinute < parkStartMinute)) { + int minutesUntilOpen = (parkStartHour - currentHour) * 60 + (parkStartMinute - currentMinute); + String currentTime = formatTime(currentHour, currentMinute) + " AM"; + String parkOpeningTime = formatTime(parkStartHour, parkStartMinute) + " AM"; + System.out.println("Current time: " + currentTime + ", Park opening time: " + parkOpeningTime + ", The park will open in " + minutesUntilOpen + " minutes."); + + currentMinute += 5; // Elapse 5 minutes + if (currentMinute >= 60) { + currentHour++; + currentMinute -= 60; + } + } + + String finalTime = formatTime(parkStartHour, parkStartMinute) + " AM"; + System.out.println("Hurray! The park is open at " + finalTime + "! Come on in!"); + } + + private static String formatTime(int hour, int minute) { + String hourString = String.format("%02d", hour); + String minuteString = String.format("%02d", minute); + return hourString + ":" + minuteString; + } +} + + + + + diff --git a/ch5/_myexercises/WhileLoop.java b/ch5/_myexercises/WhileLoop.java new file mode 100644 index 0000000..ee77f00 --- /dev/null +++ b/ch5/_myexercises/WhileLoop.java @@ -0,0 +1,32 @@ +package ch5._myexercises; +import java.util.Scanner; + +public class WhileLoop { + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + int totalSum = 0; + boolean shouldExit = false; + + while (!shouldExit) { + System.out.print("Enter a number or '=', 'done', or 'exit' to finish: "); + String userInput = scanner.nextLine().trim().toLowerCase(); + + switch (userInput) { + case "=", "done", "exit": + System.out.println("The total sum is: " + totalSum); + shouldExit = true; + break; + default: + try { + int num = Integer.parseInt(userInput); + totalSum += num; + } catch (NumberFormatException e) { + System.out.println("Invalid input. Please enter a number or '=', 'done', or 'exit'."); + } + break; + } + } + scanner.close(); + } +} + diff --git a/ch6/_myExercises/Exercise6_1.java b/ch6/_myExercises/Exercise6_1.java new file mode 100644 index 0000000..b913e65 --- /dev/null +++ b/ch6/_myExercises/Exercise6_1.java @@ -0,0 +1,34 @@ +package ch6._myExercises; +import java.util.HashSet; +import java.util.Random; +import java.util.Set; + +public class Exercise6_1 { + private static final String[] DINOSAUR_SPECIES = {"Tyrannosaurus", "Velociraptor", "Triceratops", "Brachiosaurus", "Stegosaurus"}; + private static final String[] CUTE_NAMES = {"Fluffy", "Cuddles", "Snuggles", "Sweetie", "Buttercup", "Daisy", "Sunshine", "Sprinkles"}; + + public static void main(String[] args) { + String[] dinosaurNames = generateUniqueDinosaurNames(); + printDinosaurNames(dinosaurNames); + } + + private static String[] generateUniqueDinosaurNames() { + Random random = new Random(); + Set uniqueNames = new HashSet<>(); + + while (uniqueNames.size() < 10) { + String species = DINOSAUR_SPECIES[random.nextInt(DINOSAUR_SPECIES.length)]; + String cuteName = CUTE_NAMES[random.nextInt(CUTE_NAMES.length)]; + String name = species + "_" + cuteName; + uniqueNames.add(name); + } + + return uniqueNames.toArray(new String[0]); + } + + private static void printDinosaurNames(String[] names) { + for (String name : names) { + System.out.println(name); + } + } +} diff --git a/ch6/_myExercises/Exercise6_2.java b/ch6/_myExercises/Exercise6_2.java new file mode 100644 index 0000000..98a19dd --- /dev/null +++ b/ch6/_myExercises/Exercise6_2.java @@ -0,0 +1,44 @@ +package ch6._myExercises; + +import java.util.*; + +public class Exercise6_2 { + private static final String[] DINOSAUR_SPECIES = {"Tyrannosaurus", "Velociraptor", "Triceratops", "Brachiosaurus", "Stegosaurus"}; + private static final String[] CUTE_NAMES = {"Fluffy", "Cuddles", "Snuggles", "Sweetie", "Buttercup", "Daisy", "Sunshine", "Sprinkles"}; + + public static void main(String[] args) { + String[][] dinosaurNamesAndWeights = generateUniqueDinosaurNamesAndWeights(); + printDinosaurNamesAndWeights(dinosaurNamesAndWeights); + } + + private static String[][] generateUniqueDinosaurNamesAndWeights() { + Random random = new Random(); + Set uniqueNames = new HashSet<>(); + List namesAndWeights = new ArrayList<>(); + + while (uniqueNames.size() < 10) { + String species = DINOSAUR_SPECIES[random.nextInt(DINOSAUR_SPECIES.length)]; + String cuteName = CUTE_NAMES[random.nextInt(CUTE_NAMES.length)]; + String name = species + "_" + cuteName; + float weight; + if (species.equals("Brachiosaurus")) { + weight = random.nextFloat() * 60000 + 30000; // 30,000 to 90,000 lbs + } else if (species.equals("Velociraptor")) { + weight = random.nextFloat() * 30 + 15; // 15 to 45 lbs + } else { + weight = random.nextFloat() * 10000; // Assuming weight in lbs for other species + } + + uniqueNames.add(name); + namesAndWeights.add(new String[]{name, String.valueOf(weight)}); + } + + return namesAndWeights.toArray(new String[0][]); + } + + private static void printDinosaurNamesAndWeights(String[][] namesAndWeights) { + for (String[] nameAndWeight : namesAndWeights) { + System.out.printf("%s - %.1f lbs%n", nameAndWeight[0], Double.parseDouble(nameAndWeight[1])); + } + } +} diff --git a/ch6/_myExercises/Exercise6_3.java b/ch6/_myExercises/Exercise6_3.java new file mode 100644 index 0000000..02507a2 --- /dev/null +++ b/ch6/_myExercises/Exercise6_3.java @@ -0,0 +1,44 @@ +package ch6._myExercises; + +import java.util.*; + +public class Exercise6_3 { + private static final String[] DINOSAUR_SPECIES = {"Tyrannosaurus", "Velociraptor", "Triceratops", "Brachiosaurus", "Stegosaurus"}; + private static final String[] CUTE_NAMES = {"Fluffy", "Cuddles", "Snuggles", "Sweetie", "Buttercup", "Daisy", "Sunshine", "Sprinkles"}; + + public static void main(String[] args) { + String[][] dinosaurNamesAndWeights = generateUniqueDinosaurNamesAndWeights(); + printDinosaurNamesAndWeights(dinosaurNamesAndWeights); + } + + private static String[][] generateUniqueDinosaurNamesAndWeights() { + Random random = new Random(); + Set uniqueNames = new HashSet<>(); + List namesAndWeights = new ArrayList<>(); + + while (uniqueNames.size() < 10) { + String species = DINOSAUR_SPECIES[random.nextInt(DINOSAUR_SPECIES.length)]; + String cuteName = CUTE_NAMES[random.nextInt(CUTE_NAMES.length)]; + String name = species + "_" + cuteName; + float weight; + if (species.equals("Brachiosaurus")) { + weight = random.nextFloat() * 60000 + 30000; // 30,000 to 90,000 lbs + } else if (species.equals("Velociraptor")) { + weight = random.nextFloat() * 30 + 15; // 15 to 45 lbs + } else { + weight = random.nextFloat() * 10000; // Assuming weight in lbs for other species + } + + uniqueNames.add(name); + namesAndWeights.add(new String[]{name, String.valueOf(weight)}); + } + + return namesAndWeights.toArray(new String[0][]); + } + + private static void printDinosaurNamesAndWeights(String[][] namesAndWeights) { + for (String[] nameAndWeight : namesAndWeights) { + System.out.printf("%s - %.1f lbs%n", nameAndWeight[0], Double.parseDouble(nameAndWeight[1])); + } + } +} diff --git a/ch6/_myExercises/Exercise6_4.java b/ch6/_myExercises/Exercise6_4.java new file mode 100644 index 0000000..6e42db8 --- /dev/null +++ b/ch6/_myExercises/Exercise6_4.java @@ -0,0 +1,31 @@ +package ch6._myExercises; + +import java.util.*; + +public class Exercise6_4 { + private static final String[] EMPLOYEE_NAMES = {"John", "Jane", "Michael", "Emily", "David", "Sarah", "Daniel", "Jessica", "Matthew", "Ashley", "Andrew", "Amanda", "Joseph", "Samantha", "Christopher", "Brittany", "Joshua", "Stephanie", "Robert", "Lauren"}; + private static final String[] DINOSAUR_SPECIES = {"Tyrannosaurus", "Velociraptor", "Triceratops", "Brachiosaurus", "Stegosaurus"}; + private static final String[] CUTE_NAMES = {"Fluffy", "Cuddles", "Snuggles", "Sweetie", "Buttercup", "Daisy", "Sunshine", "Sprinkles"}; + + public static void main(String[] args) { + String[][] employeeAndDinosaurs = generateEmployeeAndDinosaurs(); + for (String[] pair : employeeAndDinosaurs) { + System.out.println(pair[0] + " is assigned to care for " + pair[1]); + } + } + + private static String[][] generateEmployeeAndDinosaurs() { + Random random = new Random(); + List employeeAndDinosaurs = new ArrayList<>(); + + for (int i = 0; i < 20; i++) { + String employee = EMPLOYEE_NAMES[random.nextInt(EMPLOYEE_NAMES.length)]; + String species = DINOSAUR_SPECIES[random.nextInt(DINOSAUR_SPECIES.length)]; + String cuteName = CUTE_NAMES[random.nextInt(CUTE_NAMES.length)]; + String dinosaur = species + "_" + cuteName; + employeeAndDinosaurs.add(new String[]{employee, dinosaur}); + } + + return employeeAndDinosaurs.toArray(new String[0][]); + } +} diff --git a/ch7/_myexercises/Exercise7_1.java b/ch7/_myexercises/Exercise7_1.java new file mode 100644 index 0000000..d1d2220 --- /dev/null +++ b/ch7/_myexercises/Exercise7_1.java @@ -0,0 +1,85 @@ +package ch7._myexercises; + +public class Exercise7_1 { + public static void main(String[] args) { + + for (int i = 0; i < 22; i++) { + System.out.println(dinoStage(i)); + } + + for (int i = 0; i < 220; i+=10) { + System.out.println("Dinosaurs that weigh " + i + "lbs require " + dinoFoodIntake(i) + " lbs of food"); + } + + String[][] dinoList = createDinoArray(); + System.out.println("The average age of the dinosaurs is: " + avgAge(dinoList)); + } + private static String dinoStage ( int age){ + if (age >= 0 && age <= 1) { + return "hatchling"; + } else if (age > 1 && age <= 4) { + return "juvenile"; + } else if (age > 4 && age <= 20) { + return "adult"; + } else { + return "senior"; + } + } + + private static int dinoFoodIntake(float weight) { + int lbs_of_food = 0; + lbs_of_food = (int) Math.max(5, Math.log(weight) * 10); + return lbs_of_food; + } + private static String[][] createDinoArray() { + String[][] dinoNames = { + {"Tyrannosaurus Rex", "8"}, + {"Brachiosaurus", "30"}, + {"Velociraptor", "2"}, + {"Triceratops", "18"}, + {"Stegosaurus", "12"}, + {"Spinosaurus", "15"}, + {"Allosaurus", "10"}, + {"Diplodocus", "25"}, + {"Ankylosaurus", "20"}, + {"Parasaurolophus", "15"}, + {"Gallimimus", "5"}, + {"Corythosaurus", "12"}, + {"Pachycephalosaurus", "8"}, + {"Oviraptor", "3"}, + {"Iguanodon", "10"}, + {"Deinonychus", "4"}, + {"Quetzalcoatlus", "8"}, + {"Pteranodon", "6"}, + {"Compsognathus", "1"}, + {"Archaeopteryx", "1"}, + {"Plateosaurus", "15"}, + {"Coelophysis", "3"}, + {"Dilophosaurus", "6"}, + {"Herrerasaurus", "5"}, + {"Eoraptor", "2"}, + {"Caudipteryx", "3"}, + {"Tsintaosaurus", "12"}, + {"Shunosaurus", "18"}, + {"Mamenchisaurus", "35"}, + {"Gigantoraptor", "10"} + }; + return dinoNames; + } + + private static double avgAge(String[][] dinoArray) { + double totalAge = 0; + for (String[] dino : dinoArray) { + totalAge += Integer.parseInt(dino[1]); + } + return totalAge / dinoArray.length; + } + + private static float avgAge(int[] ages) { + int sum = 0; + for (int age : ages) { + sum += age; + } + return (float) sum / ages.length; + } +} diff --git a/ch7/_myexercises/MesozonicEdenAssistant.java b/ch7/_myexercises/MesozonicEdenAssistant.java new file mode 100644 index 0000000..57a6ea1 --- /dev/null +++ b/ch7/_myexercises/MesozonicEdenAssistant.java @@ -0,0 +1,368 @@ +package ch7._myexercises; + +import java.time.DayOfWeek; +import java.time.LocalDateTime; +import java.util.Scanner; + +public class MesozonicEdenAssistant { + private static boolean exit = false; + private static Scanner scanner = new Scanner(System.in); + + public static void main(String[] args) { + while (!exit) { + System.out.println("\nMesozonic Eden Assistant Menu:"); + System.out.println("1. Manage Dinosaurs"); + System.out.println("2. Manage Guests"); + System.out.println("3. Manage Park Hours"); + System.out.println("4. Manage Visitors"); + System.out.println("5. Greet All Current Guests"); + System.out.println("6. Exit"); + System.out.print("Enter your choice: "); + int choice = scanner.nextInt(); + scanner.nextLine(); // Consume newline character + + switch (choice) { + case 1: + Dinosaur.manageDinosaurs(); + break; + case 2: + manageGuests(); + break; + case 3: + manageParkHours(); + break; + case 4: + manageVisitors(); + break; + case 5: + greetAllCurrentGuests(); + break; + case 6: + exit = true; + break; + default: + System.out.println("Invalid choice. Please try again."); + break; + } + } + scanner.close(); + } + + private static void manageGuests() { + Scanner scanner = new Scanner(System.in); + System.out.println("Select an option:"); + System.out.println("1. Add Guest"); + System.out.println("2. Remove Guest"); + System.out.println("3. Delete Guest"); + System.out.println("4. Print Guest Information"); + int choice = scanner.nextInt(); + Guest guest = new Guest(); + switch (choice) { + case 1: + Scanner scannerGuest = new Scanner(System.in); + System.out.print("Enter first name: "); + String firstName = scannerGuest.nextLine(); + System.out.print("Enter last name: "); + String lastName = scannerGuest.nextLine(); + System.out.print("Is this a new guest? (Enter 'new' or 'returning'): "); + String isNewGuest = scannerGuest.nextLine(); + boolean isNew = isNewGuest.equalsIgnoreCase("new"); + guest.addVisitor(firstName, lastName, isNew); + break; + case 2: + guest.printGuestInfo(); + System.out.println("Select a visitor to delete:"); + int visitorIndex = scanner.nextInt(); + guest.deactivateVisitor(visitorIndex); + break; + case 3: + Scanner guestScanner = new Scanner(System.in); + System.out.print("Enter visitor's first name: "); + String firstNameGuest = guestScanner.nextLine(); + System.out.print("Enter visitor's last name: "); + String lastNameGuest = guestScanner.nextLine(); + guest.logVisit(firstNameGuest, lastNameGuest); + break; + case 4: + guest.printGuestInfo(); + break; + default: + System.out.println("Invalid choice"); + } + } + + private static void manageParkHours() { + // Implement park hours management functionality here + } + + private static void manageVisitors() { + // Implement visitor management functionality here + } + + private static void greetAllCurrentGuests() { + // Implement guest greeting functionality here + } +} + +class Dinosaur { + int age; + float weightLbs; + String species; + String randomName; + + static Dinosaur[] dinosaurs = new Dinosaur[100]; + static int numDinosaurs = 0; + + public static void addDinosaur(int age, float weightLbs, String species, String cuteName) { + Dinosaur dino = new Dinosaur(); + dino.age = age; + dino.weightLbs = weightLbs; + dino.species = species; + dino.randomName = cuteName; + dinosaurs[numDinosaurs] = dino; + numDinosaurs++; + } + + public static Dinosaur lookupDinosaur(String cuteName) { + for (int i = 0; i < numDinosaurs; i++) { + if (dinosaurs[i].randomName.equals(cuteName)) { + return dinosaurs[i]; + } + } + return null; + } + + public static void removeDinosaur(String cuteName) { + for (int i = 0; i < numDinosaurs; i++) { + if (dinosaurs[i].randomName.equals(cuteName)) { + for (int j = i; j < numDinosaurs - 1; j++) { + dinosaurs[j] = dinosaurs[j + 1]; + } + numDinosaurs--; + break; + } + } + } + + public static void changeWeightLbs(String randomName, float newWeight) { + Dinosaur dino = lookupDinosaur(randomName); + if (dino != null) { + dino.weightLbs = newWeight; + } + } + + public static void changeCuteName(String oldName, String newName) { + Dinosaur dino = lookupDinosaur(oldName); + if (dino != null) { + dino.randomName = newName; + } + } + + public static void changeAge(String randomName, int newAge) { + Dinosaur dino = lookupDinosaur(randomName); + if (dino != null) { + dino.age = newAge; + } + } + + public static void printDinosaurInfo() { + System.out.println("Age\tWeight (lbs)\tSpecies\t\tRandom Name"); + System.out.println("---\t------------\t-------\t\t-----------"); + for (int i = 0; i < numDinosaurs; i++) { + Dinosaur dino = dinosaurs[i]; + System.out.printf("%d\t%.2f\t\t%s\t\t%s\n", dino.age, dino.weightLbs, dino.species, dino.randomName); + } + } + + public static void manageDinosaurs() { + System.out.println("Manage Dinosaurs Menu:"); + System.out.println("1. Add Dinosaur"); + System.out.println("2. Remove Dinosaur"); + System.out.println("3. Change Weight"); + System.out.println("4. Change Name"); + System.out.println("5. Change Age"); + System.out.println("6. Print Dinosaur Information"); + System.out.println("7. Exit"); + + Scanner scanner = new Scanner(System.in); + int choice = scanner.nextInt(); + + switch (choice) { + case 1: + System.out.print("Enter age: "); + int age = scanner.nextInt(); + System.out.print("Enter weight (lbs): "); + float weightLbs = scanner.nextFloat(); + String[] dinosaurs = {"Tyrannosaurus", "Velociraptor", "Triceratops", "Brachiosaurus", "Stegosaurus"}; + System.out.print("Select a dinosaur species (1. Tyrannosaurus, 2. Velociraptor, 3. Triceratops, 4. Brachiosaurus, 5. Stegosaurus): "); + int choiceSpecies = scanner.nextInt() - 1; + String species = dinosaurs[choiceSpecies]; + + System.out.println("Pick a pet name from the list:"); + + String[] petNames = {"Rex", "Raptor", "Triceratops", "Brachie", "Steggie", "Dino", "Spike", "Tiny", "Chomper", "Roary", "Stomp", "Crunch", "Nibbles", "Scales", "Claws", "Jaws", "Rumble", "Growler", "Snarl", "Gnasher"}; + for (int i = 0; i < petNames.length; i++) { + System.out.println((i + 1) + ". " + petNames[i]); + } + int choicePetName = scanner.nextInt() - 1; + String randomName = petNames[choicePetName]; + addDinosaur(age, weightLbs, species, randomName); + break; + case 2: + System.out.print("Enter name to remove: "); + String nameToRemove = scanner.next(); + removeDinosaur(nameToRemove); + break; + case 3: + System.out.print("Enter name to change weight: "); + String nameToChangeWeight = scanner.next(); + System.out.print("Enter new weight (lbs): "); + float newWeight = scanner.nextFloat(); + changeWeightLbs(nameToChangeWeight, newWeight); + break; + case 4: + System.out.print("Enter name to change: "); + String oldName = scanner.next(); + System.out.print("Enter new random name: "); + String newName = scanner.next(); + changeCuteName(oldName, newName); + break; + case 5: + System.out.print("Enter name of dinosaur to change age: "); + String nameToChangeAge = scanner.next(); + System.out.print("Enter new age: "); + int newAge = scanner.nextInt(); + changeAge(nameToChangeAge, newAge); + break; + case 6: + printDinosaurInfo(); + break; + case 7: + System.out.println("Exiting..."); + break; + default: + System.out.println("Invalid choice. Try again."); + manageDinosaurs(); + } + } +} + +class Guest { + String firstName; + String lastName; + boolean member; + int visits; + LocalDateTime latestVisit; + + static Guest[] guests = new Guest[100]; + static int numGuests = 0; + private boolean active; + + public static void addVisitor(String firstName, String lastName, boolean member) { + Guest guest = new Guest(); + guest.firstName = firstName; + guest.lastName = lastName; + guest.member = member; + guest.visits = 1; + guest.latestVisit = LocalDateTime.now(); + guest.active = true; + guests[numGuests] = guest; + numGuests++; + } + + public static void logVisit(String firstName, String lastName) { + for (int i = 0; i < numGuests; i++) { + if (guests[i].firstName.equals(firstName) && guests[i].lastName.equals(lastName)) { + guests[i].visits++; + guests[i].latestVisit = LocalDateTime.now(); + break; + } + } + } + + public static void printGuestInfo() { + System.out.println("Guests:"); + for (int i = 0; i < numGuests; i++) { + System.out.println(guests[i].firstName + " " + guests[i].lastName + " " + guests[i].visits + " " + guests[i].latestVisit + " " + guests[i].active); + } + } + + public static void deactivateVisitor(int visitorIndex) { + if (visitorIndex >= 0 && visitorIndex < numGuests) { + guests[visitorIndex].active = false; + } + } + +} + +class Employee { + String firstName; + String lastName; + String shift; + int primaryDinosaur; + + static Employee[] employees = new Employee[100]; + static int numEmployees = 0; + + public static void addEmployee(String firstName, String lastName, String shift, int primaryDinosaur) { + Employee employee = new Employee(); + employee.firstName = firstName; + employee.lastName = lastName; + employee.shift = shift; + employee.primaryDinosaur = primaryDinosaur; + employees[numEmployees] = employee; + numEmployees++; + } + + public static void deleteEmployee(String firstName, String lastName) { + for (int i = 0; i < numEmployees; i++) { + if (employees[i].firstName.equals(firstName) && employees[i].lastName.equals(lastName)) { + for (int j = i; j < numEmployees - 1; j++) { + employees[j] = employees[j + 1]; + } + numEmployees--; + break; + } + } + } + + public static void editEmployee(String firstName, String lastName, String newShift, int newPrimaryDinosaur) { + for (int i = 0; i < numEmployees; i++) { + if (employees[i].firstName.equals(firstName) && employees[i].lastName.equals(lastName)) { + employees[i].shift = newShift; + employees[i].primaryDinosaur = newPrimaryDinosaur; + break; + } + } + } +} + +class ParkHours { + LocalDateTime openingTime; + LocalDateTime closingTime; + DayOfWeek day; + + static ParkHours[] parkHours = new ParkHours[7]; + + public static void addTime(DayOfWeek day, LocalDateTime openingTime, LocalDateTime closingTime) { + int index = day.getValue() - 1; + ParkHours ph = new ParkHours(); + ph.day = day; + ph.openingTime = openingTime; + ph.closingTime = closingTime; + parkHours[index] = ph; + } + + public static void editTime(DayOfWeek day, LocalDateTime newOpeningTime, LocalDateTime newClosingTime) { + int index = day.getValue() - 1; + if (parkHours[index] != null) { + parkHours[index].openingTime = newOpeningTime; + parkHours[index].closingTime = newClosingTime; + } + } + + public static void deleteTime(DayOfWeek day) { + int index = day.getValue() - 1; + parkHours[index] = null; + } +} diff --git a/ch8/_myexercises/Dinosaur.java b/ch8/_myexercises/Dinosaur.java new file mode 100644 index 0000000..21c1799 --- /dev/null +++ b/ch8/_myexercises/Dinosaur.java @@ -0,0 +1,57 @@ +package ch8._myexercises; + +import java.util.Random; +import java.util.ArrayList; +import java.util.List; + +public class Dinosaur { + String name; + int age; + Species species; + enum Species { + T_Rex, + Velociraptor, + // add other species cases as needed + } + public Dinosaur(String name, int age, Species species) { + this.name = name; + this.age = age; + this.species = species; + } + + public String getName() { + return this.name; + } + + public int getAge() { + return this.age; + } + + public Species getSpecies() { + return this.species; + } + + public static void main(String[] args) { + + String[] cuteNames = {"Fluffy", "Cuddles", "Snuggles", "Sweetie", "Cutie"}; + /** + * Creates a list of 5 randomly generated Dinosaur objects. + * Each Dinosaur has a random name from the cuteNames array, + * a random age between 0 and 24, and a random species from + * the Species enum. + */ + List dinosaurs = new ArrayList<>(); + for (int i = 0; i < 5; i++) { + Dinosaur dinosaur = new Dinosaur(cuteNames[i], new Random().nextInt(25), + Species.values()[new Random().nextInt(Species.values().length)]); + dinosaurs.add(dinosaur); + } + + System.out.printf("%-15s%-5s%-10s%n", "Name", "Age", "Species"); + System.out.println("-------------------------------"); + for (Dinosaur dino : dinosaurs) { + System.out.printf("%-15s%-5d%-10s%n", dino.getName(), dino.getAge(), dino.getSpecies()); + } + + } +} diff --git a/ch8/_myexercises/Employee.java b/ch8/_myexercises/Employee.java new file mode 100644 index 0000000..ac0f1b3 --- /dev/null +++ b/ch8/_myexercises/Employee.java @@ -0,0 +1,58 @@ +package ch8._myexercises; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +public class Employee { + private String name; + private Title jobTitle; + private int experienceYears; + + public Employee(String name, Title jobTitle, int experienceYears) { + this.name = name; + this.jobTitle = jobTitle; + this.experienceYears = experienceYears; + } + + enum Title { + ZOOKEEPER, + VETERINARIAN, + ANIMAL_TRAINER, + GROUNDSKEEPER, + EDUCATOR, + ADMINISTRATOR, + OTHER + } + public String getName() { + return this.name; + } + + public Title getJobTitle() { + return this.jobTitle; + } + + public int getExperienceYears() { + return this.experienceYears; + } + + + public static void main(String[] args) { + + String[] empNames = {"Joe", "Juan", "Susan", "Bonita", "Shakil"}; + + List employees = new ArrayList<>(); + for (int i = 0; i < 5; i++) { + Employee employee = new Employee(empNames[i], + Employee.Title.values()[new Random().nextInt(Employee.Title.values().length)], + new Random().nextInt(10)); + employees.add(employee); + } + + System.out.printf("%-15s%-15s%-15s%n", "Name", "Years of Experience", "Title"); + System.out.println("-------------------------------"); + for (Employee emp : employees) { + System.out.printf("%-15s%-15d%-15s%n", emp.getName(), emp.getExperienceYears(), emp.getJobTitle()); + } + } +} diff --git a/ch8/_myexercises/Park.java b/ch8/_myexercises/Park.java new file mode 100644 index 0000000..228ef5b --- /dev/null +++ b/ch8/_myexercises/Park.java @@ -0,0 +1,25 @@ +package ch8._myexercises; + +public class Park { + enum OpenDay { + MONDAY("9-5"), + TUESDAY("9-5"), + WEDNESDAY("9-5"), + THURSDAY("9-5"), + FRIDAY("9-10"), + SATURDAY("10-5"); + + private String hoursOfOperation; + OpenDay(String hoursOfOperation) { + this.hoursOfOperation = hoursOfOperation; + } + public String getHoursOfOperation() { + return hoursOfOperation; + } + } + + public static void main(String[] args) { + String[] parkAnimals = {"T-Rex", "Velociraptor", "Deinonychus", "Triceratops", "Tyrannosaurus", "Stegosaurus"}; + String[] parkEnclosures = {"Small Herbivore Enclosure", "Medium Herbivore Enclosure", "Large Herbivore Enclosure", "Carnivore Enclosure"}; + } +} diff --git a/ch9/PatternMatchingForSwitch.java b/ch9/PatternMatchingForSwitch.java index 0b0192f..bb26ba2 100644 --- a/ch9/PatternMatchingForSwitch.java +++ b/ch9/PatternMatchingForSwitch.java @@ -1,39 +1,84 @@ -package java21.pattern_matching_for_switch; - -sealed class Vehicle permits Car, Boat, Train{} -final class Car extends Vehicle { - private int numDoors; - Car(int numDoors){ - this.numDoors = numDoors; - } - public int getNumDoors() {return numDoors;} - public String onRoad(){ return "I can move on the road"; } -} -final class Boat extends Vehicle{} -final class Train extends Vehicle{} +package ch9; public class PatternMatchingForSwitch { - public static void patternMatchingSwitch(Vehicle v) { - System.out.println( - switch(v){ - case Boat b -> "It's a Boat"; - case Train t -> "It's a Train"; - case Car c when c.getNumDoors() == 4 -> - "Saloon/Sedan: "+ c.onRoad(); // custom Car method - case Car c when c.getNumDoors() == 2 -> - "Convertible: " + c.onRoad(); - case null, default -> "Invalid type"; // exhaustivess + + public static void patternMatchingSwitch(VehicleType v) { + String result = switch (v) { + case Boat b -> b.toString(); + case Train t -> t.toString(); + case Auto c -> { + if (c.getNumDoors() == 4) { + yield "Saloon/Sedan: " + c.onRoad(); + } else if (c.getNumDoors() == 2) { + yield "Convertible: " + c.onRoad(); + } else { + yield "Unknown Auto type"; + } } - ); + case null -> "Invalid type"; + default -> "Invalid type"; // exhaustiveness + }; + System.out.println(result); } + + // Example usage: public static void main(String[] args) { - patternMatchingSwitch(new Car(2)); - patternMatchingSwitch(new Car(4)); - patternMatchingSwitch(new Boat()); - patternMatchingSwitch(null); + VehicleType vehicle1 = new Boat(); + VehicleType vehicle2 = new Train(); + VehicleType vehicle3 = new Auto(4); // assuming Auto has a constructor that sets numDoors + VehicleType vehicle4 = new Auto(2); + + patternMatchingSwitch(vehicle1); // Output: Boat toString() result + patternMatchingSwitch(vehicle2); // Output: Train toString() result + patternMatchingSwitch(vehicle3); // Output: Saloon/Sedan: onRoad() result + patternMatchingSwitch(vehicle4); // Output: Convertible: onRoad() result + patternMatchingSwitch(null); // Output: Invalid type + } +} + +interface VehicleType { + // common methods for all vehicle types +} + +class Boat implements VehicleType { + @Override + public String toString() { + return "Boat"; } } +class Train implements VehicleType { + @Override + public String toString() { + return "Train"; + } +} + +class Auto implements VehicleType { + private final int numDoors; + + public Auto(int numDoors) { + this.numDoors = numDoors; + } + + public int getNumDoors() { + return numDoors; + } + + public String onRoad() { + return "on the road"; + } + + @Override + public String toString() { + return "Auto with " + numDoors + " doors"; + } +} + + + + + /* package java21.pattern_matching_for_switch;