From 6dc4eab5bd2b7c3542a52b5515423c2cc5d7dbc9 Mon Sep 17 00:00:00 2001 From: angiejones Date: Sat, 20 Apr 2019 19:25:18 -0700 Subject: [PATCH] initial checkin --- chapter10/Animal.java | 8 ++ chapter10/Cat.java | 14 +++ chapter10/Dog.java | 13 +++ chapter10/Zoo.java | 32 ++++++ chapter11/Book.java | 65 +++++++++++ chapter11/Customer.java | 10 ++ chapter11/Product.java | 17 +++ chapter11/Rectangle.java | 33 ++++++ chapter11/Shape.java | 10 ++ chapter11/ShapeTester.java | 11 ++ chapter12/CollectionsDemo.java | 96 +++++++++++++++++ chapter13/ExceptionHandling.java | 50 +++++++++ chapter2/GrossPayCalculator.java | 26 +++++ chapter3/GradeMessage.java | 45 ++++++++ chapter3/LoanQualifier.java | 45 ++++++++ chapter3/LogicalOperatorLoanQualifier.java | 38 +++++++ chapter3/QuotaCalculator.java | 33 ++++++ chapter3/SalaryCalculator.java | 35 ++++++ chapter3/TestResults.java | 40 +++++++ chapter4/AddNumbers.java | 42 ++++++++ chapter4/AverageTestScores.java | 35 ++++++ chapter4/Cashier.java | 35 ++++++ chapter4/GrossPayInputValidation.java | 39 +++++++ chapter4/LetterSearch.java | 37 +++++++ chapter5/Greetings.java | 23 ++++ chapter5/InstantCreditCheck.java | 61 +++++++++++ chapter6/HomeAreaCalculator.java | 33 ++++++ chapter6/HomeAreaCalculatorRedo.java | 38 +++++++ chapter6/Month.java | 41 +++++++ chapter6/MonthConverter.java | 9 ++ chapter6/Rectangle.java | 41 +++++++ chapter7/Grades.java | 68 ++++++++++++ chapter7/LotteryTicket.java | 84 +++++++++++++++ chapter8/TextProcessor.java | 57 ++++++++++ chapter9/Employee.java | 27 +++++ chapter9/InheritanceTester.java | 38 +++++++ chapter9/Mother.java | 5 + chapter9/Person.java | 33 ++++++ chapter9/Rectangle.java | 40 +++++++ chapter9/Square.java | 13 +++ chapter9/Woman.java | 8 ++ exercises/chapter10/Apple.java | 17 +++ exercises/chapter10/Banana.java | 17 +++ exercises/chapter10/Fruit.java | 18 ++++ exercises/chapter10/Market.java | 31 ++++++ exercises/chapter11/Animal.java | 10 ++ exercises/chapter11/Duck.java | 9 ++ exercises/chapter11/Farm.java | 15 +++ exercises/chapter11/Pig.java | 9 ++ exercises/chapter12/GradeBook.java | 31 ++++++ exercises/chapter12/TestResults.java | 41 +++++++ exercises/chapter13/DivideByZero.java | 15 +++ exercises/chapter2/MadLibs.java | 26 +++++ exercises/chapter3/ChangeForADollarGame.java | 52 +++++++++ exercises/chapter4/RollTheDieGame.java | 44 ++++++++ exercises/chapter5/PhoneBillCalculator.java | 44 ++++++++ exercises/chapter6/PhoneBill.java | 88 +++++++++++++++ exercises/chapter6/PhoneBillCalculator.java | 10 ++ exercises/chapter7/DayOfTheWeek.java | 17 +++ exercises/chapter8/PasswordValidator.java | 107 +++++++++++++++++++ exercises/chapter9/BirthdayCake.java | 18 ++++ exercises/chapter9/Cake.java | 28 +++++ exercises/chapter9/TasteTester.java | 22 ++++ exercises/chapter9/WeddingCake.java | 18 ++++ exercises/project/Coin.java | 29 +++++ exercises/project/CoinTossGame.java | 61 +++++++++++ exercises/project/Player.java | 27 +++++ 67 files changed, 2232 insertions(+) create mode 100644 chapter10/Animal.java create mode 100644 chapter10/Cat.java create mode 100644 chapter10/Dog.java create mode 100644 chapter10/Zoo.java create mode 100644 chapter11/Book.java create mode 100644 chapter11/Customer.java create mode 100644 chapter11/Product.java create mode 100644 chapter11/Rectangle.java create mode 100644 chapter11/Shape.java create mode 100644 chapter11/ShapeTester.java create mode 100644 chapter12/CollectionsDemo.java create mode 100644 chapter13/ExceptionHandling.java create mode 100644 chapter2/GrossPayCalculator.java create mode 100644 chapter3/GradeMessage.java create mode 100644 chapter3/LoanQualifier.java create mode 100644 chapter3/LogicalOperatorLoanQualifier.java create mode 100644 chapter3/QuotaCalculator.java create mode 100644 chapter3/SalaryCalculator.java create mode 100644 chapter3/TestResults.java create mode 100644 chapter4/AddNumbers.java create mode 100644 chapter4/AverageTestScores.java create mode 100644 chapter4/Cashier.java create mode 100644 chapter4/GrossPayInputValidation.java create mode 100644 chapter4/LetterSearch.java create mode 100644 chapter5/Greetings.java create mode 100644 chapter5/InstantCreditCheck.java create mode 100644 chapter6/HomeAreaCalculator.java create mode 100644 chapter6/HomeAreaCalculatorRedo.java create mode 100644 chapter6/Month.java create mode 100644 chapter6/MonthConverter.java create mode 100644 chapter6/Rectangle.java create mode 100644 chapter7/Grades.java create mode 100644 chapter7/LotteryTicket.java create mode 100644 chapter8/TextProcessor.java create mode 100644 chapter9/Employee.java create mode 100644 chapter9/InheritanceTester.java create mode 100644 chapter9/Mother.java create mode 100644 chapter9/Person.java create mode 100644 chapter9/Rectangle.java create mode 100644 chapter9/Square.java create mode 100644 chapter9/Woman.java create mode 100644 exercises/chapter10/Apple.java create mode 100644 exercises/chapter10/Banana.java create mode 100644 exercises/chapter10/Fruit.java create mode 100644 exercises/chapter10/Market.java create mode 100644 exercises/chapter11/Animal.java create mode 100644 exercises/chapter11/Duck.java create mode 100644 exercises/chapter11/Farm.java create mode 100644 exercises/chapter11/Pig.java create mode 100644 exercises/chapter12/GradeBook.java create mode 100644 exercises/chapter12/TestResults.java create mode 100644 exercises/chapter13/DivideByZero.java create mode 100644 exercises/chapter2/MadLibs.java create mode 100644 exercises/chapter3/ChangeForADollarGame.java create mode 100644 exercises/chapter4/RollTheDieGame.java create mode 100644 exercises/chapter5/PhoneBillCalculator.java create mode 100644 exercises/chapter6/PhoneBill.java create mode 100644 exercises/chapter6/PhoneBillCalculator.java create mode 100644 exercises/chapter7/DayOfTheWeek.java create mode 100644 exercises/chapter8/PasswordValidator.java create mode 100644 exercises/chapter9/BirthdayCake.java create mode 100644 exercises/chapter9/Cake.java create mode 100644 exercises/chapter9/TasteTester.java create mode 100644 exercises/chapter9/WeddingCake.java create mode 100644 exercises/project/Coin.java create mode 100644 exercises/project/CoinTossGame.java create mode 100644 exercises/project/Player.java diff --git a/chapter10/Animal.java b/chapter10/Animal.java new file mode 100644 index 0000000..b0eac4a --- /dev/null +++ b/chapter10/Animal.java @@ -0,0 +1,8 @@ +package chapter10; + +public class Animal { + + public void makeSound(){ + System.out.println("unknown animal sound"); + } +} diff --git a/chapter10/Cat.java b/chapter10/Cat.java new file mode 100644 index 0000000..35067b4 --- /dev/null +++ b/chapter10/Cat.java @@ -0,0 +1,14 @@ +package chapter10; + +public class Cat extends Animal { + + @Override + public void makeSound(){ + System.out.println("meow"); + } + + public void scratch(){ + System.out.println("I am a cat. I scratch things."); + } + +} diff --git a/chapter10/Dog.java b/chapter10/Dog.java new file mode 100644 index 0000000..a2087e1 --- /dev/null +++ b/chapter10/Dog.java @@ -0,0 +1,13 @@ +package chapter10; + +public class Dog extends Animal { + + @Override + public void makeSound(){ + System.out.println("woof"); + } + + public void fetch(){ + System.out.println("fetch is fun!"); + } +} diff --git a/chapter10/Zoo.java b/chapter10/Zoo.java new file mode 100644 index 0000000..ac81993 --- /dev/null +++ b/chapter10/Zoo.java @@ -0,0 +1,32 @@ +package chapter10; + +public class Zoo { + + public static void main(String[] args){ + + Dog rocky = new Dog(); + rocky.fetch(); + rocky.makeSound(); + feed(rocky); + + Animal sasha = new Dog(); + sasha.makeSound(); + feed(sasha); + + sasha = new Cat(); + sasha.makeSound(); + ((Cat) sasha).scratch(); + feed(sasha); + } + + public static void feed(Animal animal){ + + if(animal instanceof Dog){ + System.out.println("here's your dog food"); + } + + else if(animal instanceof Cat){ + System.out.println("here's your cat food"); + } + } +} diff --git a/chapter11/Book.java b/chapter11/Book.java new file mode 100644 index 0000000..1c07cd9 --- /dev/null +++ b/chapter11/Book.java @@ -0,0 +1,65 @@ +package chapter11; + +public class Book implements Product { + + private double price; + private String name; + private String color; + private String author; + private int pages; + private String isbn; + + @Override + public double getPrice() { + return price; + } + + @Override + public void setPrice(double price) { + this.price = price; + } + + @Override + public String getName() { + return name; + } + + @Override + public void setName(String name) { + this.name = name; + } + + @Override + public String getColor() { + return color; + } + + @Override + public void setColor(String color) { + this.color = color; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + public int getPages() { + return pages; + } + + public void setPages(int pages) { + this.pages = pages; + } + + public String getIsbn() { + return isbn; + } + + public void setIsbn(String isbn) { + this.isbn = isbn; + } +} diff --git a/chapter11/Customer.java b/chapter11/Customer.java new file mode 100644 index 0000000..ccf9b43 --- /dev/null +++ b/chapter11/Customer.java @@ -0,0 +1,10 @@ +package chapter11; + +public class Customer { + + public static void main(String[] args){ + + Product book = new Book(); + book.setPrice(9.99); + } +} diff --git a/chapter11/Product.java b/chapter11/Product.java new file mode 100644 index 0000000..4f76a3b --- /dev/null +++ b/chapter11/Product.java @@ -0,0 +1,17 @@ +package chapter11; + +public interface Product { + + double getPrice(); + void setPrice(double price); + + String getName(); + void setName(String name); + + String getColor(); + void setColor(String color); + + default String getBarcode(){ + return "no barcode"; + } +} diff --git a/chapter11/Rectangle.java b/chapter11/Rectangle.java new file mode 100644 index 0000000..09c16e8 --- /dev/null +++ b/chapter11/Rectangle.java @@ -0,0 +1,33 @@ +package chapter11; + +public class Rectangle extends Shape { + + private double length; + private double width; + + public double getLength() { + return length; + } + + public void setLength(double length) { + this.length = length; + } + + public double getWidth() { + return width; + } + + public void setWidth(double width) { + this.width = width; + } + + public Rectangle(double length, double width){ + setLength(length); + setWidth(width); + } + + @Override + double calculateArea() { + return length * width; + } +} diff --git a/chapter11/Shape.java b/chapter11/Shape.java new file mode 100644 index 0000000..1ff8fd0 --- /dev/null +++ b/chapter11/Shape.java @@ -0,0 +1,10 @@ +package chapter11; + +public abstract class Shape { + + abstract double calculateArea(); + + public void print(){ + System.out.println("I am a shape"); + } +} diff --git a/chapter11/ShapeTester.java b/chapter11/ShapeTester.java new file mode 100644 index 0000000..5f659c4 --- /dev/null +++ b/chapter11/ShapeTester.java @@ -0,0 +1,11 @@ +package chapter11; + +public class ShapeTester { + + public static void main(String[] args){ + + Shape rectangle = new Rectangle(5, 7); + rectangle.print(); + System.out.println(rectangle.calculateArea()); + } +} diff --git a/chapter12/CollectionsDemo.java b/chapter12/CollectionsDemo.java new file mode 100644 index 0000000..dac517d --- /dev/null +++ b/chapter12/CollectionsDemo.java @@ -0,0 +1,96 @@ +package chapter12; + +import java.util.*; + +public class CollectionsDemo { + + public static void main(String[] args){ + setDemo(); + listDemo(); + queueDemo(); + mapDemo(); + } + + public static void setDemo(){ + Set fruit = new HashSet(); + fruit.add("apple"); + fruit.add("lemon"); + fruit.add("banana"); + fruit.add("orange"); + fruit.add("lemon"); + + System.out.println(fruit.size()); //4 + System.out.println(fruit); //[banana, orange, apple, lemon] + } + + public static void listDemo(){ + List fruit = new ArrayList(); + fruit.add("apple"); + fruit.add("lemon"); + fruit.add("banana"); + fruit.add("orange"); + fruit.add("lemon"); + + System.out.println(fruit.get(2)); //banana + System.out.println(fruit.size()); //5 + System.out.println(fruit); //[apple, lemon, banana, orange, lemon] + } + + public static void queueDemo(){ + Queue fruit = new LinkedList(); + fruit.add("apple"); + fruit.add("lemon"); + fruit.add("banana"); + fruit.add("orange"); + fruit.add("lemon"); + + System.out.println(fruit.size()); //5 + System.out.println(fruit); //[apple, lemon, banana, orange, lemon] + + fruit.remove(); + System.out.println(fruit);//[lemon, banana, orange, lemon] + + System.out.println(fruit.peek());//lemon + } + + public static void mapDemo(){ + Map fruitCalories = new HashMap(); + fruitCalories.put("apple", 95); + fruitCalories.put("lemon", 20); + fruitCalories.put("banana", 105); + fruitCalories.put("orange", 45); + fruitCalories.put("lemon", 17); + + System.out.println(fruitCalories.size()); //4 + System.out.println(fruitCalories); //{banana=105, orange=45, apple=95, lemon=17} + + System.out.println(fruitCalories.get("lemon"));//17 + + System.out.println(fruitCalories.entrySet());//[banana=105, orange=45, apple=95, lemon=17] + + fruitCalories.remove("orange"); + System.out.println(fruitCalories);//{banana=105, apple=95, lemon=17} + } + + public void print(Collection collection){ + var i = collection.iterator(); + while(i.hasNext()){ + System.out.println(i.next()); + } + + for(String item : collection){ + System.out.println(item); + } + + collection.forEach(System.out::println); + } + + public void print(Map map){ + for(var entry : map.entrySet()){ + System.out.println(entry.getValue()); + } + + map.forEach( + (k,v)->System.out.println("Fruit: " + k + ", Calories: " + v)); + } +} diff --git a/chapter13/ExceptionHandling.java b/chapter13/ExceptionHandling.java new file mode 100644 index 0000000..4bd5ffe --- /dev/null +++ b/chapter13/ExceptionHandling.java @@ -0,0 +1,50 @@ +package chapter13; + + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.InputMismatchException; +import java.util.Scanner; + +public class ExceptionHandling { + + public static void main(String args[]){ + createNewFile(); + numbersExceptionHandling(); + } + + public static void createNewFile(){ + File file = new File("resources/nonexistent.txt"); + try{ + file.createNewFile(); + }catch (Exception e){ + System.out.println("Directory does not exist."); + e.printStackTrace(); + } + } + + public static void createNewFileRethrow() throws IOException{ + File file = new File("resources/nonexistent.txt"); + file.createNewFile(); + } + + public static void numbersExceptionHandling(){ + File file = new File("resources/numbers.txt"); + Scanner fileReader = null; + try{ + fileReader = new Scanner(file); + + while(fileReader.hasNext()){ + double num = fileReader.nextDouble(); + System.out.println(num); + } + + + }catch(FileNotFoundException | InputMismatchException e){ + e.printStackTrace(); + }finally{ + fileReader.close(); + } + } +} diff --git a/chapter2/GrossPayCalculator.java b/chapter2/GrossPayCalculator.java new file mode 100644 index 0000000..0b7b373 --- /dev/null +++ b/chapter2/GrossPayCalculator.java @@ -0,0 +1,26 @@ +package chapter2; + +import java.util.Scanner; + +public class GrossPayCalculator { + + public static void main(String arg[]){ + + //1. Get the number of hours worked + System.out.println("Enter the number of hours the employee worked."); + Scanner scanner = new Scanner(System.in); + int hours = scanner.nextInt(); + + //2. Get the hourly pay rate + System.out.println("Enter the employee's pay rate."); + double rate = scanner.nextDouble(); + scanner.close(); + + //3. Multiply hours and pay rate + double grossPay = hours * rate; + + //4. Display result + System.out.println("The employee's gross pay is $" + grossPay); + } + +} diff --git a/chapter3/GradeMessage.java b/chapter3/GradeMessage.java new file mode 100644 index 0000000..e95dcc8 --- /dev/null +++ b/chapter3/GradeMessage.java @@ -0,0 +1,45 @@ +package chapter3; + +import java.util.Scanner; + +/* + * SWITCH + * Have a user enter their letter grade, and using a switch statement, + * print out a message letting them know how they did. + */ +public class GradeMessage { + + public static void main(String args[]){ + + System.out.println("Enter your letter grade:"); + Scanner scanner = new Scanner(System.in); + String grade = scanner.next(); + scanner.close(); + + String message; + + switch(grade){ + case "A": + message = "Excellent job!"; + break; + case "B": + message = "Great job!"; + break; + case "C": + message = "Good job!"; + break; + case "D": + message = "You need to work a bit harder"; + break; + case "F": + message = "Uh oh!"; + break; + default: + message = "Error. Invalid grade"; + break; + } + + System.out.println(message); + + } +} diff --git a/chapter3/LoanQualifier.java b/chapter3/LoanQualifier.java new file mode 100644 index 0000000..30e1c45 --- /dev/null +++ b/chapter3/LoanQualifier.java @@ -0,0 +1,45 @@ +package chapter3; + + +import java.util.Scanner; + +/* + * NESTED IFS: + * To qualify for a loan, a person must make at least $30,000 + * and have been working at their current job for at least 2 years. + */ +public class LoanQualifier { + + public static void main(String args[]){ + + //Initialize what we know + int requiredSalary = 30000; + int requiredYearsEmployed = 2; + + //Get what we don't + System.out.println("Enter your salary:"); + Scanner scanner = new Scanner(System.in); + double salary = scanner.nextDouble(); + + System.out.println("Enter the number of years with your current employer:"); + double years = scanner.nextDouble(); + + scanner.close(); + + //Make decision + if(salary >= requiredSalary){ + if(years >= requiredYearsEmployed){ + System.out.println("Congrats! You qualify for the loan"); + } + else{ + System.out.println("Sorry, you must have worked at your current job " + + requiredYearsEmployed + " years."); + } + } + else{ + System.out.println("Sorry, you must earn at least $" + + requiredSalary + " to qualify for the loan"); + } + + } +} diff --git a/chapter3/LogicalOperatorLoanQualifier.java b/chapter3/LogicalOperatorLoanQualifier.java new file mode 100644 index 0000000..f2e9d41 --- /dev/null +++ b/chapter3/LogicalOperatorLoanQualifier.java @@ -0,0 +1,38 @@ +package chapter3; + + +import java.util.Scanner; + +/* + * LOGICAL OPERATORS: + * To qualify for a loan, a person must make at least $30,000 + * and have been working at their current job for at least 2 years. + */ +public class LogicalOperatorLoanQualifier { + + public static void main(String args[]){ + + //Initialize what we know + int requiredSalary = 30000; + int requiredYearsEmployed = 2; + + //Get what we don't + System.out.println("Enter your salary:"); + Scanner scanner = new Scanner(System.in); + double salary = scanner.nextDouble(); + + System.out.println("Enter the number of years with your current employer:"); + double years = scanner.nextDouble(); + + scanner.close(); + + //Make decision + if(salary >= requiredSalary && years >= requiredYearsEmployed){ + System.out.println("Congrats! You qualify for the loan"); + } + else{ + System.out.println("Sorry, you must earn at least $" + + requiredSalary + " to qualify for the loan"); + } + } +} diff --git a/chapter3/QuotaCalculator.java b/chapter3/QuotaCalculator.java new file mode 100644 index 0000000..245801e --- /dev/null +++ b/chapter3/QuotaCalculator.java @@ -0,0 +1,33 @@ +package chapter3; + +import java.util.Scanner; + +/* + * IF ELSE + * All salespeople are expected to make at least 10 sales each week. + * For those who do, they receive a congratulatory message. + * For those who don’t, they are informed of how many sales they were short. + */ +public class QuotaCalculator { + + public static void main(String args[]){ + + //Initialize values we know + int quota = 10; + + //Get unknown values + System.out.println("Enter the number of sales you made this week:"); + Scanner scanner = new Scanner(System.in); + int sales = scanner.nextInt(); + scanner.close(); + + //Make a decision on the path to take - Output + if(sales >= quota){ + System.out.println("Congrats! You've met your quota"); + } + else{ + int salesShort = quota - sales; + System.out.println("You did not make your quota. You were " + salesShort + " sales short"); + } + } +} diff --git a/chapter3/SalaryCalculator.java b/chapter3/SalaryCalculator.java new file mode 100644 index 0000000..acaca3d --- /dev/null +++ b/chapter3/SalaryCalculator.java @@ -0,0 +1,35 @@ +package chapter3; + +import java.util.Scanner; + +/* +IF Statement. +All salespeople get a payment of $1000 a week. +Salespeople who exceed 10 sales get an additional bonus of $250. + */ +public class SalaryCalculator { + + public static void main(String args[]){ + + //Initialize known values + int salary = 1000; + int bonus = 250; + int quota = 10; + + //Get values for the unknown + System.out.println("How many sales did the employee make this week?"); + Scanner scanner = new Scanner(System.in); + int sales = scanner.nextInt(); + scanner.close(); + + //Quick detour for the bonus earners + if(sales > quota){ + salary = salary + bonus; + } + + //Output + System.out.println("The employee's pay is $" + salary); + + } + +} diff --git a/chapter3/TestResults.java b/chapter3/TestResults.java new file mode 100644 index 0000000..14d72bc --- /dev/null +++ b/chapter3/TestResults.java @@ -0,0 +1,40 @@ +package chapter3; + +import java.util.Scanner; + +/* + * IF-ELSE-IF + * Display the letter grade for a student based on their test score. + */ +public class TestResults { + + public static void main(String args[]){ + + //Get the test score + System.out.println("Enter your test score:"); + Scanner scanner = new Scanner(System.in); + double score = scanner.nextDouble(); + scanner.close(); + + //Determine the letter grade + char grade; + + if(score < 60){ + grade = 'F'; + } + else if(score < 70){ + grade = 'D'; + } + else if(score < 80){ + grade = 'C'; + } + else if(score < 90){ + grade = 'B'; + } + else{ + grade = 'A'; + } + + System.out.println("Your grade is " + grade); + } +} diff --git a/chapter4/AddNumbers.java b/chapter4/AddNumbers.java new file mode 100644 index 0000000..6079761 --- /dev/null +++ b/chapter4/AddNumbers.java @@ -0,0 +1,42 @@ +package chapter4; + +import java.util.Scanner; + +/* + * DO WHILE LOOP: + * Write a program that allows a user to enter two numbers, + * and then sums up the two numbers. The user should be able to + * repeat this action until they indicate they are done. + */ +public class AddNumbers { + + public static void main(String args[]){ + + Scanner scanner = new Scanner(System.in); + + boolean again; + + do{ + System.out.println("Enter the first number"); + double num1 = scanner.nextDouble(); + + System.out.println("Enter the second number"); + double num2 = scanner.nextDouble(); + + double sum = num1 + num2; + + System.out.println("The sum is " + sum); + + System.out.println("Would you like to start over? True or False"); + again = scanner.nextBoolean(); + + } while(again); + + scanner.close(); + } + + public static int calculateSum(int number1, int number2){ + int sum = number1 + number2; + return sum; + } +} diff --git a/chapter4/AverageTestScores.java b/chapter4/AverageTestScores.java new file mode 100644 index 0000000..9b87e39 --- /dev/null +++ b/chapter4/AverageTestScores.java @@ -0,0 +1,35 @@ +package chapter4; + +import java.util.Scanner; + +/* + * NESTED LOOPS: + * Find the average of each student's test scores + */ +public class AverageTestScores { + + public static void main(String args[]){ + + //Initialize what we know + int numberOfStudents = 24; + int numberOfTests = 4; + + Scanner scanner = new Scanner(System.in); + + //Process all students + for(int i=0; i< numberOfStudents; i++){ + + double total = 0; + for(int j=0; j maxHours || hoursWorked < 1){ + System.out.println("Invalid entry. Yours hours must be between 1 and 40. Try again."); + hoursWorked = scanner.nextDouble(); + } + + scanner.close(); + + //Calculate gross + double gross = rate * hoursWorked; + System.out.println("Gross pay: $" + gross); + + + + } +} diff --git a/chapter4/LetterSearch.java b/chapter4/LetterSearch.java new file mode 100644 index 0000000..c339d51 --- /dev/null +++ b/chapter4/LetterSearch.java @@ -0,0 +1,37 @@ +package chapter4; + +import java.util.Scanner; + +/* + * LOOP BREAK + * Search a String to determine if it contains the letter ‘A’. + */ +public class LetterSearch { + + public static void main(String args[]){ + + //Get text + System.out.println("Enter some text:"); + Scanner scanner = new Scanner(System.in); + String text = scanner.next(); + scanner.close(); + + boolean letterFound = false; + + //Search text for letter A + for(int i=0; i= requiredCreditScore && salary >= requiredSalary){ + return true; + } + else{ + return false; + } + } + + public static void notifyUser(boolean isQualified){ + if(isQualified){ + System.out.println("Congrats! You've been approved."); + } + else{ + System.out.println("Sorry. You've been declined"); + } + } +} diff --git a/chapter6/HomeAreaCalculator.java b/chapter6/HomeAreaCalculator.java new file mode 100644 index 0000000..aeb511c --- /dev/null +++ b/chapter6/HomeAreaCalculator.java @@ -0,0 +1,33 @@ +package chapter6; + +/* + * Write a class that creates instances of the Rectangle class to find the + * total area of two rooms in a house. + */ +public class HomeAreaCalculator { + + public static void main(String args[]){ + + /******************* + * RECTANGLE 1 + ********************/ + + //Create instance of Rectangle class + Rectangle room1 = new Rectangle(); + room1.setWidth(25); + room1.setLength(50); + double areaOfRoom1 = room1.calculateArea(); + + /******************* + * RECTANGLE 2 + ********************/ + + //Create instance of Rectangle class + Rectangle room2 = new Rectangle(30, 75); + double areaOfRoom2 = room2.calculateArea(); + + double totalArea = areaOfRoom1 + areaOfRoom2; + + System.out.println("Area of both rooms: " + totalArea); + } +} diff --git a/chapter6/HomeAreaCalculatorRedo.java b/chapter6/HomeAreaCalculatorRedo.java new file mode 100644 index 0000000..d210230 --- /dev/null +++ b/chapter6/HomeAreaCalculatorRedo.java @@ -0,0 +1,38 @@ +package chapter6; + +import java.util.Scanner; + +public class HomeAreaCalculatorRedo { + + private Scanner scanner = new Scanner(System.in); + + public static void main(String args[]){ + + HomeAreaCalculatorRedo calculator = new HomeAreaCalculatorRedo(); + Rectangle kitchen = calculator.getRoom(); + Rectangle bathroom = calculator.getRoom(); + + double area = calculator.calculateTotalArea(kitchen, bathroom); + + System.out.println("The total area is: " + area); + + calculator.scanner.close(); + + } + + public Rectangle getRoom(){ + + System.out.println("Enter the length of your room:"); + double length = scanner.nextDouble(); + + System.out.println("Enter the width of your room:"); + double width = scanner.nextDouble(); + + return new Rectangle(length, width); + } + + public double calculateTotalArea(Rectangle rectangle1, Rectangle rectangle2){ + return rectangle1.calculateArea() + rectangle2.calculateArea(); + } + +} diff --git a/chapter6/Month.java b/chapter6/Month.java new file mode 100644 index 0000000..4e15255 --- /dev/null +++ b/chapter6/Month.java @@ -0,0 +1,41 @@ +package chapter6; + +public class Month { + + public static String getMonth(int month){ + switch(month){ + case 1: return "January"; + case 2: return "February"; + case 3: return "March"; + case 4: return "April"; + case 5: return "May"; + case 6: return "June"; + case 7: return "July"; + case 8: return "August"; + case 9: return "September"; + case 10: return "October"; + case 11: return "November"; + case 12: return "December"; + default: return "Invalid month. Please enter a value between 1 and 12."; + } + } + + public static int getMonth(String month){ + switch(month){ + case "January": return 1; + case "February": return 2; + case "March": return 3; + case "April": return 4; + case "May": return 5; + case "June": return 6; + case "July": return 7; + case "August": return 8; + case "September": return 9; + case "October": return 10; + case "November": return 11; + case "December": return 12; + default: return -1; + } + } + +} diff --git a/chapter6/MonthConverter.java b/chapter6/MonthConverter.java new file mode 100644 index 0000000..f6e1e17 --- /dev/null +++ b/chapter6/MonthConverter.java @@ -0,0 +1,9 @@ +package chapter6; + +public class MonthConverter { + + public static void main(String args[]){ + System.out.println(Month.getMonth(2)); + System.out.println(Month.getMonth("January")); + } +} diff --git a/chapter6/Rectangle.java b/chapter6/Rectangle.java new file mode 100644 index 0000000..633b421 --- /dev/null +++ b/chapter6/Rectangle.java @@ -0,0 +1,41 @@ +package chapter6; + +public class Rectangle { + + private double length; + private double width; + + public Rectangle(){ + length = 0; + width = 0; + } + + public Rectangle(double length, double width){ + this.length = length; //can be set this way + setWidth(width); //or can be set this way. these are only different here to demo alternative options + } + + public double getLength(){ + return length; + } + + public void setLength(double length){ + this.length = length; + } + + public double getWidth(){ + return width; + } + + public void setWidth(double width){ + this.width = width; + } + + public double calculatePerimeter(){ + return (2 * length) + (2 * width); + } + + public double calculateArea(){ + return length * width; + } +} diff --git a/chapter7/Grades.java b/chapter7/Grades.java new file mode 100644 index 0000000..53c0bc3 --- /dev/null +++ b/chapter7/Grades.java @@ -0,0 +1,68 @@ +package chapter7; + + +import java.util.Scanner; + +/* + * Create a program that allows a user to enter any + * number of grades and provides them with their + * average score, as well as the highest and lowest scores. + */ +public class Grades { + + private static int grades[]; + private static Scanner scanner = new Scanner(System.in); + + public static void main(String[] args){ + + System.out.println("How many grades would you like to enter?"); + grades = new int[scanner.nextInt()]; + + getGrades(); + + System.out.println("Average: " + String.format("%.2f", calculateAverage())); + System.out.println("Highest: " + getHighest()); + System.out.println("Lowest: " + getLowest()); + + } + + public static void getGrades(){ + for(int i=0; i highest){ + highest = grade; + } + } + return highest; + } + + public static int getLowest(){ + int lowest = grades[0]; + for(int grade: grades){ + if(grade < lowest){ + lowest = grade; + } + } + return lowest; + } + +} diff --git a/chapter7/LotteryTicket.java b/chapter7/LotteryTicket.java new file mode 100644 index 0000000..b702177 --- /dev/null +++ b/chapter7/LotteryTicket.java @@ -0,0 +1,84 @@ +package chapter7; + +import java.util.Arrays; +import java.util.Random; + +public class LotteryTicket { + + private static final int LENGTH = 6; + private static final int MAX_TICKET_NUMBER = 69; + + public static void main(String[] args){ + + int[] ticket = generateNumbers(); + Arrays.sort(ticket); + printTicket(ticket); + } + + public static int[] generateNumbers(){ + + int[] ticket = new int[LENGTH]; + + Random random = new Random(); + + for(int i=0; i< LENGTH; i++){ + int randomNumber; + + /* + Generate random number then search to make sure it doesn't + already exist in the array. If it does, regenerate and search again. + */ + do{ + randomNumber = random.nextInt(MAX_TICKET_NUMBER) + 1; + }while(search(ticket, randomNumber)); + + //Number is unique if we get here. Add it to the array. + ticket[i] = randomNumber; + } + + return ticket; + } + + /** + * Does a sequential search on the array to find a value + * @param array Array to search through + * @param numberToSearchFor Value to search for + * @return true if found, false if not + */ + public static boolean search(int[] array, int numberToSearchFor){ + + /*This is called an enhanced loop. + It iterates through 'array' and + each time assigns the current element to 'value' + */ + for(int value : array){ + if(value == numberToSearchFor){ + return true; + } + } + + /*If we've reached this point, then the entire array was searched + and the value was not found + */ + return false; + } + + public static boolean binarySearch(int[] array, int numberToSearchFor){ + + //Array must be sorted first + Arrays.sort(array); + + int index = Arrays.binarySearch(array, numberToSearchFor); + if(index >= 0){ + return true; + } + else return false; + + } + + public static void printTicket(int ticket[]){ + for(int i=0; i=0; i--){ + System.out.print(text.charAt(i)); + } + } + + + /** + * Adds spaces before each uppercase letter + * @param text jumbled text + */ + public static void addSpaces(String text){ + + var modifiedText = new StringBuilder(text); + + for(int i=0; i< modifiedText.length(); i++){ + if(i!=0 && Character.isUpperCase(modifiedText.charAt(i))){ + modifiedText.insert(i, " "); + i++; + } + } + + System.out.println(modifiedText); + } +} diff --git a/chapter9/Employee.java b/chapter9/Employee.java new file mode 100644 index 0000000..576f921 --- /dev/null +++ b/chapter9/Employee.java @@ -0,0 +1,27 @@ +package chapter9; + +public class Employee extends Person { + + private String employeeId; + private String title; + + public Employee(){ + System.out.println("In Employee default constructor"); + } + + public String getEmployeeId() { + return employeeId; + } + + public void setEmployeeId(String employeeId) { + this.employeeId = employeeId; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } +} diff --git a/chapter9/InheritanceTester.java b/chapter9/InheritanceTester.java new file mode 100644 index 0000000..b3bef44 --- /dev/null +++ b/chapter9/InheritanceTester.java @@ -0,0 +1,38 @@ +package chapter9; + +public class InheritanceTester { + + public static void main(String[] args){ + + Mother mom = new Mother(); + mom.setName("Glenda"); + + System.out.println(mom.getName() + " is a " + mom.getGender()); + + } + + public static void testSquareOverride(){ + Rectangle rectangle = new Rectangle(); + rectangle.setLength(4); + rectangle.setWidth(8); + System.out.println(rectangle.calculatePerimeter()); + + Square square = new Square(); + square.setLength(4); + square.setWidth(8); + System.out.println(square.calculatePerimeter()); + } + + public static void testInheritance(){ + Employee employee = new Employee(); + employee.setName("Angie"); + } + + public static void testOverload(){ + Rectangle rectangle = new Rectangle(); + rectangle.print(); + + Square square = new Square(); + square.print("square"); + } +} diff --git a/chapter9/Mother.java b/chapter9/Mother.java new file mode 100644 index 0000000..71a6592 --- /dev/null +++ b/chapter9/Mother.java @@ -0,0 +1,5 @@ +package chapter9; + +public class Mother extends Woman { + +} diff --git a/chapter9/Person.java b/chapter9/Person.java new file mode 100644 index 0000000..ca3954b --- /dev/null +++ b/chapter9/Person.java @@ -0,0 +1,33 @@ +package chapter9; + +public class Person { + + private String name; + private int age; + private String gender; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public String getGender() { + return gender; + } + + public void setGender(String gender) { + this.gender = gender; + } + +} diff --git a/chapter9/Rectangle.java b/chapter9/Rectangle.java new file mode 100644 index 0000000..043abbd --- /dev/null +++ b/chapter9/Rectangle.java @@ -0,0 +1,40 @@ +package chapter9; + +public class Rectangle { + + protected double length; + protected double width; + protected double sides = 4; + + public double getLength() { + return length; + } + + public void setLength(double length) { + this.length = length; + } + + public double getWidth() { + return width; + } + + public void setWidth(double width) { + this.width = width; + } + + public double getSides() { + return sides; + } + + public void setSides(double sides) { + this.sides = sides; + } + + public double calculatePerimeter(){ + return (2 * length) + (2 * width); + } + + public void print(){ + System.out.println("I am a rectangle"); + } +} diff --git a/chapter9/Square.java b/chapter9/Square.java new file mode 100644 index 0000000..ffbf6eb --- /dev/null +++ b/chapter9/Square.java @@ -0,0 +1,13 @@ +package chapter9; + +public class Square extends Rectangle { + + @Override + public double calculatePerimeter(){ + return sides * length; + } + + public void print(String what){ + System.out.println("I am a " + what); + } +} diff --git a/chapter9/Woman.java b/chapter9/Woman.java new file mode 100644 index 0000000..5b569f4 --- /dev/null +++ b/chapter9/Woman.java @@ -0,0 +1,8 @@ +package chapter9; + +public class Woman extends Person { + + public Woman(){ + setGender("female"); + } +} diff --git a/exercises/chapter10/Apple.java b/exercises/chapter10/Apple.java new file mode 100644 index 0000000..d9b6888 --- /dev/null +++ b/exercises/chapter10/Apple.java @@ -0,0 +1,17 @@ +package exercises.chapter10; + +public class Apple extends Fruit { + + public Apple(){ + setCalories(95); + } + + public void removeSeeds(){ + System.out.println("Apple seeds removed"); + } + + @Override + public void makeJuice() { + System.out.println("Apple juice is my favorite 🥃"); + } +} diff --git a/exercises/chapter10/Banana.java b/exercises/chapter10/Banana.java new file mode 100644 index 0000000..1bb8845 --- /dev/null +++ b/exercises/chapter10/Banana.java @@ -0,0 +1,17 @@ +package exercises.chapter10; + +public class Banana extends Fruit { + + public Banana(){ + setCalories(105); + } + + public void peel(){ + System.out.println("Banana has been peeled"); + } + + @Override + public void makeJuice() { + System.out.println("Banana juice is gross 🥴"); + } +} diff --git a/exercises/chapter10/Fruit.java b/exercises/chapter10/Fruit.java new file mode 100644 index 0000000..4f7247d --- /dev/null +++ b/exercises/chapter10/Fruit.java @@ -0,0 +1,18 @@ +package exercises.chapter10; + +public class Fruit { + + private int calories; + + public int getCalories() { + return calories; + } + + public void setCalories(int calories) { + this.calories = calories; + } + + public void makeJuice(){ + System.out.println("Juice is made"); + } +} diff --git a/exercises/chapter10/Market.java b/exercises/chapter10/Market.java new file mode 100644 index 0000000..628ca28 --- /dev/null +++ b/exercises/chapter10/Market.java @@ -0,0 +1,31 @@ +package exercises.chapter10; + +public class Market { + + public static void main(String[] args){ + Fruit apple = new Apple(); + ((Apple) apple).removeSeeds(); + + Apple apple2 = new Apple(); + apple2.removeSeeds(); + + Banana banana = new Banana(); + banana.peel(); + + Fruit banana2 = new Banana(); + ((Banana) banana2).peel(); + + Fruit orange = new Fruit(); + + squeeze(apple); + squeeze(banana); + squeeze(banana2); + squeeze(orange); + + } + + public static void squeeze(Fruit fruit){ + System.out.print("Squeezing..."); + fruit.makeJuice(); + } +} diff --git a/exercises/chapter11/Animal.java b/exercises/chapter11/Animal.java new file mode 100644 index 0000000..7556604 --- /dev/null +++ b/exercises/chapter11/Animal.java @@ -0,0 +1,10 @@ +package exercises.chapter11; + +public abstract class Animal { + + public abstract void makeSound(); + + public void eat(){ + System.out.println("I am eating"); + } +} diff --git a/exercises/chapter11/Duck.java b/exercises/chapter11/Duck.java new file mode 100644 index 0000000..7c82247 --- /dev/null +++ b/exercises/chapter11/Duck.java @@ -0,0 +1,9 @@ +package exercises.chapter11; + +public class Duck extends Animal { + + @Override + public void makeSound() { + System.out.println("quack quack"); + } +} diff --git a/exercises/chapter11/Farm.java b/exercises/chapter11/Farm.java new file mode 100644 index 0000000..db6bf64 --- /dev/null +++ b/exercises/chapter11/Farm.java @@ -0,0 +1,15 @@ +package exercises.chapter11; + +public class Farm { + + public static void main(String[] args){ + Animal donald = new Duck(); + donald.makeSound(); + + Duck daffy = new Duck(); + daffy.makeSound(); + + Pig porky = new Pig(); + porky.makeSound(); + } +} diff --git a/exercises/chapter11/Pig.java b/exercises/chapter11/Pig.java new file mode 100644 index 0000000..5644940 --- /dev/null +++ b/exercises/chapter11/Pig.java @@ -0,0 +1,9 @@ +package exercises.chapter11; + +public class Pig extends Animal { + + @Override + public void makeSound() { + System.out.println("oink oink"); + } +} diff --git a/exercises/chapter12/GradeBook.java b/exercises/chapter12/GradeBook.java new file mode 100644 index 0000000..a63db22 --- /dev/null +++ b/exercises/chapter12/GradeBook.java @@ -0,0 +1,31 @@ +package exercises.chapter12; + +import java.util.Map; + +public class GradeBook { + + public static void main(String[] args){ + Map gradeBook = TestResults.getOriginalGrades(); + Map test2 = TestResults.getMakeUpGrades(); + + for(var student : test2.entrySet()){ + Integer firstGrade = gradeBook.get(student.getKey()); + Integer secondGrade = test2.get(student.getKey()); + + if(secondGrade > firstGrade){ + gradeBook.put(student.getKey(), secondGrade); + } + } + + /* + The forEach is used here to demonstrate another approach to looping. + However, in reality, I would have added a print statement inside of + the loop above so that the program does not have to loop over this map + for a second time. This would be a more efficient approach: + System.out.println("Student: " + student.getKey() + ", Grade:" + gradeBook.get(student.getKey())); + */ + System.out.println("Final Grades:"); + gradeBook.forEach( + (k,v)->System.out.println("Student: " + k + ", Grade: " + v)); + } +} diff --git a/exercises/chapter12/TestResults.java b/exercises/chapter12/TestResults.java new file mode 100644 index 0000000..52b3f2a --- /dev/null +++ b/exercises/chapter12/TestResults.java @@ -0,0 +1,41 @@ +package exercises.chapter12; + +import java.util.HashMap; +import java.util.Map; + +public class TestResults { + + public static Map getOriginalGrades(){ + Map grades = new HashMap(); + grades.put("Angie", 24); + grades.put("Dave", 32); + grades.put("Lisi", 80); + grades.put("Raja", 50); + grades.put("Shashi", 79); + grades.put("Bas", 40); + grades.put("Carlos", 59); + grades.put("Amber", 55); + grades.put("Rex", 95); + grades.put("Jason", 63); + grades.put("Nikolay", 32); + + return grades; + } + + public static Map getMakeUpGrades(){ + Map grades = new HashMap(); + grades.put("Angie", 97); + grades.put("Dave", 82); + grades.put("Lisi", 76); + grades.put("Raja", 89); + grades.put("Shashi", 79); + grades.put("Bas", 98); + grades.put("Carlos", 80); + grades.put("Amber", 95); + grades.put("Rex", 90); + grades.put("Jason", 62); + grades.put("Nikolay", 79); + + return grades; + } +} diff --git a/exercises/chapter13/DivideByZero.java b/exercises/chapter13/DivideByZero.java new file mode 100644 index 0000000..4333265 --- /dev/null +++ b/exercises/chapter13/DivideByZero.java @@ -0,0 +1,15 @@ +package exercises.chapter13; + +public class DivideByZero { + + public static void main(String[] args){ + + try{ + int c = 30/0; + }catch(ArithmeticException e){ + System.out.println("Dividing by zero is not permitted"); + }finally{ + System.out.println("Division is fun!"); + } + } +} diff --git a/exercises/chapter2/MadLibs.java b/exercises/chapter2/MadLibs.java new file mode 100644 index 0000000..89260d5 --- /dev/null +++ b/exercises/chapter2/MadLibs.java @@ -0,0 +1,26 @@ +package exercises.chapter2; + +import java.util.Scanner; + +public class MadLibs { + + public static void main(String args[]){ + + Scanner scanner = new Scanner(System.in); + + System.out.println("Enter a season of the year:"); + String season = scanner.next(); + + System.out.println("Enter a whole number:"); + int number = scanner.nextInt(); + + System.out.println("Enter an adjective:"); + String adjective = scanner.next(); + + scanner.close(); + + System.out.println("On a " + adjective + " " + season + + " day, I drink a minimum of " + number + + " cups of coffee."); + } +} diff --git a/exercises/chapter3/ChangeForADollarGame.java b/exercises/chapter3/ChangeForADollarGame.java new file mode 100644 index 0000000..3d519a2 --- /dev/null +++ b/exercises/chapter3/ChangeForADollarGame.java @@ -0,0 +1,52 @@ +package exercises.chapter3; + +import java.util.Scanner; + +public class ChangeForADollarGame { + + public static void main(String args[]){ + + double penny = .01; + double nickel = .05; + double dime = .10; + double quarter = .25; + int dollar = 1; + + Scanner scanner = new Scanner(System.in); + + System.out.println("Welcome to 'Change for a Dollar'! " + + "Your goal is to enter enough change to make exactly $1.00"); + + System.out.println("Enter your number of pennies:"); + int numOfPennies = scanner.nextInt(); + + System.out.println("Enter your number of nickels:"); + int numOfNickels = scanner.nextInt(); + + System.out.println("Enter your number of dimes:"); + int numOfDimes = scanner.nextInt(); + + System.out.println("Enter your number of quarters:"); + int numOfQuarters = scanner.nextInt(); + + scanner.close(); + + double total = numOfPennies * penny + numOfNickels * nickel + numOfDimes * dime + numOfQuarters * quarter; + + if(total < dollar){ + double amountShort = dollar - total; + + //Way to make the decimal print with only 2 decimal places + System.out.println("Sorry, you lose! You were short " + String.format("%.2f", amountShort) + " cents."); + } + else if(total > dollar){ + double amountOver = total - dollar; + + //Way to make the decimal print with only 2 decimal places + System.out.println("Sorry, you lose! You were over " + String.format("%.2f", amountOver) + " cents."); + } + else{ + System.out.println("Yay! That's exactly $1.00! You win!"); + } + } +} diff --git a/exercises/chapter4/RollTheDieGame.java b/exercises/chapter4/RollTheDieGame.java new file mode 100644 index 0000000..3e48ded --- /dev/null +++ b/exercises/chapter4/RollTheDieGame.java @@ -0,0 +1,44 @@ +package exercises.chapter4; + +import java.util.Random; + +public class RollTheDieGame { + + public static void main(String args[]){ + int lastSpace = 20; + int currentSpace = 0; + int maxRolls = 5; + Random random = new Random(); + + System.out.println("Welcome to Roll the Die! Let's begin..."); + + for(int i=1; i<=maxRolls; i++){ + + int die = random.nextInt(6) + 1; + currentSpace = currentSpace + die; + + System.out.print(String.format("Roll #%d: You've rolled a %d. ", i, die)); + + if(currentSpace == lastSpace){ + System.out.print("You're on space " + currentSpace + ". Congrats, you win!"); + break; + } + else if(currentSpace > lastSpace){ + System.out.print("Unfortunately, that takes you past " + lastSpace + " spaces. You lose!"); + break; + } + else if(i==maxRolls && currentSpace < lastSpace){ + System.out.println("You're on space " + currentSpace + "."); + System.out.println("Unfortunately, you didn't make it to all " + + lastSpace + " spaces. You lose!"); + } + else{ + int spacesToGo = lastSpace - currentSpace; + System.out.print("You are now on space " + currentSpace + + " and have " + spacesToGo + " more to go."); + } + + System.out.println(); + } + } +} diff --git a/exercises/chapter5/PhoneBillCalculator.java b/exercises/chapter5/PhoneBillCalculator.java new file mode 100644 index 0000000..33f75c6 --- /dev/null +++ b/exercises/chapter5/PhoneBillCalculator.java @@ -0,0 +1,44 @@ +package exercises.chapter5; + +import java.util.Scanner; + +public class PhoneBillCalculator { + + public static void main(String args[]){ + + Scanner scanner = new Scanner(System.in); + + System.out.println("Enter base cost of the plan:"); + double baseCost = scanner.nextDouble(); + + System.out.println("Enter overage minutes:"); + double overageMinutes = scanner.nextDouble(); + + double overageCharge = calculateOverages(overageMinutes); + double tax = calculateTax(baseCost + overageCharge); + + calculateAndPrintBill(baseCost, overageCharge, tax); + } + + public static double calculateOverages(double extraMinutes){ + double rate = 0.25; + double overage = extraMinutes * rate; + return overage; + } + + public static double calculateTax(double subtotal){ + double rate = 0.15; + double tax = subtotal * rate; + return tax; + } + + public static void calculateAndPrintBill(double base, double overage, double tax){ + double finalTotal = base + overage + tax; + + System.out.println("Phone Bill Statement"); + System.out.println("Plan: $" + String.format("%.2f", base)); + System.out.println("Overage: $" + String.format("%.2f", overage)); + System.out.println("Tax: $" + String.format("%.2f", tax)); + System.out.println("Total: $" + String.format("%.2f", finalTotal)); + } +} diff --git a/exercises/chapter6/PhoneBill.java b/exercises/chapter6/PhoneBill.java new file mode 100644 index 0000000..069be6e --- /dev/null +++ b/exercises/chapter6/PhoneBill.java @@ -0,0 +1,88 @@ +package exercises.chapter6; + +public class PhoneBill { + + private int id; + private double baseCost; + private int allottedMinutes; + private int minutesUsed; + + public PhoneBill(){ + id = 0; + baseCost = 79.99; + allottedMinutes = 800; + minutesUsed = 800; + } + + public PhoneBill(int id){ + this.id = id; + baseCost = 79.99; + allottedMinutes = 800; + minutesUsed = 800; + } + + public PhoneBill(int id, double baseCost, int allottedMinutes, int minutesUsed){ + this.id = id; + this.baseCost = baseCost; + this.allottedMinutes = allottedMinutes; + this.minutesUsed = minutesUsed; + } + + public int getId(){ + return id; + } + + public void setId(int id){ + this.id = id; + } + + public double getBaseCost(){ + return baseCost; + } + + public void setBaseCost(double baseCost){ + this.baseCost = baseCost; + } + + public int getAllottedMinutes(){ + return allottedMinutes; + } + + public void setAllottedMinutes(int minutes){ + allottedMinutes = minutes; + } + + public int getMinutesUsed(){ + return minutesUsed; + } + + public void setMinutesUsed(int minutes){ + minutesUsed = minutes; + } + + public double calculateOverage(){ + double overageRate = 0.25; + double overageMinutes = minutesUsed - allottedMinutes; + return overageMinutes * overageRate; + } + + public double calculateTax(){ + double taxRate = 0.15; + return taxRate * (baseCost + calculateOverage()); + } + + public double calculateTotal(){ + return baseCost + calculateOverage() + calculateTax(); + } + + public void printItemizedBill(){ + System.out.println("ID: " + id); + System.out.println("Base Rate: $" + baseCost); + System.out.println("Overage Fee: $" + + String.format("%.2f", calculateOverage())); + System.out.println("Tax: $" + + String.format("%.2f", calculateTax())); + System.out.println("Total: $" + + String.format("%.2f", calculateTotal())); + } +} diff --git a/exercises/chapter6/PhoneBillCalculator.java b/exercises/chapter6/PhoneBillCalculator.java new file mode 100644 index 0000000..2d4acbc --- /dev/null +++ b/exercises/chapter6/PhoneBillCalculator.java @@ -0,0 +1,10 @@ +package exercises.chapter6; + +public class PhoneBillCalculator { + + public static void main(String args[]){ + PhoneBill bill = new PhoneBill(123456); + bill.setMinutesUsed(1000); + bill.printItemizedBill(); + } +} diff --git a/exercises/chapter7/DayOfTheWeek.java b/exercises/chapter7/DayOfTheWeek.java new file mode 100644 index 0000000..64ca5a4 --- /dev/null +++ b/exercises/chapter7/DayOfTheWeek.java @@ -0,0 +1,17 @@ +package exercises.chapter7; + +import java.util.Scanner; + +public class DayOfTheWeek { + + public static void main(String args[]){ + String[] week = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}; + + Scanner input = new Scanner(System.in); + System.out.println("Enter a number for the day of the week"); + int index = input.nextInt(); + input.close(); + + System.out.println("Corresponding day: " + week[index - 1]); + } +} diff --git a/exercises/chapter8/PasswordValidator.java b/exercises/chapter8/PasswordValidator.java new file mode 100644 index 0000000..df52be7 --- /dev/null +++ b/exercises/chapter8/PasswordValidator.java @@ -0,0 +1,107 @@ +package exercises.chapter8; + +import java.util.Scanner; + +public class PasswordValidator { + + private String username; + private String currentPassword; + + private boolean valid; + private String errorMessage; + + private static Scanner scanner = new Scanner(System.in); + + public PasswordValidator(String username, String currentPassword){ + this.username = username; + this.currentPassword = currentPassword; + } + + public boolean isValid(){ + return valid; + } + + public String getErrorMessage(){ + return errorMessage; + } + + public void closeScanner(){ + scanner.close(); + } + + public static void main(String[] args){ + var validator = login(); + validator.printPasswordRules(); + + do{ + var proposedPassword = validator.getProposedPassword(); + validator.changePassword(proposedPassword); + + if(!validator.isValid()){ + System.out.println(validator.getErrorMessage()); + } + + }while(!validator.isValid()); + + System.out.println("Your password has been changed"); + + validator.closeScanner(); + } + + public static PasswordValidator login(){ + System.out.println("Enter your username:"); + String username = scanner.nextLine(); + + System.out.println("Enter your password:"); + String password = scanner.nextLine(); + + return new PasswordValidator(username, password); + } + + public void printPasswordRules(){ + System.out.println("Your new password must meet the following requirements:"); + System.out.println("* at least 8 characters long"); + System.out.println("* contain an uppercase letter"); + System.out.println("* contain a special character"); + System.out.println("* not contain the username"); + System.out.println("* not the same as the old password"); + System.out.println(); + } + + public String getProposedPassword(){ + System.out.println("Enter your new password:"); + return scanner.nextLine(); + } + + public void changePassword(String newPassword){ + + valid = true; + errorMessage = ""; + + if(newPassword.length() < 8){ + valid = false; + errorMessage += "\n Your password must be at least 8 characters."; + } + + //Alternatively, can loop through string and use Character.isUpperCase on each char + if(newPassword.equals(newPassword.toLowerCase())){ + valid = false; + errorMessage += "\n Your password must include an uppercase letter."; + } + + if(newPassword.matches("[a-zA-Z0-9 ]*")){ + valid = false; + errorMessage += "\n Your password must include a special character (e.g. %,$[:)."; + } + + if(newPassword.toUpperCase().contains(username.toUpperCase())){ + valid = false; + errorMessage += "\n Your password cannot contain your username."; + } + + if(newPassword.equals(currentPassword)){ + valid = false; + errorMessage += "\n Your password must be different from your current password."; + } + } +} \ No newline at end of file diff --git a/exercises/chapter9/BirthdayCake.java b/exercises/chapter9/BirthdayCake.java new file mode 100644 index 0000000..c970cb9 --- /dev/null +++ b/exercises/chapter9/BirthdayCake.java @@ -0,0 +1,18 @@ +package exercises.chapter9; + +public class BirthdayCake extends Cake{ + + private int candles; + + public BirthdayCake(){ + super("vanilla"); + } + + public int getCandles() { + return candles; + } + + public void setCandles(int candles) { + this.candles = candles; + } +} diff --git a/exercises/chapter9/Cake.java b/exercises/chapter9/Cake.java new file mode 100644 index 0000000..ec00324 --- /dev/null +++ b/exercises/chapter9/Cake.java @@ -0,0 +1,28 @@ +package exercises.chapter9; + +public class Cake { + + private String flavor; + private double price; + + public Cake(String flavor){ + setFlavor(flavor); + setPrice(9.99); + } + + public String getFlavor() { + return flavor; + } + + public void setFlavor(String flavor) { + this.flavor = flavor; + } + + public double getPrice() { + return price; + } + + public void setPrice(double price) { + this.price = price; + } +} diff --git a/exercises/chapter9/TasteTester.java b/exercises/chapter9/TasteTester.java new file mode 100644 index 0000000..d284ae9 --- /dev/null +++ b/exercises/chapter9/TasteTester.java @@ -0,0 +1,22 @@ +package exercises.chapter9; + +public class TasteTester { + + public static void main(String[] args){ + Cake cake = new Cake("chocolate"); + cake.setPrice(29.99); + System.out.println("Cake flavor: " + cake.getFlavor()); + System.out.println("Cake price: " + cake.getPrice()); + + BirthdayCake birthdayCake = new BirthdayCake(); + birthdayCake.setPrice(49.95); + System.out.println("Birthday cake flavor: " + birthdayCake.getFlavor()); + System.out.println("Birthday cake price: " + birthdayCake.getPrice()); + + WeddingCake weddingCake = new WeddingCake(); + weddingCake.setFlavor("pina colada"); + System.out.println("Wedding cake flavor: " + weddingCake.getFlavor()); + System.out.println("Wedding cake price: " + weddingCake.getPrice()); + + } +} diff --git a/exercises/chapter9/WeddingCake.java b/exercises/chapter9/WeddingCake.java new file mode 100644 index 0000000..4efe582 --- /dev/null +++ b/exercises/chapter9/WeddingCake.java @@ -0,0 +1,18 @@ +package exercises.chapter9; + +public class WeddingCake extends Cake{ + + private int tiers; + + public WeddingCake(){ + super("almond"); + } + + public int getTiers() { + return tiers; + } + + public void setTiers(int tiers) { + this.tiers = tiers; + } +} diff --git a/exercises/project/Coin.java b/exercises/project/Coin.java new file mode 100644 index 0000000..c78f8a9 --- /dev/null +++ b/exercises/project/Coin.java @@ -0,0 +1,29 @@ +package exercises.project; + +import java.util.Random; + +public class Coin { + + private String side; + public static String HEADS = "Heads"; + public static String TAILS = "Tails"; + + public String getSide() { + return side; + } + + public void setSide(String side) { + this.side = side; + } + + public String flip(){ + if(new Random().nextBoolean()){ + setSide(HEADS); + } + else{ + setSide(TAILS); + } + + return getSide(); + } +} diff --git a/exercises/project/CoinTossGame.java b/exercises/project/CoinTossGame.java new file mode 100644 index 0000000..e4904e3 --- /dev/null +++ b/exercises/project/CoinTossGame.java @@ -0,0 +1,61 @@ +package exercises.project; + +import java.util.Scanner; + +public class CoinTossGame { + + private Scanner scanner; + + public static void main(String[] args){ + CoinTossGame game = new CoinTossGame(); + game.scanner = new Scanner(System.in); + + Player player1 = new Player(game.askPlayerName()); + player1.setGuess(game.askGuess()); + + Player player2 = new Player(game.askPlayerName()); + if(player1.getGuess().equalsIgnoreCase(Coin.HEADS)){ + player2.setGuess(Coin.TAILS); + }else{ + player2.setGuess(Coin.HEADS); + } + + System.out.println("Flipping the coin..."); + Coin coin = new Coin(); + coin.flip(); + System.out.println("The coin landed on " + coin.getSide()); + + game.determineWinner(player1, player2, coin); + game.scanner.close(); + } + + private String askPlayerName(){ + System.out.println("Enter the player's name:"); + return scanner.nextLine(); + } + + private String askGuess(){ + String prompt = String.format("%s or %s?", Coin.HEADS, Coin.TAILS); + System.out.println(prompt); + String guess = scanner.nextLine(); + + while(!guess.equalsIgnoreCase(Coin.HEADS) + && !guess.equalsIgnoreCase(Coin.TAILS)){ + System.out.println("Invalid guess. Try again. " + prompt); + guess = scanner.nextLine(); + } + + return guess; + } + + private void determineWinner(Player player1, Player player2, Coin coin){ + String winner; + if(coin.getSide().equalsIgnoreCase(player1.getGuess())){ + winner = player1.getName(); + }else{ + winner = player2.getName(); + } + + System.out.println("The winner is " + winner); + } +} diff --git a/exercises/project/Player.java b/exercises/project/Player.java new file mode 100644 index 0000000..b3dd8f6 --- /dev/null +++ b/exercises/project/Player.java @@ -0,0 +1,27 @@ +package exercises.project; + +public class Player { + + private String name; + private String guess; + + public Player(String name){ + setName(name); + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getGuess() { + return guess; + } + + public void setGuess(String guess) { + this.guess = guess; + } +}