├── .gitignore
├── .travis.yml
├── LICENSE
├── README.md
├── pom.xml
└── src
├── main
├── java
│ └── com
│ │ └── levelup
│ │ └── java
│ │ └── exercises
│ │ └── beginner
│ │ ├── AplhaTeleNumberTranslator.java
│ │ ├── AreaClassProgram.java
│ │ ├── AverageRainfall.java
│ │ ├── BankCharges.java
│ │ ├── BarChart.java
│ │ ├── BodyMassIndex.java
│ │ ├── BookClubPoints.java
│ │ ├── BudgetAnalysis.java
│ │ ├── CarInstrumentSimulator.java
│ │ ├── CarpetCalculatorProgram.java
│ │ ├── CelsiusToFahrenheitTable.java
│ │ ├── CharacterCounter.java
│ │ ├── CircleClass.java
│ │ ├── CircuitBoardProfit.java
│ │ ├── CoinTossSimulator.java
│ │ ├── CombinationGenerator.java
│ │ ├── DepositAndWithdrawalFiles.java
│ │ ├── DiceGame.java
│ │ ├── DistanceConversion.java
│ │ ├── ESPGame.java
│ │ ├── EnergyDrinkConsumption.java
│ │ ├── EvenOddCounter.java
│ │ ├── FatGramCalculator.java
│ │ ├── FishingGameSimulator.java
│ │ ├── FreezingAndBoilingPoints.java
│ │ ├── GameOfTwentyOne.java
│ │ ├── GeometryCalculator.java
│ │ ├── GradePapers.java
│ │ ├── GuessingGame.java
│ │ ├── LandCalculation.java
│ │ ├── MagicDates.java
│ │ ├── MassAndWeight.java
│ │ ├── MilesPerGallon.java
│ │ ├── MiscellaneousStringOperations.java
│ │ ├── MorseCodeConverter.java
│ │ ├── Mortgage.java
│ │ ├── NameSearch.java
│ │ ├── NumberIsPrime.java
│ │ ├── PalindromeDiscoverer.java
│ │ ├── ParkingTicketSimulator.java
│ │ ├── PasswordVerifier.java
│ │ ├── PenniesForPay.java
│ │ ├── PhoneBookArrayList.java
│ │ ├── PigLatin.java
│ │ ├── PresentValue.java
│ │ ├── RestaurantBill.java
│ │ ├── RockPaperScissorsGame.java
│ │ ├── RomanNumerals.java
│ │ ├── RunningTheRace.java
│ │ ├── SalesAnalysis.java
│ │ ├── SavingsAccountClass.java
│ │ ├── SlotMachineSimulation.java
│ │ ├── SortedNames.java
│ │ ├── SpeedOfSound.java
│ │ ├── SquareDisplay.java
│ │ ├── StockCommission.java
│ │ ├── StockTransaction.java
│ │ ├── StringManipulator.java
│ │ ├── SumOfDigits.java
│ │ ├── TestAverage.java
│ │ ├── TestScoresClassProgram.java
│ │ ├── TossingCoinsForADollar.java
│ │ ├── TrivaGame.java
│ │ ├── TwoDimensionalArrayOperations.java
│ │ ├── UppercaseFileConverter.java
│ │ ├── WordCounter.java
│ │ ├── WordSeparator.java
│ │ └── WorldSeriesChampion.java
└── resources
│ └── com
│ └── levelup
│ └── java
│ └── exercises
│ └── beginner
│ ├── BoyNames.txt
│ ├── Deposits.txt
│ ├── GirlNames.txt
│ ├── SalesData.txt
│ ├── Withdrawls.txt
│ ├── WorldSeriesWinners.txt
│ └── trivia.txt
└── test
└── java
└── com
└── levelup
└── java
└── exercises
└── beginner
├── AverageRainfallTest.java
├── BarChartTest.java
├── BodyMassIndexTest.java
├── BookClubPointsTest.java
├── CelsiusToFahrenheitTableTest.java
├── CharacterCounterTest.java
├── CircleClassTest.java
├── CircuitBoardProfitTest.java
├── DiceGameTest.java
├── DistanceConversionTest.java
├── ESPGameTest.java
├── EnergyDrinkConsumptionTest.java
├── EvenOddCounterTest.java
├── FatGramCalculatorTest.java
├── FreezingAndBoilingPointsTest.java
├── GameOfTwentyOneTest.java
├── GradePapersTest.java
├── GuessingGameTest.java
├── LandCalcuationTest.java
├── MagicDatesTest.java
├── MassAndWeightTest.java
├── MilesPerGallonTest.java
├── MortgageTest.java
├── NumberIsPrimeTest.java
├── PalindromeDiscovererTest.java
├── PenniesForPayTest.java
├── PresentValueTest.java
├── RestaurantBillTest.java
├── RockPaperScissorsGameTest.java
├── RomanNumeralsTest.java
├── SlotMachineSimulationTest.java
├── SpeedOfSoundTest.java
├── StockCommissionTest.java
├── StockTransactionTest.java
├── TestAverageTest.java
└── TossingCoinsForADollarTest.java
/.gitignore:
--------------------------------------------------------------------------------
1 | *.pydevproject
2 | .project
3 | .metadata
4 | target/**/*
5 | bin/**
6 | tmp/**
7 | tmp/**/*
8 | *.tmp
9 | *.bak
10 | *.swp
11 | *~.nib
12 | local.properties
13 | .classpath
14 | .settings/
15 | .loadpath
16 |
17 | # External tool builders
18 | .externalToolBuilders/
19 |
20 | # Locally stored "Eclipse launch configurations"
21 | *.launch
22 |
23 | # CDT-specific
24 | .cproject
25 |
26 | # PDT-specific
27 | .buildpath
28 | /target
29 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: java
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | levelup-java-exercises
2 | =====================
3 |
4 | [](https://travis-ci.org/leveluplunch/levelup-java-exercises)
5 |
6 | Levelup [Java exercises](http://www.leveluplunch.com/java/exercises/) is a series of exercises that walk through problems.
7 |
8 | ## Staying in touch
9 |
10 | * [leveluplunch.com](http://www.leveluplunch.com)
11 | * [Twitter](https://twitter.com/leveluplunch)
12 | * [Google plus](https://plus.google.com/+Leveluplunch)
13 | * [Facebook](https://www.facebook.com/leveluplunch)
14 | * [Youtube channel](https://www.youtube.com/user/LevelUpLunch)
15 |
16 |
17 | ## License
18 |
19 | Level up lunch is released under version 2.0 of the [Apache License](http://www.apache.org/licenses/LICENSE-2.0).
20 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 |
5 | com.levelup
6 | levelup-java-exercises
7 | 0.0.1-SNAPSHOT
8 | jar
9 |
10 | exercises
11 | http://maven.apache.org
12 |
13 |
14 | UTF-8
15 |
16 |
17 |
18 |
19 | org.mockito
20 | mockito-all
21 | 1.9.5
22 | test
23 |
24 |
25 | com.google.guava
26 | guava
27 | 15.0
28 |
29 |
30 | org.hamcrest
31 | hamcrest-all
32 | 1.3
33 |
34 |
35 | org.apache.commons
36 | commons-lang3
37 | 3.1
38 |
39 |
40 | org.apache.commons
41 | commons-math3
42 | 3.2
43 |
44 |
45 | junit
46 | junit
47 | 4.10
48 | test
49 |
50 |
51 |
52 |
53 |
54 |
55 | org.apache.maven.plugins
56 | maven-compiler-plugin
57 | 3.1
58 |
59 | 1.6
60 | 1.6
61 |
62 |
63 |
64 | org.apache.maven.plugins
65 | maven-surefire-plugin
66 | 2.16
67 |
74 |
75 |
76 |
77 |
78 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/AplhaTeleNumberTranslator.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.List;
4 | import java.util.Scanner;
5 | import java.util.stream.Collectors;
6 |
7 | import com.google.common.base.Splitter;
8 | import com.google.common.collect.ImmutableMultimap;
9 | import com.google.common.collect.Lists;
10 |
11 | /**
12 | * This java example will demonstrate how to translates alphabetic characters to
13 | * numeric equivalent.
14 | *
15 | * @author Justin Musgrove
16 | * @see Alphabetic
18 | * telephone number translator
19 | */
20 | public class AplhaTeleNumberTranslator {
21 |
22 | static ImmutableMultimap numberAlphaTrans = null;
23 |
24 | static {
25 | numberAlphaTrans = new ImmutableMultimap.Builder()
26 | .putAll("2", Lists. newArrayList("A", "B", "C"))
27 | .putAll("3", Lists. newArrayList("D", "E", "F"))
28 | .putAll("4", Lists. newArrayList("G", "H", "I"))
29 | .putAll("5", Lists. newArrayList("J", "K", "L"))
30 | .putAll("6", Lists. newArrayList("M", "N", "O"))
31 | .putAll("7", Lists. newArrayList("P", "Q", "R", "S"))
32 | .putAll("8", Lists. newArrayList("T", "U", "V"))
33 | .putAll("9", Lists. newArrayList("W", "X", "Y", "Z"))
34 | .build();
35 | }
36 |
37 | public static void main(String[] args) {
38 |
39 | // Create a Scanner to get keyboard input
40 | Scanner keyboard = new Scanner(System.in);
41 |
42 | // Get a phone number.
43 | System.out.print("Enter a phone number for translation: ");
44 | String phoneNumber = keyboard.nextLine();
45 |
46 | // close scanner
47 | keyboard.close();
48 |
49 | List convertedPhone = Splitter
50 | .fixedLength(1)
51 | .splitToList(phoneNumber)
52 | .stream()
53 | .map(t -> {
54 | if (Character.isAlphabetic(t.codePointAt(0))) {
55 | return numberAlphaTrans.inverse().get(t).asList()
56 | .get(0);
57 | } else {
58 | return t;
59 | }
60 | }).collect(Collectors.toList());
61 |
62 | System.out.println(String.join("", convertedPhone));
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/AreaClassProgram.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | /**
4 | * This java exercise will demonstrate a solution to the area class program.
5 | *
6 | * @author Justin Musgrove
7 | * @see Area class program
8 | */
9 | public class AreaClassProgram {
10 |
11 | public static class Area {
12 |
13 | /**
14 | * Method should calculate the area of a circle
15 | *
16 | * @param radius
17 | * @return area of a circle
18 | */
19 | public static double getArea(double radius) {
20 | return Math.PI * radius * radius;
21 | }
22 |
23 | /**
24 | * Method should calculate the area of a rectangle
25 | *
26 | * @param length
27 | * @param width
28 | *
29 | * @return area of a rectangle
30 | */
31 | public static double getArea(int length, int width) {
32 | return length * width;
33 | }
34 |
35 | /**
36 | * Method should calculate the area of a cylinder
37 | *
38 | * @param radius
39 | * @param height
40 | *
41 | * @return area of a cylinder
42 | */
43 | public static double getArea(double radius, double height) {
44 | return Math.PI * radius * radius * height;
45 | }
46 | }
47 |
48 | public static void main(String[] args) {
49 |
50 | // Area of a circle
51 | System.out.printf("The area of a circle with a "
52 | + "radius of 10.0 is %6.2f\n", Area.getArea(10.0));
53 |
54 | // Area of a rectangle
55 | System.out.printf("The area of a rectangle with a "
56 | + "length of 15 and a width of 25 is %6.2f\n",
57 | Area.getArea(15, 25));
58 |
59 | // Area of cylinder
60 | System.out.printf("The area of a cylinder with a "
61 | + "radius of 12.0 and a height " + "of 17.0 is %6.2f\n",
62 | Area.getArea(12.0, 17.0));
63 | }
64 |
65 | }
66 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/AverageRainfall.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.Scanner;
6 |
7 | /**
8 | * This program demonstrates how to calculate the average rainfall.
9 | *
10 | * @author Justin Musgrove
11 | * @see Average rainfall
12 | */
13 | public class AverageRainfall {
14 |
15 | final static int NUM_MONTHS = 12; // Months per year
16 |
17 | public static void main(String[] args) {
18 |
19 | int years; // Number of years
20 | double monthRain;
21 | List rainFall = new ArrayList();
22 |
23 | // Create a Scanner object for keyboard input.
24 | Scanner keyboard = new Scanner(System.in);
25 |
26 | // Get the number of years.
27 | System.out.print("Enter the number of years: ");
28 | years = keyboard.nextInt();
29 |
30 | // Validate the input.
31 | while (years < 1) {
32 | System.out.print("Invalid. Enter 1 or greater: ");
33 | years = keyboard.nextInt();
34 | }
35 |
36 | System.out.println("Enter the rainfall, in inches, "
37 | + "for each month.");
38 |
39 | for (int y = 1; y <= years; y++) {
40 |
41 | for (int m = 1; m <= NUM_MONTHS; m++) {
42 |
43 | // Get the rainfall for a month.
44 | System.out.print("Year " + y + " month " + m + ": ");
45 | monthRain = keyboard.nextDouble();
46 |
47 | // Accumulate the rainfall.
48 | rainFall.add(new Double(monthRain));
49 | }
50 | }
51 |
52 | // Display the statistics.
53 | System.out.println("\nNumber of months: " + (years * NUM_MONTHS));
54 | System.out.println("Total rainfall: "
55 | + calculateTotalRainFall(rainFall) + " inches");
56 | System.out.println("Average monthly rainfall: "
57 | + calculateAverageRainFall(rainFall) + " inches");
58 |
59 |
60 | keyboard.close();
61 |
62 | }
63 |
64 | /**
65 | * Method should return the sum of all elements in list.
66 | *
67 | * @param rainFall
68 | * @return sum of elements
69 | */
70 | static double calculateTotalRainFall(List rainFall) {
71 |
72 | Double sum = new Double(0);
73 | for (Double i : rainFall) {
74 | sum = sum + i;
75 | }
76 | return sum;
77 | }
78 |
79 | /**
80 | * Method should return the average of elements
81 | * passed in list.
82 | *
83 | * @param rainFall
84 | * @return average of elements
85 | */
86 | static double calculateAverageRainFall(List rainFall) {
87 |
88 | Double sum = 0d;
89 | for (Double vals : rainFall) {
90 | sum += vals;
91 | }
92 |
93 | return sum = sum / rainFall.size();
94 | }
95 |
96 | }
97 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/BankCharges.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.Scanner;
4 |
5 | import com.google.common.collect.Range;
6 | import com.google.common.collect.RangeMap;
7 | import com.google.common.collect.TreeRangeMap;
8 |
9 | /**
10 | * This program demonstrates a solution bank charges.
11 | *
12 | * @author Justin Musgrove
13 | * @see Bank charges
14 | */
15 | public class BankCharges {
16 |
17 | static double BASE_FEE = 10;
18 |
19 | public static void main(String[] args) {
20 |
21 | // define rages for checks
22 | RangeMap checkFee = TreeRangeMap.create();
23 | checkFee.put(Range.closed(0, 19), .1);
24 | checkFee.put(Range.closed(20, 39), .8);
25 | checkFee.put(Range.closed(40, 59), .6);
26 | checkFee.put(Range.closed(60, Integer.MAX_VALUE), .4);
27 |
28 | // Create a Scanner object for keyboard input.
29 | Scanner keyboard = new Scanner(System.in);
30 |
31 | // Get the number of checks written.
32 | System.out.print("Enter the number of checks written " + "this month: ");
33 | int numChecks = keyboard.nextInt();
34 |
35 | //close scanner
36 | keyboard.close();
37 |
38 | // calculate total fee
39 | double total = BASE_FEE + (checkFee.get(numChecks) * numChecks);
40 |
41 | // Display the total bank fees.
42 | System.out.printf("The total fees are $%.2f\n", total);
43 | }
44 |
45 |
46 |
47 | }
48 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/BarChart.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.Scanner;
6 |
7 | /**
8 | * This java exercise will demonstrate solution for bar chart exercise.
9 | *
10 | * @author Justin Musgrove
11 | * @see Bar
12 | * chart
13 | */
14 | public class BarChart {
15 |
16 | static int CHAR_PER_SALE = 100;
17 |
18 | public static void main(String[] args) {
19 |
20 | double sales;
21 | List storeSales = new ArrayList<>();
22 |
23 | // Create a Scanner object for keyboard input.
24 | Scanner keyboard = new Scanner(System.in);
25 |
26 | do {
27 | // ask user for input
28 | System.out.print("Enter today's sales for store 1: ");
29 | sales = keyboard.nextDouble();
30 |
31 | // add input to collection
32 | storeSales.add(new Double(sales));
33 |
34 | } while (sales != -1);
35 |
36 | // close scanner
37 | keyboard.close();
38 |
39 | // Display the bar chart heading.
40 | System.out.println("\nSALES BAR CHART");
41 |
42 | // Display chart bars
43 | for (Double sale : storeSales) {
44 | System.out.println("Store:" + getBar(sale));
45 | }
46 | }
47 |
48 | /**
49 | * Method should return the number of chars to make up the bar in the chart.
50 | *
51 | * @param sales
52 | * @return
53 | */
54 | static String getBar(double sales) {
55 |
56 | int numberOfChars = (int) (sales / CHAR_PER_SALE);
57 |
58 | StringBuffer buffer = new StringBuffer();
59 | for (int i = 0; i < numberOfChars; i++) {
60 | buffer.append("*");
61 | }
62 |
63 | return buffer.toString();
64 | }
65 |
66 | }
67 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/BodyMassIndex.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * This program demonstrates a solution to the to the Body Mass Index exercise.
7 | *
8 | * @author Justin Musgrove
9 | * @see Calculate Body Mass Index
10 | *
11 | */
12 | public class BodyMassIndex {
13 |
14 | public static void main(String[] args) {
15 |
16 | // Variables
17 | double weight; // The user's weight
18 | double height; // The user's height
19 | double bmi; // The user's BMI
20 |
21 | // Create a Scanner object for keyboard input.
22 | Scanner keyboard = new Scanner(System.in);
23 |
24 | // Tell the user what the program will do.
25 | System.out.println("This program will calculate your body mass index, or BMI.");
26 |
27 | // Get the user's weight.
28 | System.out.print("Enter your weight, in pounds: ");
29 | weight = keyboard.nextDouble();
30 |
31 | // Get the user's height.
32 | System.out.print("Enter your height, in inches: ");
33 | height = keyboard.nextDouble();
34 |
35 | // Calculate the user's body mass index.
36 | bmi = calculateBMI(height, weight);
37 |
38 | // Display the user's BMI.
39 | System.out.println("Your body mass index (BMI) is " + bmi);
40 |
41 | System.out.println(bmiDescription(bmi));
42 |
43 | keyboard.close();
44 | }
45 |
46 | /**
47 | * Method should calcuate bmi
48 | *
49 | * @param height
50 | * @param weight
51 | * @return
52 | */
53 | static double calculateBMI (double height, double weight) {
54 | return weight * 703 / (height * height);
55 | }
56 |
57 | /**
58 | * Method should return description based on bmi
59 | *
60 | * @param bmi
61 | * @return string
62 | */
63 | static String bmiDescription (double bmi) {
64 | if (bmi < 18.5) {
65 | return "You are underweight.";
66 | } else {
67 | if (bmi > 25) {
68 | return "You are overweight.";
69 | } else {
70 | return "Your weight is optimal.";
71 | }
72 | }
73 | }
74 |
75 |
76 | }
77 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/BookClubPoints.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * This program demonstrates a solution to the book club points exercise.
7 |
8 | *
9 | * @author Justin Musgrove
10 | * @see Book club points
11 | */
12 | public class BookClubPoints {
13 |
14 | public static void main(String[] args) {
15 |
16 | // Define variables
17 | int numberOfBooksPurchased;
18 | int pointsAwarded;
19 |
20 | // Create a Scanner object for keyboard input.
21 | Scanner keyboard = new Scanner(System.in);
22 |
23 | // Get the number of books purchased this month.
24 | System.out.print("How many books have you purchased? ");
25 | numberOfBooksPurchased = keyboard.nextInt();
26 |
27 | keyboard.close();
28 |
29 | // Determine the number of points to award.
30 | pointsAwarded = getPointsEarned(numberOfBooksPurchased);
31 |
32 | // Display the points earned.
33 | System.out.println("You have earned " + pointsAwarded + " points.");
34 | }
35 |
36 | /**
37 | * Method should return the number of points earned based on the number of
38 | * books purchased
39 | *
40 | * @param numberOfBooksPurchased
41 | * @return points earied
42 | */
43 | public static int getPointsEarned(int numberOfBooksPurchased) {
44 |
45 | if (numberOfBooksPurchased < 1) {
46 | return 0;
47 | } else if (numberOfBooksPurchased == 1) {
48 | return 5;
49 | } else if (numberOfBooksPurchased == 2) {
50 | return 15;
51 | } else if (numberOfBooksPurchased == 3) {
52 | return 30;
53 | } else {
54 | return 60;
55 | }
56 | }
57 |
58 | }
59 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/BudgetAnalysis.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.text.DecimalFormat;
4 | import java.util.Scanner;
5 |
6 | /**
7 | * This java example will demonstrate a solution to the budget analysis problem.
8 | *
9 | * @author Justin Musgrove
10 | * @see Budget analysis
11 | */
12 | public class BudgetAnalysis {
13 |
14 | public static void main(String[] args) {
15 |
16 | // Create a DecimalFormat object to format output.
17 | DecimalFormat dollar = new DecimalFormat("#,##0.00");
18 |
19 | // Create a Scanner object for keyboard input.
20 | Scanner keyboard = new Scanner(System.in);
21 |
22 | // Get the budget amount.
23 | System.out.print("Enter your budget for the month: ");
24 | double monthlyBudget = keyboard.nextDouble();
25 |
26 | // Get each expense, keep track of total.
27 | double expense;
28 | double totalExpenses = 0.0;
29 | do {
30 | // Get an expense amount.
31 | System.out.print("Enter an expense, or a negative "
32 | + "number to quit: ");
33 | expense = keyboard.nextDouble();
34 |
35 | totalExpenses += expense;
36 |
37 | } while (expense >= 0);
38 |
39 | // Display the amount after expenses.
40 | double balance = calculateAmountOverBudget(monthlyBudget, totalExpenses);
41 | if (balance < 0) {
42 | System.out.println("You are OVER budget by $"
43 | + dollar.format(Math.abs(balance)));
44 | } else if (balance > 0) {
45 | System.out.println("You are UNDER budget by $"
46 | + dollar.format(balance));
47 | } else {
48 | System.out.println("You spent the budget amount exactly.");
49 | }
50 |
51 | keyboard.close();
52 | }
53 |
54 | static double calculateAmountOverBudget(double monthlyBudget,
55 | double totalExpenses) {
56 | return monthlyBudget - totalExpenses;
57 | }
58 |
59 | }
60 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/CarInstrumentSimulator.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | /**
4 | * This java exercises will demonstrate a solution to the car instrument
5 | * simulator problem.
6 | *
7 | * @author Justin Musgrove
8 | * @see
11 | */
12 | public class CarInstrumentSimulator {
13 |
14 | class FuelGauge {
15 |
16 | final static int MAXIMUM_GALLONS = 15;
17 |
18 | private int gallons;
19 |
20 | public FuelGauge() {
21 | gallons = 0;
22 | }
23 |
24 | /**
25 | * Constructor should initialize the number of gallons of gas. If the
26 | * gallons is greater than the max it will default to the max.
27 | *
28 | * TODO: If gallons is greater than max throw GasOverflowException
29 | *
30 | * @param gallons
31 | */
32 | public FuelGauge(int gallons) {
33 | if (gallons <= MAXIMUM_GALLONS) {
34 | this.gallons = gallons;
35 | } else {
36 | gallons = MAXIMUM_GALLONS;
37 | }
38 | }
39 |
40 | public int getGallons() {
41 | return gallons;
42 | }
43 |
44 | /**
45 | * Method will add one gallon, if gallon is greater than the max for the
46 | * tank then a message will be output.
47 | */
48 | public void addGallons() {
49 | if (gallons < MAXIMUM_GALLONS) {
50 | gallons++;
51 | } else {
52 | // TODO: see constructor, throw GasOverflowException
53 | System.out.println("FUEL OVERFLOWING!!!");
54 | }
55 | }
56 |
57 | /**
58 | * Burn fuel will reduce the gallons in the tank by 1, if the fuel tank
59 | * is empty then a message will be outputed.
60 | *
61 | * TODO: Instead of outputting out of fuel, throw a
62 | * GasTankEmptyException
63 | */
64 | public void burnFuel() {
65 | if (gallons > 0) {
66 | gallons--;
67 | } else {
68 | System.out.println("OUT OF FUEL!!!");
69 | }
70 | }
71 | }
72 |
73 | class Odometer {
74 |
75 | // Constant for the maximum mileage
76 | public final int MAXIMUM_MILEAGE = 999999;
77 |
78 | // Constant for the miles-per-gallon
79 | public final int MPG = 24;
80 |
81 | private int initialMileage;
82 | private int mileage;
83 |
84 | // Field to reference a FuelGauge object
85 | private FuelGauge fuelGauge;
86 |
87 | /**
88 | * Constructor
89 | *
90 | * @param m
91 | * Initial mileage.
92 | * @param fg
93 | * A reference to a FuelGauge object.
94 | */
95 | public Odometer(int mileage, FuelGauge fuelGauge) {
96 | this.initialMileage = mileage;
97 | this.mileage = mileage;
98 | this.fuelGauge = fuelGauge;
99 | }
100 |
101 | /**
102 | * getMileage method
103 | *
104 | * @returns The mileage.
105 | */
106 | public int getMileage() {
107 | return mileage;
108 | }
109 |
110 | /**
111 | * The addMileage method increments the mileage field. If mileage
112 | * exceeds the maximum amount, it rolls over to 0.
113 | */
114 | public void addMileage() {
115 |
116 | if (mileage < MAXIMUM_MILEAGE) {
117 | mileage++;
118 | } else {
119 | mileage = 0;
120 | }
121 |
122 | int driven = initialMileage - mileage;
123 | if (driven % MPG == 0) {
124 | fuelGauge.burnFuel();
125 | }
126 | }
127 | }
128 |
129 | public static void main(String[] args) {
130 |
131 | CarInstrumentSimulator carInstrumentSimulator = new CarInstrumentSimulator();
132 |
133 | FuelGauge fuel = carInstrumentSimulator.new FuelGauge();
134 | Odometer odometer = carInstrumentSimulator.new Odometer(0, fuel);
135 |
136 | for (int x = 0; x < FuelGauge.MAXIMUM_GALLONS; x++) {
137 | fuel.addGallons();
138 | }
139 |
140 | // dive until you can't drive no longer.
141 | while (fuel.getGallons() > 0) {
142 |
143 | // add mile driven
144 | odometer.addMileage();
145 |
146 | // Display the mileage.
147 | System.out.println("Mileage: " + odometer.getMileage());
148 |
149 | // Display the amount of fuel.
150 | System.out.println("Fuel level: " + fuel.getGallons() + " gallons");
151 | System.out.println("------------------------------");
152 | }
153 | }
154 |
155 | }
156 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/CarpetCalculatorProgram.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * This program demonstrates a solution to the carpet calculator program.
7 | *
8 | * @author Justin Musgrove
9 | * @see Carpet
11 | * calculator program
12 | *
13 | */
14 | public class CarpetCalculatorProgram {
15 |
16 | /**
17 | * This class should hold information about the room's dimensions such as
18 | * the height and width.
19 | *
20 | */
21 | public class RoomDimension {
22 |
23 | private double length;
24 | private double width;
25 |
26 | public RoomDimension(double length, double width) {
27 | super();
28 | this.length = length;
29 | this.width = width;
30 | }
31 |
32 | public double getLength() {
33 | return length;
34 | }
35 |
36 | public double getWidth() {
37 | return width;
38 | }
39 |
40 | public double getArea() {
41 | return length * width;
42 | }
43 |
44 | @Override
45 | public String toString() {
46 | return "RoomDimension [length=" + length + ", width=" + width + "]";
47 | }
48 |
49 | }
50 |
51 | /**
52 | * RoomCarpet class should hold information for calculating the cost of
53 | * carpet.
54 | *
55 | */
56 | public class RoomCarpet {
57 |
58 | private RoomDimension roomDimensions;
59 | private double costOfCarpet;
60 |
61 | public RoomCarpet(RoomDimension roomDimensions, double costOfCarpet) {
62 | super();
63 | this.roomDimensions = roomDimensions;
64 | this.costOfCarpet = costOfCarpet;
65 | }
66 |
67 | public double getTotalCost() {
68 | return costOfCarpet * roomDimensions.getArea();
69 | }
70 |
71 | @Override
72 | public String toString() {
73 | return "RoomCarpet [roomDimensions=" + roomDimensions
74 | + ", costOfCarpet=" + costOfCarpet + ", " + "total cost="
75 | + getTotalCost() + "]";
76 | }
77 |
78 | }
79 |
80 | public static void main(String[] args) {
81 |
82 | final double CARPET_PRICE_PER_SQFT = 8.0;
83 |
84 | // Create a Scanner object for keyboard input.
85 | Scanner keyboard = new Scanner(System.in);
86 |
87 | // Display intro.
88 | System.out.println("This program will display the "
89 | + "carpet cost of a room." + "\nPlease enter the room's "
90 | + "dimension in feet.");
91 |
92 | // Get the length of the room.
93 | System.out.print("Enter the length of room: ");
94 | double length = keyboard.nextDouble();
95 |
96 | // Get the width of the room.
97 | System.out.print("Enter the width of room: ");
98 | double width = keyboard.nextDouble();
99 |
100 | // close keyboard
101 | keyboard.close();
102 |
103 | // Create RoomDimension and RoomCarpet objects.
104 | CarpetCalculatorProgram calculatorProgram = new CarpetCalculatorProgram();
105 | RoomDimension dimensions = calculatorProgram.new RoomDimension(length,
106 | width);
107 | RoomCarpet roomCarpet = calculatorProgram.new RoomCarpet(dimensions,
108 | CARPET_PRICE_PER_SQFT);
109 |
110 | // Print the object calling the toString
111 | System.out.println(roomCarpet);
112 | }
113 |
114 | }
115 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/CelsiusToFahrenheitTable.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | /**
4 | * This program demonstrates a solution to the celsius to fahrenheit table.
5 | *
6 | * @author Justin Musgrove
7 | * @see Celsius To Fahrenheit
8 | *
9 | */
10 | public class CelsiusToFahrenheitTable {
11 |
12 | public static void main(String[] args) {
13 |
14 | // Display the table header.
15 | System.out.println("Fahrenheit\tCelsius");
16 | System.out.println("====================");
17 |
18 | for (int x = 0; x <= 100; x++) {
19 |
20 | System.out.print(x);
21 | System.out.print("\t\t");
22 | System.out.print(celsius(x));
23 | System.out.println();
24 | }
25 |
26 | }
27 |
28 | /**
29 | * The celsius method converts a Fahrenheit temperature to Celsius.
30 | *
31 | * @param fahrenheit The Fahrenheit temperature.
32 | * @return The equivalent Celsius temperature.
33 | */
34 | static double celsius(double fahrenheit) {
35 | return ((5.0 / 9.0) * (fahrenheit - 32));
36 | }
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/CharacterCounter.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import static com.google.common.base.Preconditions.checkNotNull;
4 |
5 | import java.util.Scanner;
6 |
7 | import org.apache.commons.lang3.StringUtils;
8 |
9 | /**
10 | * This program demonstrates a solution to character counter exercise.
11 | *
12 | * @author Justin Musgrove
13 | * @see Character counter
14 | *
15 | */
16 | public class CharacterCounter {
17 |
18 |
19 | public static void main(String[] args) {
20 |
21 | String stringToSearch; // The string to search
22 | String letter = null; // The letter to count
23 |
24 | // Create a Scanner object for keyboard input.
25 | Scanner keyboard = new Scanner(System.in);
26 |
27 | // Get a string from the user.
28 | System.out.print("Enter a string:");
29 | stringToSearch = keyboard.nextLine();
30 |
31 | // Retrieve the letter to count.
32 | System.out.print("Enter a letter contained in the string:");
33 | letter = keyboard.nextLine();
34 |
35 | // Get the letter to count.
36 | double numberOfLettersInString = countLetters(stringToSearch, letter);
37 |
38 | System.out.println("The letter " + letter + " appears " + numberOfLettersInString + " times in the string:\n" + stringToSearch);
39 |
40 | keyboard.close();
41 | }
42 |
43 | /**
44 | * This method should count the number of letters in a string.
45 | *
46 | * While it looks counter intuitive wrapping a utility method
47 | * that already provides the need, it kind of is! This is demonstration
48 | * but if you wanted to refactor for some reason logic you could.
49 | *
50 | * @param stringToSearch
51 | * @param letter
52 | * @return number of letters in a string
53 | */
54 | static double countLetters (String stringToSearch, String letter) {
55 |
56 | checkNotNull(stringToSearch);
57 | checkNotNull(letter);
58 |
59 | return StringUtils.countMatches(stringToSearch, letter);
60 | }
61 |
62 | }
63 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/CircleClass.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * This java exercise will show a solution to the circle class program.
7 | *
8 | * @author Justin Musgrove
9 | * @see Circle class program
10 | */
11 | public class CircleClass {
12 |
13 | public class Circle {
14 |
15 | private final double PI = 3.14159;
16 | private double radius;
17 |
18 | public Circle() {
19 | radius = 0.0;
20 | }
21 |
22 | public Circle(double r) {
23 | radius = r;
24 | }
25 |
26 | public void setRadius(double r) {
27 | radius = r;
28 | }
29 |
30 | public double getRadius() {
31 | return radius;
32 | }
33 |
34 | public double getArea() {
35 | return PI * radius * radius;
36 | }
37 |
38 | public double getDiameter() {
39 | return radius * 2;
40 | }
41 |
42 | public double getCircumference() {
43 | return 2 * PI * radius;
44 | }
45 | }
46 |
47 | public static void main(String[] args) {
48 |
49 | // Create a Scanner object for keyboard input.
50 | Scanner keyboard = new Scanner(System.in);
51 |
52 | // Ask user to input circle radius
53 | System.out.print("Enter the radius of a circle: ");
54 | double radius = keyboard.nextDouble();
55 |
56 | // close keyboard
57 | keyboard.close();
58 |
59 | // Create a Circle object passing in user input
60 | CircleClass circleClass = new CircleClass();
61 | Circle circle = circleClass.new Circle(radius);
62 |
63 | // Display circle information
64 | System.out.println("Area is " + circle.getArea());
65 | System.out.println("Diameter is " + circle.getDiameter());
66 | System.out.println("Circumference is " + circle.getCircumference());
67 |
68 | }
69 |
70 | }
71 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/CircuitBoardProfit.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * This program will show circuit board profit.
7 | *
8 | * @author Justin Musgrove
9 | * @see Circui
11 | * t board profit
12 | */
13 | public class CircuitBoardProfit {
14 |
15 | // profit as a percentage constant
16 | final static double PROFIT_AS_PERCENT = 0.4;
17 |
18 | public static void main(String[] args) {
19 |
20 | // Create a Scanner object for keyboard input.
21 | Scanner keyboard = new Scanner(System.in);
22 |
23 | // Get the number of years.
24 | System.out.print("Enter the circuit board's retail price: ");
25 | double retailPrice = keyboard.nextDouble();
26 |
27 | // Call method to calculate profit.
28 | double profit = calculateProfit(retailPrice);
29 |
30 | // Display the amount of profit.
31 | System.out.println("Amount of profit: $" + profit);
32 |
33 | // close keyboard
34 | keyboard.close();
35 | }
36 |
37 | /**
38 | * Method will return the profit based on the
39 | * retail price and PROFIT_AS_PERCENT constant.
40 | *
41 | * @param retailPrice
42 | * @return number representing profit
43 | */
44 | public static double calculateProfit(double retailPrice) {
45 | return retailPrice * PROFIT_AS_PERCENT;
46 | }
47 |
48 | }
49 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/CoinTossSimulator.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.Random;
4 |
5 | /**
6 | * This java example will demonstrate the coin toss simulation program.
7 | *
8 | * @author Justin Musgrove
9 | * @see Coin toss Simulator
11 | */
12 | public class CoinTossSimulator {
13 |
14 | class Coin {
15 |
16 | private String sideUp;
17 |
18 | /**
19 | * Default constructor
20 | */
21 | public Coin() {
22 | // initialize sideUp
23 | toss();
24 | }
25 |
26 | /**
27 | * This method will simulate the tossing of a coin. It should set the
28 | * sideUp field to either "heads" or "tails".
29 | */
30 | public void toss() {
31 |
32 | Random rand = new Random();
33 |
34 | // Get a random value, 0 or 1.
35 | int value = rand.nextInt(2);
36 |
37 | if (value == 0) {
38 | this.sideUp = "heads";
39 | } else {
40 | this.sideUp = "tails";
41 | }
42 | }
43 |
44 | /**
45 | *
46 | * @return The side of the coin facing up.
47 | */
48 | public String getSideUp() {
49 | return sideUp;
50 | }
51 | }
52 |
53 | static final int NUMBER_OF_TOSSES = 20;
54 |
55 | public static void main(String args[]) {
56 |
57 | // Create an instance of the Coin class.
58 | CoinTossSimulator coinTossSimulator = new CoinTossSimulator();
59 | Coin myCoin = coinTossSimulator.new Coin();
60 |
61 | // Display initial toss
62 | System.out.println("The side initially facing up: "
63 | + myCoin.getSideUp());
64 |
65 | // Toss the coin repeatedly.
66 | System.out.println("Now I will toss the coin " + NUMBER_OF_TOSSES
67 | + " times.");
68 |
69 | int headCount = 0;
70 | for (int i = 0; i < NUMBER_OF_TOSSES; i++) {
71 |
72 | // Toss the coin.
73 | myCoin.toss();
74 |
75 | // Display the side facing up.
76 | System.out.println("Toss: " + myCoin.getSideUp());
77 |
78 | if ("heads".equals(myCoin.getSideUp())) {
79 | headCount++;
80 | }
81 | }
82 |
83 | System.out.println("Heads facing up: " + headCount);
84 | System.out
85 | .println("Tails facing up: " + (NUMBER_OF_TOSSES - headCount));
86 | }
87 |
88 | }
89 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/CombinationGenerator.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.Set;
4 | import java.util.stream.Collectors;
5 |
6 | import com.google.common.collect.Sets;
7 |
8 | /**
9 | * Write a program that generate all combinations of a set returning only that satisfy a size of n.
10 | *
11 | * @author Justin Musgrove
12 | * @see Combination generator
13 | */
14 | public class CombinationGenerator {
15 |
16 | public static void main(String[] args) {
17 |
18 | Set general = Sets.newHashSet(1, 2, 3, 4);
19 |
20 | Set> combinations = generateCombinations(general, 3);
21 |
22 | System.out.println(combinations);
23 | }
24 |
25 | /**
26 | * Method will generate possible combinations of
27 | * elements based on parameters
28 | *
29 | * @param from
30 | * @param size
31 | *
32 | * @return possible combinations
33 | *
34 | */
35 | public static Set> generateCombinations(
36 | Set from,
37 | int size) {
38 |
39 | Set> elements = Sets.powerSet(from);
40 |
41 | Set> possibleCombinations = elements.stream().filter(p -> p.size() == size)
42 | .collect(Collectors.toSet());
43 |
44 | return possibleCombinations;
45 | }
46 |
47 | }
48 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/DepositAndWithdrawalFiles.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import static java.lang.Double.valueOf;
4 |
5 | import java.io.IOException;
6 | import java.nio.file.Files;
7 | import java.nio.file.Path;
8 | import java.nio.file.Paths;
9 | import java.text.DecimalFormat;
10 | import java.util.Scanner;
11 |
12 | /**
13 | * This java example will provide a solution to the deposit and withdrawal
14 | * exercise.
15 | *
16 | * @author Justin Musgrove
17 | * @see Deposit and Withdrawal files
18 | */
19 | public class DepositAndWithdrawalFiles {
20 |
21 | /**
22 | * Savings account class
23 | *
24 | */
25 | class SavingsAccount {
26 |
27 | private double accountBalance;
28 | private double annualInterestRate;
29 | private double lastAmountOfInterestEarned;
30 |
31 | public SavingsAccount(double balance, double interestRate) {
32 |
33 | accountBalance = balance;
34 | annualInterestRate = interestRate;
35 | lastAmountOfInterestEarned = 0.0;
36 | }
37 |
38 | public void withdraw(double withdrawAmount) {
39 | accountBalance -= withdrawAmount;
40 | }
41 |
42 | public void deposit(double depositAmount) {
43 | accountBalance += depositAmount;
44 | }
45 |
46 | public void addInterest() {
47 |
48 | // Get the monthly interest rate.
49 | double monthlyInterestRate = annualInterestRate / 12;
50 |
51 | // Calculate the last amount of interest earned.
52 | lastAmountOfInterestEarned = monthlyInterestRate * accountBalance;
53 |
54 | // Add the interest to the balance.
55 | accountBalance += lastAmountOfInterestEarned;
56 | }
57 |
58 | public double getAccountBalance() {
59 | return accountBalance;
60 | }
61 |
62 | public double getAnnualInterestRate() {
63 | return annualInterestRate;
64 | }
65 |
66 | public double getLastAmountOfInterestEarned() {
67 | return lastAmountOfInterestEarned;
68 | }
69 | }
70 |
71 | public static void main(String args[]) throws IOException {
72 |
73 | // Create a Scanner to read keyboard input.
74 | Scanner keyboard = new Scanner(System.in);
75 |
76 | // Ask user to enter annual interest rate
77 | System.out.print("Enter the savings account's "
78 | + "annual interest rate: ");
79 | double interestRate = keyboard.nextDouble();
80 |
81 | // close keyboard
82 | keyboard.close();
83 |
84 | DepositAndWithdrawalFiles depositAndWithdrawalFiles = new DepositAndWithdrawalFiles();
85 | SavingsAccount savingsAccount = depositAndWithdrawalFiles.new SavingsAccount(
86 | 500, interestRate);
87 |
88 | // create a path to the deposit file
89 | Path depositPath = Paths
90 | .get("src/main/resources/com/levelup/java/exercises/beginner/Deposits.txt")
91 | .toAbsolutePath();
92 |
93 | // sum all lines in file and setting value in saving account
94 | double totalDeposits = Files.lines(depositPath)
95 | .mapToDouble(Double::valueOf).sum();
96 |
97 | savingsAccount.deposit(totalDeposits);
98 |
99 | // create a path to the withdrawls file
100 | Path withdrawlsPath = Paths
101 | .get("src/main/resources/com/levelup/java/exercises/beginner/Withdrawls.txt")
102 | .toAbsolutePath();
103 |
104 | // sum all lines in file and setting value in saving account
105 | double totalWithdrawls = Files.lines(withdrawlsPath)
106 | .mapToDouble(Double::valueOf).sum();
107 |
108 | savingsAccount.withdraw(totalWithdrawls);
109 |
110 | // Get the balance before adding interest.
111 | double priorBalance = savingsAccount.getAccountBalance();
112 |
113 | // Add the interest.
114 | savingsAccount.addInterest();
115 |
116 | // Get the interest earned.
117 | double interestEarned = savingsAccount.getLastAmountOfInterestEarned();
118 |
119 | // Create a DecimalFormat object for formatting output.
120 | DecimalFormat dollar = new DecimalFormat("#,##0.00");
121 |
122 | // Show user interest earned and balance.
123 | System.out
124 | .println("Interest earned: $" + dollar.format(interestEarned));
125 |
126 | System.out.println("Prior balance: $" + dollar.format(priorBalance));
127 |
128 | System.out.println("Ending balance: $"
129 | + dollar.format(savingsAccount.getAccountBalance()));
130 |
131 | }
132 |
133 | }
134 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/DiceGame.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.Random;
4 |
5 |
6 | /**
7 | * This program demonstrates a solution to the dice game exercise.
8 | *
9 | * @author Justin Musgrove
10 | * @see Dice game
11 | *
12 | */
13 | public class DiceGame {
14 |
15 | private static int numberOfGames = 10;
16 |
17 | public static void main(String[] args) {
18 |
19 | int computerWins = 0, computerRoll = 0;
20 | int userWins = 0, userRoll = 0;
21 | int tiedGames = 0;
22 |
23 | for (int round = 0; round < numberOfGames; round++) {
24 |
25 | computerRoll = rollDie();
26 | userRoll = rollDie();
27 |
28 | // determine who won the game
29 | if (computerRoll == userRoll) {
30 | tiedGames++;
31 | } else {
32 | if (computerRoll > userRoll) {
33 | computerWins++;
34 | } else {
35 | userWins++;
36 | }
37 | }
38 | }
39 |
40 | // Display the results.
41 | System.out.println("Computer...." + computerWins);
42 | System.out.println("User........" + userWins);
43 | System.out.println("Ties........" + tiedGames);
44 |
45 | // Determine the grand winner.
46 | if (computerWins > userWins) {
47 | System.out.println("You got beat by a computer!");
48 | } else {
49 | if (computerWins < userWins) {
50 | System.out.println("You beat the computer!");
51 | } else {
52 | System.out.println("The game has ended in a tie!");
53 | }
54 | }
55 | }
56 |
57 | /**
58 | * Method should return a number that represents a
59 | * side of a die in a random format.
60 | *
61 | * @return number
62 | */
63 | static int rollDie() {
64 | Random randValue = new Random();
65 | return randValue.nextInt(6) + 1;
66 | }
67 |
68 | }
69 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/DistanceConversion.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.Scanner;
6 |
7 | /**
8 | * This program demonstrates a solution to the distance conversion program
9 | * exercise.
10 | *
11 | * @author Justin Musgrove
12 | * @see Distance converter
13 | *
14 | */
15 | public class DistanceConversion {
16 |
17 | public static void main(String[] args) {
18 |
19 | int selection; // Menu selection
20 | double distance; // Distance in meters
21 |
22 | // Create a Scanner object for keyboard input.
23 | Scanner keyboard = new Scanner(System.in);
24 |
25 | // Get a distance.
26 | System.out.print("Enter a distance in meters: ");
27 | distance = keyboard.nextDouble();
28 |
29 | // Display the menu and process the user's
30 | // selection until 4 is selected.
31 | List menuItems = getMenu();
32 | do {
33 |
34 | // Display the menu.
35 | for (int x = 0; x < menuItems.size(); x++) {
36 | System.out.println((x + 1) + ". " + menuItems.get(x));
37 | }
38 |
39 | // Get the user's selection.
40 | System.out.print("\nEnter your choice: ");
41 | selection = keyboard.nextInt();
42 |
43 | // Validate the user's selection.
44 | while (selection < 1 || selection > 4) {
45 | System.out.print("Invalid selection. Enter your choice: ");
46 | selection = keyboard.nextInt();
47 | }
48 |
49 | // Process the user's selection.
50 | switch (selection) {
51 | case 1:
52 | System.out.println(distance + " meters is " +
53 | calculateKilometers(distance) + " kilometers.");
54 | break;
55 | case 2:
56 | System.out.println(distance + " meters is " +
57 | calculateInches(distance) + " inches.");
58 | break;
59 | case 3:
60 | System.out.println(distance + " meters is " +
61 | calculateFeet(distance) + " feet.");
62 | break;
63 | case 4:
64 | System.out.println("Bye!");
65 | }
66 |
67 | System.out.println();
68 |
69 | } while (selection != 4);
70 |
71 | keyboard.close();
72 |
73 | }
74 |
75 | /**
76 | * This method should return a collection of menu items.
77 | *
78 | * @return
79 | */
80 | static List getMenu() {
81 |
82 | List menuItems = new ArrayList();
83 | menuItems.add("Convert to kilometers");
84 | menuItems.add("Convert to inches");
85 | menuItems.add("Convert to feet");
86 | menuItems.add("Quit the program");
87 |
88 | return menuItems;
89 | }
90 |
91 | /**
92 | * The calculateKilometers method displays the kilometers that are equivalent to
93 | * a specified number of meters.
94 | *
95 | * @param meters
96 | * @return the number of kilometers
97 | */
98 | static double calculateKilometers(double meters) {
99 |
100 | double kilometers = meters * 0.001;
101 |
102 | return kilometers;
103 | }
104 |
105 | /**
106 | * This method should calculate inches that are equivalent to a specified
107 | * number of meters.
108 | *
109 | * @param meters
110 | * @return the number of inches
111 | */
112 | static double calculateInches(double meters) {
113 |
114 | double inches = meters * 39.37;
115 |
116 | return inches;
117 | }
118 |
119 | /**
120 | * This method should calculate the feet that are equivalent to a specified
121 | * number of meters.
122 | *
123 | * @param meters
124 | * @return The number of feet.
125 | */
126 | static double calculateFeet(double meters) {
127 |
128 | double feet = meters * 3.281;
129 |
130 | return feet;
131 | }
132 |
133 | }
134 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/ESPGame.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.List;
4 | import java.util.OptionalInt;
5 | import java.util.Random;
6 | import java.util.Scanner;
7 |
8 | import com.google.common.collect.Lists;
9 |
10 | /**
11 | * This java exercise shows a solution for the ESP question.
12 | *
13 | * @author Justin Musgrove
14 | * @see ESP game
15 | */
16 | public class ESPGame {
17 |
18 | static List choices = Lists.newArrayList("red", "green", "orange", "blue", "yellow");
19 |
20 | public static void main(String[] args) {
21 |
22 | int correctGuesses = 0;
23 |
24 | String input;
25 | Scanner keyboard = new Scanner(System.in);
26 |
27 | // join list for display
28 | String colors = String.join(", ", choices);
29 |
30 | // Play the game for 10 rounds.
31 | for (int round = 1; round <= 10; round++) {
32 |
33 | System.out.print("I'm thinking of a color " + colors + ":");
34 |
35 | input = keyboard.next();
36 |
37 | while (!isValidChoice(input)) {
38 | System.out.print("Please enter " + colors + ":");
39 | input = keyboard.next();
40 | }
41 |
42 | if (computerChoice().equalsIgnoreCase(input)) {
43 | correctGuesses ++;
44 | }
45 | }
46 |
47 | //close scanner
48 | keyboard.close();
49 |
50 | // show output
51 | System.out.println("Number of correct guesses: " + correctGuesses);
52 | }
53 |
54 | /**
55 | * Method should return computer choice
56 | *
57 | * @return color
58 | */
59 | static String computerChoice() {
60 | Random random = new Random();
61 | OptionalInt computerChoice = random.ints(0, choices.size() - 1).findFirst();
62 |
63 | return choices.get(computerChoice.getAsInt());
64 | }
65 |
66 | /**
67 | * Check if input is contained within list
68 | *
69 | * @param input
70 | * @return
71 | */
72 | static boolean isValidChoice(String input) {
73 |
74 | java.util.Optional val = choices.stream()
75 | .filter(e -> e.equals(input.toLowerCase())).findAny();
76 |
77 | return val.isPresent();
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/EnergyDrinkConsumption.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | /**
4 | * This program demonstrates a solution to the energy drink exercise.
5 | *
6 | * @author Justin Musgrove
7 | * @see Energy drink consumption
8 | */
9 | public class EnergyDrinkConsumption {
10 |
11 | // constants
12 | final static int NUMBERED_SURVEYED = 12467;
13 | final static double PURCHASED_ENERGY_DRINKS = 0.14;
14 | final static double PREFER_CITRUS_DRINKS = 0.64;
15 |
16 | public static void main(String[] args) {
17 |
18 | // Variables
19 | double energyDrinkers = calculateEnergyDrinkers(NUMBERED_SURVEYED);
20 | double preferCitrus = calculatePreferCitris(NUMBERED_SURVEYED);
21 |
22 | // Display the results.
23 | System.out.println("Total number of people surveyed "
24 | + NUMBERED_SURVEYED);
25 | System.out.println("Approximately " + energyDrinkers
26 | + " bought at least one energy drink");
27 | System.out.println(preferCitrus + " of those "
28 | + "prefer citrus flavored energy drinks.");
29 | }
30 |
31 | /**
32 | * Calculate the number of energy drinkers.
33 | *
34 | * @param numberSurveyed
35 | * @return
36 | */
37 | public static double calculateEnergyDrinkers(int numberSurveyed) {
38 | return numberSurveyed * PURCHASED_ENERGY_DRINKS;
39 | }
40 |
41 | /**
42 | * Calculate the number of energy drinkers that prefer citrus flavor.
43 | *
44 | * @param numberSurveyed
45 | * @return
46 | */
47 | public static double calculatePreferCitris(int numberSurveyed) {
48 | return numberSurveyed * PREFER_CITRUS_DRINKS;
49 | }
50 |
51 | }
52 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/EvenOddCounter.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.Random;
4 |
5 | /**
6 | * This java example will demonstrate how to determine if
7 | * a number is even or odd.
8 | *
9 | * @author Justin Musgrove
10 | * @see Even odd counter
11 | */
12 | public class EvenOddCounter {
13 |
14 | private static int RANDOM_NUMBERS = 100;
15 |
16 | public static void main(String[] args) {
17 |
18 | int evenNumberCount = 0;
19 | int oddNumberCount = 0;
20 |
21 | Random randomValue = new Random();
22 |
23 | // Generate 100 random numbers.
24 | for (int i = 1; i <= RANDOM_NUMBERS; i++) {
25 | // Determine if the number was even or odd.
26 | if (isEven(randomValue.nextInt(i))) {
27 | evenNumberCount++;
28 | } else {
29 | oddNumberCount++;
30 | }
31 | }
32 |
33 | System.out.println("Number of even numbers: " + evenNumberCount);
34 | System.out.println("Number of odd numbers: " + oddNumberCount);
35 |
36 | }
37 |
38 | /**
39 | * @param num to check
40 | * @return true if the num is true otherwise false
41 | */
42 | public static boolean isEven(int num) {
43 | boolean isEvenNumber = false;
44 |
45 | if ((num % 2) == 0) {
46 | isEvenNumber = true;
47 | }
48 | return isEvenNumber;
49 | }
50 | }
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/FatGramCalculator.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * This program demonstrates a solution bank charges.
7 | *
8 | * @author Justin Musgrove
9 | * @see Fat gram calculator
10 | */
11 | public class FatGramCalculator {
12 |
13 | public static void main(String[] args) {
14 |
15 | // Create a Scanner object for keyboard input.
16 | Scanner keyboard = new Scanner(System.in);
17 |
18 | // Ask user for number of calories.
19 | System.out.print("How many calories does the food have? ");
20 | double calories = keyboard.nextDouble();
21 |
22 | // Get the number of fat grams.
23 | System.out.print("How many fat grams does the food have? ");
24 | double fatGrams = keyboard.nextDouble();
25 |
26 | // close scanner
27 | keyboard.close();
28 |
29 | // Calculate calories from fat.
30 | double fatCalories = calculateFatCalories(fatGrams);
31 |
32 | // validation check
33 | if (validateData (fatCalories, calories) ) {
34 | System.out.println("Invalid data.");
35 | } else {
36 |
37 | // Calculate percentage of calories from fat.
38 | double fatPercentage = calculateFatPercentatge(fatCalories, calories);
39 |
40 | // Display the results.
41 | System.out.println("The percentage of calories from fat is "
42 | + (fatPercentage * 100) + "%.");
43 |
44 | if (fatPercentage < 0.3) {
45 | System.out.println("The food is low in fat.");
46 | } else {
47 | System.out.println("The food is NOT low in fat.");
48 | }
49 | }
50 | }
51 |
52 | /**
53 | * Method should calculate fat calories based on
54 | * fat grams
55 | *
56 | * @param fatGrams
57 | * @return
58 | */
59 | static double calculateFatCalories (double fatGrams) {
60 | return fatGrams * 9;
61 | }
62 |
63 | /**
64 | * Method should calculate fat percentage.
65 | *
66 | * @param fatCalories
67 | * @param calories
68 | * @return
69 | */
70 | static double calculateFatPercentatge(double fatCalories, double calories) {
71 | return fatCalories / calories;
72 | }
73 |
74 | /**
75 | * @param fatCalories
76 | * @param calories
77 | * @return
78 | */
79 | static boolean validateData (double fatCalories, double calories) {
80 | return fatCalories > calories;
81 | }
82 |
83 | }
84 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/FishingGameSimulator.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 | import java.util.Random;
6 | import java.util.Scanner;
7 |
8 | /**
9 | * This java example will demonstrate a solution for
10 | * fishing game simulator.
11 | *
12 | * @author Justin Musgrove
13 | * @see Fishing game simulator
14 | */
15 | public class FishingGameSimulator {
16 |
17 | public class Die {
18 |
19 | private final int SIDES = 6;
20 | private int value;
21 |
22 | /**
23 | * Default constructor will call the roll
24 | */
25 | Die() {
26 | roll();
27 | }
28 |
29 | /**
30 | * The roll method sets the value of the die to a random number.
31 | */
32 |
33 | public void roll() {
34 | // Create a random object.
35 | Random randomValue = new Random();
36 |
37 | // Set the value to a random number.
38 | value = randomValue.nextInt(SIDES) + 1;
39 | }
40 |
41 | public int getValue() {
42 | return value;
43 | }
44 | }
45 |
46 | /**
47 | * This class will represent roll outcome.
48 | *
49 | */
50 | public class RollOutcome {
51 |
52 | String message;
53 | Integer points;
54 |
55 | public RollOutcome(String message, Integer points) {
56 | super();
57 | this.message = message;
58 | this.points = points;
59 | }
60 |
61 | public String getMessage() {
62 | return message;
63 | }
64 | public Integer getPoints() {
65 | return points;
66 | }
67 | }
68 |
69 | public static void main(String args[]) {
70 |
71 | // instance of class
72 | FishingGameSimulator feSim = new FishingGameSimulator();
73 |
74 | // set up outcome map
75 | Map outComeMap = new HashMap<>();
76 | outComeMap.put(1, feSim.new RollOutcome("huge fish", 10));
77 | outComeMap.put(2, feSim.new RollOutcome("an old shoe", 20));
78 | outComeMap.put(3, feSim.new RollOutcome("little fish", 30));
79 | outComeMap.put(4, feSim.new RollOutcome("30 inch walleye", 40));
80 | outComeMap.put(5, feSim.new RollOutcome("Salt water redfish", 50));
81 | outComeMap.put(6, feSim.new RollOutcome("52 inch muskellunge", 60));
82 |
83 | // Create a Scanner object for keyboard input.
84 | Scanner keyboard = new Scanner(System.in);
85 |
86 | String continuePlay = "";
87 | Integer totalFishingPoints = 0;
88 |
89 | System.out.println("Lets go fishing!");
90 |
91 | do {
92 |
93 | Die die = feSim.new Die();
94 |
95 | RollOutcome outcome = outComeMap.get(die.getValue());
96 |
97 | System.out.println("You rolled: \t\t" + die.getValue());
98 | System.out.println("You caught: \t\t" + outcome.getMessage());
99 | System.out.println("Points: \t\t" + outcome.getPoints());
100 |
101 | // track points
102 | totalFishingPoints += outcome.getPoints();
103 |
104 | // ask user to play again
105 | System.out.println("");
106 | System.out.println("Lets go fishing! Enter Y to play: ");
107 | continuePlay = keyboard.next();
108 |
109 | } while (continuePlay.equalsIgnoreCase("Y"));
110 |
111 | System.out.println("Thanks for playing, total points: " + totalFishingPoints);
112 |
113 | //Game over message
114 | if (totalFishingPoints < 100) {
115 | System.out.println("Better Luck next time");
116 | } else {
117 | System.out.println("BOOM, lets get the grill started");
118 | }
119 |
120 | // close keyboard
121 | keyboard.close();
122 | }
123 |
124 | }
125 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/FreezingAndBoilingPoints.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * This java example will demonstrate a solution to the Freezing and boiling exercise.
7 | *
8 | * @author Justin Musgrove
9 | * @see Freezing and Boiling Points
10 | */
11 | public class FreezingAndBoilingPoints {
12 |
13 | public class FreezeAndBoiling {
14 |
15 | private double temperature;
16 |
17 | public FreezeAndBoiling(double t) {
18 | temperature = t;
19 | }
20 |
21 | public double getTemperature() {
22 | return temperature;
23 | }
24 |
25 | /**
26 | * Method should check if the temperature is freezing
27 | *
28 | * @return true if Ethyl is freezing
29 | */
30 | public boolean isEthylAlchoolFreezing() {
31 |
32 | if (temperature <= -173.0) {
33 | return true;
34 | } else {
35 | return false;
36 | }
37 | }
38 |
39 | /**
40 | * Method should check if the temperature is boiling
41 | *
42 | * @return true if Ethyl is boiling
43 | */
44 | public boolean isEthylAlchoolBoiling() {
45 |
46 | if (temperature >= 172.0) {
47 | return true;
48 | } else {
49 | return false;
50 | }
51 | }
52 |
53 | /**
54 | * Method should check if the temperature is freezing
55 | *
56 | * @return true if Oxygen is freezing
57 | */
58 | public boolean isOxygenFreezing() {
59 |
60 | if (temperature <= -362.0) {
61 | return true;
62 | } else {
63 | return false;
64 | }
65 | }
66 |
67 | /**
68 | * Method should check if the temperature is boiling
69 | *
70 | * @return true if Oxygen is boiling
71 | */
72 | public boolean isOxygenBoiling() {
73 |
74 | if (temperature >= -306.0) {
75 | return true;
76 | } else {
77 | return false;
78 | }
79 | }
80 |
81 | /**
82 | * Method should check if the temperature is freezing
83 | *
84 | * @return true if Water is freezing
85 | */
86 | public boolean isWaterFreezing() {
87 |
88 | if (temperature <= 32.0) {
89 | return true;
90 | } else {
91 | return false;
92 | }
93 | }
94 |
95 | /**
96 | * Method should check if the temperature is boiling
97 | *
98 | * @return true if Water is boiling
99 | */
100 | public boolean isWaterBoiling() {
101 |
102 | if (temperature >= 212.0) {
103 | return true;
104 | } else {
105 | return false;
106 | }
107 | }
108 | }
109 |
110 | public static void main(String[] args) {
111 |
112 | // Create a Scanner object for keyboard input.
113 | Scanner keyboard = new Scanner(System.in);
114 |
115 | System.out.print("Enter a temperature: ");
116 | double temperature = keyboard.nextDouble();
117 |
118 | // close keyboard
119 | keyboard.close();
120 |
121 | FreezingAndBoilingPoints freezeAndBoilingPoints = new FreezingAndBoilingPoints();
122 | FreezeAndBoiling freezeAndBoiling = freezeAndBoilingPoints.new FreezeAndBoiling(
123 | temperature);
124 |
125 | // Display elements will freeze.
126 | if (freezeAndBoiling.isEthylAlchoolBoiling()) {
127 | System.out.println("Ethyl alcohol will freeze.");
128 | }
129 |
130 | if (freezeAndBoiling.isOxygenFreezing()) {
131 | System.out.println("Oxygen will freeze.");
132 | }
133 |
134 | if (freezeAndBoiling.isWaterFreezing())
135 | System.out.println("Water will freeze.");
136 |
137 | // Display if elements will boil.
138 | if (freezeAndBoiling.isEthylAlchoolBoiling()) {
139 | System.out.println("Ethyl alcohol will boil.");
140 | }
141 |
142 | if (freezeAndBoiling.isOxygenBoiling()) {
143 | System.out.println("Oxygen will boil.");
144 | }
145 |
146 | if (freezeAndBoiling.isWaterBoiling()) {
147 | System.out.println("Water will boil.");
148 | }
149 | }
150 |
151 | }
152 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/GameOfTwentyOne.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.Random;
4 | import java.util.Scanner;
5 |
6 | /**
7 | * This java example will demonstrate a solution to the game of twenty one.
8 | *
9 | * @author Justin Musgrove
10 | * @see Game of twenty one
11 | */
12 | public class GameOfTwentyOne {
13 |
14 | static class Die {
15 |
16 | private final int NUMBER_OF_SIDES = 6;
17 | private int value;
18 |
19 | /**
20 | * Constructor will call the roll method to set the value of the die
21 | *
22 | */
23 | Die() {
24 | roll();
25 | }
26 |
27 | /**
28 | * The roll method sets the value of the die to a random number.
29 | */
30 |
31 | public void roll() {
32 | Random randomValue = new Random();
33 |
34 | value = randomValue.nextInt(NUMBER_OF_SIDES) + 1;
35 | }
36 |
37 | /**
38 | * Get roll value
39 | *
40 | * @return number that represents roll
41 | */
42 | public int getValue() {
43 | return value;
44 | }
45 | }
46 |
47 | /**
48 | * Method should return a value that represents the sum of both die
49 | *
50 | * @return int value
51 | */
52 | public static int getRollValue() {
53 |
54 | Die die = new Die();
55 |
56 | // roll first die
57 | int roll1Value = die.getValue();
58 |
59 | // roll second die
60 | die.roll();
61 |
62 | int roll2Value = die.getValue();
63 |
64 | // Return the sum of the value of the dice.
65 | return roll1Value + roll2Value;
66 | }
67 |
68 | /**
69 | * Method will determine if the game limit has been met
70 | *
71 | * @param value
72 | * @return false if value gt 21
73 | */
74 | public static boolean isUnderGameLimit(int value) {
75 |
76 | if (value > 21) {
77 | return false;
78 | } else {
79 | return true;
80 | }
81 | }
82 |
83 | /**
84 | * Method will ask user to enter if they would like to play again
85 | *
86 | * @return true if user wants to play again
87 | */
88 | public static boolean playAgain() {
89 |
90 | Scanner keyboard = new Scanner(System.in);
91 |
92 | // Ask the user to roll the dice.
93 | System.out.print("Roll the dice? (y/n) : ");
94 | String userResponse = keyboard.nextLine(); // Get a line of input.
95 | char letter = userResponse.charAt(0); // Get the first character.
96 |
97 | if (letter == 'Y' || letter == 'y') {
98 | return true;
99 | } else {
100 | return false;
101 | }
102 | }
103 |
104 | /**
105 | * Method is responsible for handling displaying results to user
106 | *
107 | * @param computerScore
108 | * @param userScore
109 | */
110 | public static void displayResults(int computerScore, int userScore) {
111 |
112 | // Display the computer and user's points.
113 | System.out.println("\nGame Over\n");
114 | System.out.println("User's Points: " + userScore);
115 | System.out.println("Computer's Points: " + computerScore);
116 |
117 | System.out.println(getWinnerMessage(computerScore, userScore));
118 |
119 | }
120 |
121 | /**
122 | * Method should return a message on who wins the game
123 | *
124 | * @param computer
125 | * score
126 | * @param user
127 | * score
128 | * @return String representing winner
129 | */
130 | public static String getWinnerMessage(int computerScore, int userScore) {
131 |
132 | if (userScore > computerScore && isUnderGameLimit(userScore)) {
133 | return "Congrats, you win!!!";
134 | } else if (isUnderGameLimit(userScore)
135 | && !isUnderGameLimit(computerScore)) {
136 | return "Congrats, you win!!!";
137 | } else if (userScore == 21 && computerScore != 21) {
138 | return "Congrats, you win!!!";
139 | } else if (userScore == computerScore) {
140 | return "Tie game!";
141 | } else if (!isUnderGameLimit(userScore)
142 | && !isUnderGameLimit(computerScore)) {
143 | return "This game has ended without a winner.";
144 | } else {
145 | return "The computer wins!";
146 | }
147 | }
148 |
149 | public static void main(String[] args) {
150 |
151 | int computerPoints = 0;
152 | int userPoints = 0;
153 |
154 | while (playAgain()) {
155 |
156 | computerPoints += getRollValue();
157 | userPoints += getRollValue();
158 |
159 | // break the game if either user or computer go over the limit
160 | if (!isUnderGameLimit(userPoints)
161 | || !isUnderGameLimit(computerPoints)) {
162 | break;
163 | }
164 |
165 | System.out.println("User Points: " + userPoints);
166 | }
167 |
168 | if (userPoints == 0 && computerPoints == 0) {
169 | System.out.println("Gotta play to win!!!");
170 | } else {
171 | displayResults(computerPoints, userPoints);
172 | }
173 | }
174 |
175 | }
176 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/GeometryCalculator.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * This java exercise demonstrates a solution for the geometry calculator.
7 | *
8 | * @author Justin Musgrove
9 | * @see Geometry Calculator
10 | */
11 | public class GeometryCalculator {
12 |
13 | public static class Geometry {
14 | public static double areaOfCircle(double radius) {
15 | return Math.PI * radius * radius;
16 | }
17 |
18 | public static double areaOfRectangle(double length, double width) {
19 | return length * width;
20 | }
21 |
22 | public static double areaOfTriangle(double base, double h) {
23 | return base * h * 0.5;
24 | }
25 | }
26 |
27 | public static void main(String[] args) {
28 |
29 | int choice; // The user's menu choice
30 |
31 | do {
32 | // Get the user's menu choice.
33 | choice = getMenu();
34 |
35 | if (choice == 1) {
36 | calculateCircleArea();
37 | } else if (choice == 2) {
38 | calculateRectangleArea();
39 | } else if (choice == 3) {
40 | calculateTriangleArea();
41 | } else if (choice == 4) {
42 | System.out.println("Thanks for calculating!");
43 | }
44 |
45 | } while (choice != 4);
46 | }
47 |
48 | public static int getMenu() {
49 |
50 | int userChoice;
51 |
52 | // keyboard input
53 | Scanner keyboard = new Scanner(System.in);
54 |
55 | // Display the menu.
56 | System.out.println("Geometry Calculator\n");
57 | System.out.println("1. Calculate the Area of a Circle");
58 | System.out.println("2. Calculate the Area of a Rectangle");
59 | System.out.println("3. Calculate the Area of a Triangle");
60 | System.out.println("4. Quit\n");
61 | System.out.print("Enter your choice (1-4) : ");
62 |
63 | // get input from user
64 | userChoice = keyboard.nextInt();
65 |
66 | // validate input
67 | while (userChoice < 1 || userChoice > 4) {
68 | System.out.print("Please enter a valid range: 1, 2, 3, or 4: ");
69 | userChoice = keyboard.nextInt();
70 | }
71 |
72 | return userChoice;
73 | }
74 |
75 | public static void calculateCircleArea() {
76 |
77 | double radius;
78 |
79 | // Get input from user
80 | Scanner keyboard = new Scanner(System.in);
81 | System.out.print("What is the circle's radius? ");
82 | radius = keyboard.nextDouble();
83 |
84 | // Display output
85 | System.out.println("The circle's area is "
86 | + Geometry.areaOfCircle(radius));
87 | }
88 |
89 | public static void calculateRectangleArea() {
90 | double length;
91 | double width;
92 |
93 | // Get input from user
94 | Scanner keyboard = new Scanner(System.in);
95 |
96 | // Get length
97 | System.out.print("Enter length? ");
98 | length = keyboard.nextDouble();
99 |
100 | // Get width
101 | System.out.print("Enter width? ");
102 | width = keyboard.nextDouble();
103 |
104 | // Display output
105 | System.out.println("The rectangle's area is "
106 | + Geometry.areaOfRectangle(length, width));
107 | }
108 |
109 | public static void calculateTriangleArea() {
110 |
111 | double base;
112 | double height;
113 |
114 | // Get input from user
115 | Scanner keyboard = new Scanner(System.in);
116 |
117 | // Get the base
118 | System.out.print("Enter length of the triangle's base? ");
119 | base = keyboard.nextDouble();
120 |
121 | // Get the height
122 | System.out.print("Enter triangle's height? ");
123 | height = keyboard.nextDouble();
124 |
125 | // Display the triangle's area.
126 | System.out.println("The triangle's area is "
127 | + Geometry.areaOfTriangle(base, height));
128 | }
129 |
130 | }
131 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/GradePapers.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.List;
4 | import java.util.Scanner;
5 |
6 | import com.google.common.collect.Lists;
7 | import com.google.common.collect.Range;
8 | import com.google.common.collect.RangeMap;
9 | import com.google.common.collect.TreeRangeMap;
10 | import com.google.common.math.DoubleMath;
11 |
12 | /**
13 | * This program demonstrates a solution to the to the grade papers exercise.
14 | *
15 | * @author Justin Musgrove
16 | * @see Grade papers
17 | *
18 | */
19 | public class GradePapers {
20 |
21 | static RangeMap gradeScale = TreeRangeMap.create();
22 | static {
23 | gradeScale.put(Range.closed(0, 60), "F");
24 | gradeScale.put(Range.closed(61, 70), "D");
25 | gradeScale.put(Range.closed(71, 80), "C");
26 | gradeScale.put(Range.closed(81, 90), "B");
27 | gradeScale.put(Range.closed(91, 100), "A");
28 | }
29 |
30 | public static void main(String[] args) {
31 |
32 | // create a list to hold test scores
33 | List grades = Lists.newArrayList();
34 |
35 | // Create a Scanner object for keyboard input.
36 | Scanner keyboard = new Scanner(System.in);
37 |
38 | // Get the user's selection.
39 | System.out.print("Enter test score (-1 to exit): ");
40 | double selection = keyboard.nextDouble();
41 |
42 | while (selection != -1) {
43 | System.out.print("Enter test score (-1 to exit): ");
44 | selection = keyboard.nextDouble();
45 | if (selection != -1) {
46 | grades.add(new Double (selection));
47 | }
48 | }
49 |
50 | // average test scores
51 | double averageOfAllTestScores = getTestScoreAverages (grades);
52 |
53 | String letterGrade = getLetterGrade (averageOfAllTestScores);
54 |
55 | System.out.println("Average of test scores: " + averageOfAllTestScores);
56 | System.out.println("Your overall average grade is: " + letterGrade);
57 |
58 | keyboard.close();
59 | }
60 |
61 | /**
62 | * Method should calculate the average scores
63 | *
64 | * @param grades
65 | * @return
66 | */
67 | static double getTestScoreAverages (List extends Number> grades) {
68 | return DoubleMath.mean(grades);
69 | }
70 |
71 | /**
72 | * Method should return the letter grade based on scale
73 | *
74 | * @param averageOfAllTestScores
75 | * @return
76 | */
77 | static String getLetterGrade (double averageOfAllTestScores) {
78 | return gradeScale.get((int) averageOfAllTestScores);
79 | }
80 |
81 |
82 |
83 |
84 | }
85 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/GuessingGame.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.Random;
4 | import java.util.Scanner;
5 |
6 | /**
7 | * This program demonstrates a solution to the guessing game exercise.
8 | *
9 | * @author Justin Musgrove
10 | * @see Guessing game
11 | *
12 | */
13 | public class GuessingGame {
14 |
15 | // Create a Random object.
16 | final static Random rand = new Random();
17 |
18 | // max number is the upward bound number
19 | static final int MAX_NUMBER = 10;
20 |
21 | public static void main(String[] args) {
22 |
23 | // Create variables to hold input in program
24 | int usersGuess;
25 | int randomNumber;
26 | int numberOfGuesses;
27 |
28 | // Create a Scanner object for keyboard input.
29 | Scanner keyboard = new Scanner(System.in);
30 |
31 | // Ask the user to guess a number
32 | System.out.println("I'm thinking of a number.");
33 | System.out.print("Guess what it is: ");
34 | usersGuess = keyboard.nextInt();
35 |
36 | // initialize number of guesses
37 | numberOfGuesses = 1;
38 |
39 | // get random number
40 | randomNumber = getRandomNumber();
41 |
42 | // Respond to the user's usersGuess.
43 | while (usersGuess != randomNumber) {
44 |
45 | if (usersGuess < randomNumber) {
46 | System.out.println("No, that's too low.");
47 | } else if (usersGuess > randomNumber) {
48 | System.out.println("Sorry, that's too high.");
49 | }
50 |
51 | // Ask again
52 | System.out.print("Guess again: ");
53 | usersGuess = keyboard.nextInt();
54 |
55 | // Increment the usersGuess counter.
56 | numberOfGuesses++;
57 | }
58 |
59 | // output to user.
60 | System.out.println("Congratulations! You guessed it!");
61 | System.out.println("I was thinking of the number " + randomNumber + ".");
62 | System.out.println("You got it right in " + numberOfGuesses + " guesses.");
63 |
64 | keyboard.close();
65 | }
66 |
67 | /**
68 | * Method should return a random number within the upward bound MAX_NUMBER.
69 | * @return
70 | */
71 | static int getRandomNumber () {
72 | return rand.nextInt(MAX_NUMBER);
73 | }
74 |
75 |
76 | }
77 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/LandCalculation.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * This program demonstrates a solution to the to the Land Calculation exercise.
7 | *
8 | * @author Justin Musgrove
9 | * @see Land calcuation
10 | *
11 | */
12 | public class LandCalculation {
13 |
14 | private static final int FEET_PER_ACRE = 43560;
15 |
16 | public static void main(String[] args) {
17 | double tract; // tract in feet
18 | double acres; // To hold number of acres
19 |
20 | // Create a Scanner object for keyboard input.
21 | Scanner keyboard = new Scanner(System.in);
22 |
23 | // Tell the user what the program will do.
24 | System.out.println("This program will calculate number of acres.");
25 |
26 | // Get the tract in feet.
27 | System.out.print("Enter tract in feet: ");
28 | tract = keyboard.nextDouble();
29 |
30 | acres = calculateAcres(tract);
31 |
32 | // Display the results.
33 | System.out.println("A tract of land with " + tract + " square feet has " + acres + " acres.");
34 |
35 | keyboard.close();
36 | }
37 |
38 | /**
39 | * Should calculate the number of acres.
40 | *
41 | * @param tract
42 | * @return double
43 | */
44 | static double calculateAcres(double tract) {
45 | return tract / FEET_PER_ACRE;
46 | }
47 |
48 | }
49 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/MagicDates.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.time.LocalDate;
4 | import java.time.format.DateTimeFormatter;
5 | import java.util.Scanner;
6 |
7 | /**
8 | * This program is a solution to the magic date program.
9 | *
10 | * @author Justin Musgrove
11 | * @see Magic
12 | * dates
13 | */
14 | public class MagicDates {
15 |
16 | public static void main(String[] args) {
17 |
18 | // Create a Scanner object for keyboard input.
19 | Scanner keyboard = new Scanner(System.in);
20 |
21 | // Ask user for input
22 | System.out.print("Enter date in mm/dd/yyyy format:");
23 | String dateAsString = keyboard.next();
24 |
25 | // close stream
26 | keyboard.close();
27 |
28 | // Parse string to date
29 | LocalDate date = LocalDate.parse(dateAsString,
30 | DateTimeFormatter.ofPattern("MM/dd/yyyy"));
31 |
32 | // check date and display output
33 | if (magicDate(date)) {
34 | System.out.println("That date is magic!");
35 | } else {
36 | System.out.println("Sorry, nothing magic about that date...");
37 | }
38 | }
39 |
40 | /**
41 | * Method will check if a date is magic define by month * date = last two
42 | * digets of year
43 | *
44 | * @param date
45 | * @return true if the date is magic
46 | */
47 | public static boolean magicDate(LocalDate date) {
48 |
49 | int month = date.getMonth().getValue();
50 | int day = date.getDayOfMonth();
51 | int year = date.getYear();
52 |
53 | String yearAsString = String.valueOf(year);
54 | String lastTwoDigits = "0";
55 | if (yearAsString.length() == 4) {
56 | lastTwoDigits = yearAsString.substring(2);
57 | }
58 |
59 | return (month * day) == Integer.parseInt(lastTwoDigits);
60 | }
61 |
62 | }
63 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/MassAndWeight.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * This program demonstrates a solution to mass and weight.
7 | *
8 | * @author Justin Musgrove
9 | * @see Mass and weight
10 | */
11 | public class MassAndWeight {
12 |
13 | public static void main(String[] args) {
14 |
15 | // Create a Scanner object for keyboard input.
16 | Scanner keyboard = new Scanner(System.in);
17 |
18 | // Describe to the user what the program will do.
19 | System.out.println("Enter the object's mass:");
20 |
21 | double mass = keyboard.nextDouble();
22 |
23 | //close scanner
24 | keyboard.close();
25 |
26 | // pass mass to calculate weight
27 | double weight = calculateWeightInNewtons(mass);
28 |
29 | System.out.println("The object's weight is: " + weight);
30 |
31 | // get message per requirement
32 | String message = validWeight(weight);
33 |
34 | if (message.length() > 0) {
35 | System.out.println(message);
36 | }
37 |
38 | }
39 |
40 | /**
41 | * Method should return a message if weight is greater
42 | * than 1000 or less than 10. If it is between the range
43 | * an empty string will be returned
44 | *
45 | * @param weight
46 | * @return message
47 | */
48 | static String validWeight (double weight) {
49 |
50 | if (weight > 1000) {
51 | return "The object is to heavy";
52 | } else if (weight < 10) {
53 | return "The object is to light";
54 | } else {
55 | return "";
56 | }
57 | }
58 |
59 | /**
60 | * Method will calculate weight in Newtons
61 | *
62 | * @param mass
63 | * @return weight
64 | */
65 | static double calculateWeightInNewtons(double mass) {
66 | return mass * 9.8;
67 | }
68 |
69 | }
70 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/MilesPerGallon.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * This java exercises will demonstrate calculating miles per gallon.
7 | *
8 | * @author Justin Musgrove
9 | * @see Calculate Miles per Gallon
10 | *
11 | */
12 | public class MilesPerGallon {
13 |
14 | public static void main(String[] args) {
15 |
16 | double miles; // Miles driven
17 | double gallons; // Gallons of fuel
18 | double mpg; // Miles-per-gallon
19 |
20 | // Create a Scanner object for keyboard input.
21 | Scanner keyboard = new Scanner(System.in);
22 |
23 | // Describe to the user what the program will do.
24 | System.out.println("This program will calculate miles per gallon.");
25 |
26 | // Get the miles driven.
27 | System.out.print("Enter the miles driven: ");
28 | miles = keyboard.nextDouble();
29 |
30 | // Get gallons of fuel
31 | System.out.print("Enter the gallons of fuel used: ");
32 | gallons = keyboard.nextDouble();
33 |
34 | // call calculateMilesPerGallon to run calculation
35 | mpg = calculateMilesPerGallon(miles, gallons);
36 |
37 | // Display the miles-per-gallon.
38 | System.out.print("The miles-per-gallon is " + mpg);
39 |
40 | keyboard.close();
41 | }
42 |
43 | /**
44 | * Method should calculate miles per gallon
45 | *
46 | * @param miles
47 | * @param gallons
48 | * @return
49 | */
50 | static double calculateMilesPerGallon(double miles, double gallons) {
51 | return miles / gallons;
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/MiscellaneousStringOperations.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.Arrays;
4 | import java.util.Comparator;
5 | import java.util.Map;
6 | import java.util.Map.Entry;
7 | import java.util.Optional;
8 | import java.util.StringTokenizer;
9 | import java.util.stream.Collectors;
10 |
11 | /**
12 | * This program demonstrates a solution to the Miscellaneous string operations
13 | * exercise.
14 | *
15 | * @author Justin Musgrove
16 | * @see Miscellaneo
18 | * u s string operations
19 | *
20 | */
21 | public class MiscellaneousStringOperations {
22 |
23 | static class StringOperations {
24 |
25 | public static int wordCount(String phrase) {
26 | StringTokenizer strTok = new StringTokenizer(phrase);
27 | return strTok.countTokens();
28 | }
29 |
30 | public static String mostFrequent(String sentence) {
31 |
32 | Comparator> byValue = (entry1, entry2) -> entry1
33 | .getValue().compareTo(entry2.getValue());
34 |
35 | // group existing chars together
36 | Map frequentChars = Arrays.stream(
37 | sentence.toLowerCase().split("")).collect(
38 | Collectors.groupingBy(c -> c, Collectors.counting()));
39 |
40 | // order highest to lowest
41 | Optional> val = frequentChars.entrySet()
42 | .stream().sorted(byValue.reversed()).findFirst();
43 |
44 | return val.get().getKey();
45 | }
46 |
47 | public static String replaceSubString(String original,
48 | String findString, String replaceString) {
49 |
50 | // If string to find and the replace string are the same then return
51 | // original b/c there is nothing to replace
52 | if (findString.equals(replaceString)) {
53 | return original;
54 | }
55 |
56 | // Make a StringBuffer object for original.
57 | StringBuffer modifiedString = new StringBuffer(original);
58 |
59 | // Find the first occurrence of findstring.
60 | int index = modifiedString.indexOf(findString);
61 |
62 | while (index != -1) {
63 | // Replace this occurrence of the substring.
64 | modifiedString.replace(index, (index + findString.length()),
65 | replaceString);
66 |
67 | // Find the next occurrence of findString.
68 | index = modifiedString.indexOf(findString);
69 | }
70 |
71 | // Return the modified string.
72 | return modifiedString.toString();
73 |
74 | }
75 |
76 | public static String arrayToString(char[] array) {
77 | String newString = String.valueOf(array);
78 | return newString;
79 | }
80 | }
81 |
82 | public static void main(String[] args) {
83 |
84 | String phrase = "the dog jumped over the fence";
85 |
86 | // Number of words in a string
87 | System.out.println("Number of words in \"" + phrase + "\" is "
88 | + StringOperations.wordCount(phrase));
89 |
90 | // Show most frequent char
91 | System.out.println("Most frequently occurring character: "
92 | + StringOperations.mostFrequent(phrase));
93 |
94 | // Replace string
95 | System.out.println("Modified phrase replacing the with that: "
96 | + StringOperations.replaceSubString(phrase, "the", "that"));
97 |
98 | // Convert an array to a string and display it.
99 | String arrayToString = StringOperations.arrayToString(phrase
100 | .toCharArray());
101 | System.out.println("Converted arrayToString: " + arrayToString);
102 | }
103 |
104 | }
105 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/MorseCodeConverter.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 | import java.util.Scanner;
6 |
7 | /**
8 | * This java exercises will demonstrate how to convert a letter to Morse code.
9 | *
10 | * @author Justin Musgrove
11 | * @see Morse code converter
12 | *
13 | */
14 | public class MorseCodeConverter {
15 |
16 | static Map LETTER_TO_MORSE_CODE = new HashMap<>();
17 |
18 | static {
19 | LETTER_TO_MORSE_CODE.put(" ", " ");
20 | LETTER_TO_MORSE_CODE.put(",", "--..--");
21 | LETTER_TO_MORSE_CODE.put(".", ".-.-.-");
22 | LETTER_TO_MORSE_CODE.put("?", "..--..");
23 | LETTER_TO_MORSE_CODE.put("0", "-----");
24 | LETTER_TO_MORSE_CODE.put("1", ".----");
25 | LETTER_TO_MORSE_CODE.put("2", "..---");
26 | LETTER_TO_MORSE_CODE.put("3", "...--");
27 | LETTER_TO_MORSE_CODE.put("4", "....-");
28 | LETTER_TO_MORSE_CODE.put("5", ".....");
29 | LETTER_TO_MORSE_CODE.put("6", "-....");
30 | LETTER_TO_MORSE_CODE.put("7", "--...");
31 | LETTER_TO_MORSE_CODE.put("8", "---..");
32 | LETTER_TO_MORSE_CODE.put("9", "----.");
33 | LETTER_TO_MORSE_CODE.put("A", ".-");
34 | LETTER_TO_MORSE_CODE.put("B", "-...");
35 | LETTER_TO_MORSE_CODE.put("C", "-.-.");
36 | LETTER_TO_MORSE_CODE.put("D", "-..");
37 | LETTER_TO_MORSE_CODE.put("E", ".");
38 | LETTER_TO_MORSE_CODE.put("F", "..-.");
39 | LETTER_TO_MORSE_CODE.put("G", "--.");
40 | LETTER_TO_MORSE_CODE.put("H", "....");
41 | LETTER_TO_MORSE_CODE.put("I", "..");
42 | LETTER_TO_MORSE_CODE.put("J", ".---");
43 | LETTER_TO_MORSE_CODE.put("K", "-.-");
44 | LETTER_TO_MORSE_CODE.put("L", ".-..");
45 | LETTER_TO_MORSE_CODE.put("M", "--");
46 | LETTER_TO_MORSE_CODE.put("N", "-.");
47 | LETTER_TO_MORSE_CODE.put("O", "---");
48 | LETTER_TO_MORSE_CODE.put("P", ".--.");
49 | LETTER_TO_MORSE_CODE.put("Q", "--.-");
50 | LETTER_TO_MORSE_CODE.put("R", ".-.");
51 | LETTER_TO_MORSE_CODE.put("S", "...");
52 | LETTER_TO_MORSE_CODE.put("T", "-");
53 | LETTER_TO_MORSE_CODE.put("U", "..-");
54 | LETTER_TO_MORSE_CODE.put("V", "...-");
55 | LETTER_TO_MORSE_CODE.put("W", ".--");
56 | LETTER_TO_MORSE_CODE.put("X", "-..-");
57 | LETTER_TO_MORSE_CODE.put("Y", "-.--");
58 | LETTER_TO_MORSE_CODE.put("Z", "--..");
59 | }
60 |
61 | public static void main(String[] args) {
62 |
63 | // Create a Scanner object for keyboard input.
64 | Scanner keyboard = new Scanner(System.in);
65 |
66 | // Get a string from the user.
67 | System.out.println("Enter a string to convert to Morse code.");
68 | System.out.print("> ");
69 |
70 | // String to hold the user's input.
71 | String userInput = keyboard.nextLine();
72 |
73 | // close keyboard
74 | keyboard.close();
75 |
76 | // split string into array and upper case
77 | userInput
78 | .toUpperCase()
79 | .chars()
80 | .forEach(
81 | s -> System.out.println(LETTER_TO_MORSE_CODE
82 | .get(Character.toString((char) s))));
83 | }
84 | }
85 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/Mortgage.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * This java exercises will demonstrate how to computes loan payments.
7 | *
8 | * @author Justin Musgrove
9 | * @see Mortgage
10 | *
11 | */
12 | public class Mortgage {
13 |
14 | public static void main(String[] args) {
15 |
16 | Scanner console = new Scanner(System.in);
17 |
18 | // ask user for input
19 | System.out.println("This program computes monthly loan payments.");
20 | System.out.print("Enter loan amount: ");
21 | double loanAmount = console.nextDouble();
22 |
23 | System.out.print("Enter number of years: ");
24 | int years = console.nextInt();
25 |
26 | System.out.print("Enter interest rate: ");
27 | double interestRate = console.nextDouble();
28 | System.out.println();
29 |
30 | //close stream
31 | console.close();
32 |
33 | // call method for payment
34 | double payment = calculateMonthlyPayment(loanAmount, years, interestRate);
35 |
36 | // output result
37 | System.out.println("Your loan payment = $" + (int) payment);
38 | }
39 |
40 | /**
41 | * Method should calculate monthly payment
42 | *
43 | * @param loanAmount
44 | * @param years
45 | * @param interestRate
46 | * @return payment
47 | */
48 | static double calculateMonthlyPayment(double loanAmount, int years,
49 | double interestRate) {
50 |
51 | int months = 12 * years;
52 | double c = interestRate / 12.0 / 100.0;
53 | double payment = loanAmount * c * Math.pow(1 + c, months)
54 | / (Math.pow(1 + c, months) - 1);
55 |
56 | return payment;
57 | }
58 |
59 | }
60 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/NameSearch.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.io.IOException;
4 | import java.nio.file.Files;
5 | import java.nio.file.Path;
6 | import java.nio.file.Paths;
7 | import java.util.List;
8 | import java.util.Scanner;
9 | import java.util.stream.Collectors;
10 |
11 | /**
12 | * This java exercises will demonstrate how to search for name within a file.
13 | *
14 | * @author Justin Musgrove
15 | * @see Name search
16 | */
17 | public class NameSearch {
18 |
19 | public static void main(String args[]) throws IOException {
20 |
21 | Path boysNamesPath = Paths
22 | .get("src/main/resources/com/levelup/java/exercises/beginner/BoyNames.txt")
23 | .toAbsolutePath();
24 |
25 | Path girlsNamePath = Paths
26 | .get("src/main/resources/com/levelup/java/exercises/beginner/GirlNames.txt")
27 | .toAbsolutePath();
28 |
29 | // read boys names
30 | List boysNames = Files.lines(boysNamesPath).collect(
31 | Collectors.toList());
32 |
33 | // ready girls names
34 | List girlsNames = Files.lines(girlsNamePath).collect(
35 | Collectors.toList());
36 |
37 | // ask user get name from user
38 | String searchName = getNamesFromUser();
39 |
40 | displaySearchResults(searchName, boysNames, girlsNames);
41 |
42 | }
43 |
44 | /**
45 | * Method should ask user to input a name
46 | *
47 | * @return name to be searched
48 | */
49 | public static String getNamesFromUser() {
50 |
51 | // Create a Scanner object to read input.
52 | Scanner keyboard = new Scanner(System.in);
53 |
54 | // Get a name from user
55 | System.out.println("Popular Name Search");
56 | System.out.print("Enter a name: ");
57 |
58 | String name = keyboard.nextLine();
59 |
60 | keyboard.close();
61 |
62 | return name;
63 | }
64 |
65 | /**
66 | * Method should determine and output if a name is contained with in lists
67 | * passed
68 | *
69 | * @param searchName
70 | * @param boysNames
71 | * @param girlsNames
72 | * @throws IOException
73 | */
74 | public static void displaySearchResults(String searchName,
75 | List boysNames, List girlsNames) throws IOException {
76 |
77 | System.out.println("\nHere are the search results:\n");
78 |
79 | boolean popularBoyName = boysNames.stream().anyMatch(
80 | p -> p.equalsIgnoreCase(searchName));
81 | boolean popularGirlName = girlsNames.stream().anyMatch(
82 | p -> p.equalsIgnoreCase(searchName));
83 |
84 | // Display the results.
85 | if (popularBoyName) {
86 | System.out.println(searchName + " is a popular boy's name.");
87 | }
88 | if (popularGirlName) {
89 | System.out.println(searchName + " is a popular girl's name.");
90 | }
91 | if (!popularBoyName && !popularGirlName) {
92 | System.out.println(searchName + " is not a popular name.");
93 | }
94 | }
95 |
96 | }
97 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/NumberIsPrime.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.Scanner;
4 |
5 | import org.apache.commons.math3.primes.Primes;
6 |
7 | /**
8 | * This program demonstrates how to find prime numbers.
9 | *
10 | * @author Justin Musgrove
11 | * @see Is number prime
12 | */
13 | public class NumberIsPrime {
14 |
15 | public static void main(String[] args) {
16 |
17 | String message;
18 | int number;
19 | Scanner keyboard = new Scanner(System.in);
20 |
21 | // Get the number to check
22 | System.out.print("Enter a number: ");
23 | number = keyboard.nextInt();
24 |
25 | // Determine whether it is prime or not.
26 | if (isPrime(number)) {
27 | message = " is a prime number.";
28 | } else {
29 | message = " is not a prime number.";
30 | }
31 |
32 | // ouput results
33 | System.out.println("The number " + number
34 | + message);
35 |
36 | keyboard.close();
37 | }
38 |
39 | /**
40 | * The isPrime method determines whether a number is prime.
41 | *
42 | * {@link Primes} is a utility method found in apache commons.
43 | * In this instance I am wrapping this method but isn't necessary.
44 | *
45 | * @param num
46 | * The number to check.
47 | * @return true if the number is prime, false otherwise.
48 | */
49 | public static boolean isPrime(int number) {
50 | return Primes.isPrime(number);
51 | }
52 |
53 | }
54 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/PalindromeDiscoverer.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * This program demonstrates a solution to the to the palindrome exercise
7 | *
8 | * @author Justin Musgrove
9 | * @see Palindrome discoverer
10 | *
11 | */
12 | public class PalindromeDiscoverer {
13 |
14 | public static void main(String[] args) {
15 |
16 | // Create a Scanner object for keyboard input.
17 | Scanner keyboard = new Scanner(System.in);
18 |
19 | // Get user input
20 | System.out.print("Enter a word or phrase: ");
21 | String userInput = keyboard.nextLine();
22 |
23 | boolean isAPalindrome = isPalindrome(userInput);
24 |
25 | if (isAPalindrome) {
26 | System.out.print("The word or phrase is a palindrome");
27 | } else {
28 | System.out.print("Sorry the word or phrase is NOT a palindrome");
29 | }
30 |
31 | keyboard.close();
32 | }
33 |
34 |
35 | /**
36 | * Method should return true if a string is identified as a palindrome.
37 | * There are many ways to do a palindrome check, this is just one of them.
38 | * If you are performing checks on very, very long strings you may want to
39 | * consider another algorithm.
40 | *
41 | * @param str
42 | * @return
43 | */
44 | public static boolean isPalindrome(String str) {
45 |
46 | if (str.length() <= 1) {
47 | return true;
48 | } else {
49 | String toCompare = str.replaceAll("\\s+","");
50 |
51 | StringBuffer buffer = new StringBuffer(toCompare);
52 | String reversedString = buffer.reverse().toString();
53 |
54 | if (reversedString.equalsIgnoreCase(toCompare)) {
55 | return true;
56 | } else {
57 | return false;
58 | }
59 | }
60 | }
61 |
62 | }
63 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/PasswordVerifier.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.Scanner;
4 | import java.util.function.Predicate;
5 |
6 | /**
7 | * This program demonstrates a solution to the password verifier.
8 | *
9 | * @author Justin Musgrove
10 | * @see Password Verifier
11 | *
12 | */
13 | public class PasswordVerifier {
14 |
15 | static class Password {
16 |
17 | private String password;
18 |
19 | public Password(String password) {
20 | this.password = password;
21 | }
22 |
23 | public boolean isValid() {
24 | return hasUpperCase.and(hasLowerCase).and(hasLengthOfSix)
25 | .and(hasAtLeastOneDigit).test(this.password);
26 | }
27 |
28 | Predicate hasAtLeastOneDigit = new Predicate() {
29 | @Override
30 | public boolean test(String t) {
31 | return t.chars().anyMatch(Character::isDigit);
32 | }
33 | };
34 |
35 | Predicate hasLengthOfSix = new Predicate() {
36 | @Override
37 | public boolean test(String t) {
38 | return t.length() >=6 ? true : false;
39 | }
40 | };
41 |
42 | Predicate hasLowerCase = new Predicate() {
43 | @Override
44 | public boolean test(String t) {
45 | return t.chars().anyMatch(Character::isLowerCase);
46 | }
47 | };
48 |
49 | Predicate hasUpperCase = new Predicate() {
50 | @Override
51 | public boolean test(String t) {
52 | return t.chars().anyMatch(Character::isUpperCase);
53 | }
54 | };
55 | }
56 |
57 | public static void main(String[] args) {
58 |
59 | // Create a Scanner object for keyboard input.
60 | Scanner keyboard = new Scanner(System.in);
61 |
62 | // get password to verify logic
63 | System.out.print("Enter a string to represent password: ");
64 | String input = keyboard.nextLine();
65 |
66 | // close keyboard
67 | keyboard.close();
68 |
69 | // validate
70 | Password password = new Password(input);
71 |
72 | boolean validPassword = password.isValid();
73 |
74 | System.out.println("The password of " + input + "is "
75 | + (validPassword ? " valid password " : "an invalid password"));
76 |
77 | }
78 |
79 | }
80 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/PenniesForPay.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.text.DecimalFormat;
4 | import java.util.ArrayList;
5 | import java.util.List;
6 | import java.util.Scanner;
7 |
8 | /**
9 | * This program demonstrates pennies for pay.
10 | *
11 | * @author Justin Musgrove
12 | * @see Pennies
14 | * for pay
15 | */
16 | public class PenniesForPay {
17 |
18 | public static void main(String[] args) {
19 |
20 | int maxDays; // number of days
21 |
22 | // Create a Scanner object for keyboard input.
23 | Scanner keyboard = new Scanner(System.in);
24 |
25 | // Get the number of days.
26 | System.out.print("Days of work? ");
27 | maxDays = keyboard.nextInt();
28 |
29 | // Validate the input.
30 | while (maxDays < 1) {
31 | System.out.print("The number of days must be greater than 0.\n"
32 | + "Re-enter the number of days: ");
33 | maxDays = keyboard.nextInt();
34 | }
35 | // close scanner
36 | keyboard.close();
37 |
38 | // Display the report header.
39 | System.out.println("Day\t\tPennies Earned");
40 |
41 | // call getPay to calculate total amount of pay
42 | // passing in a start penny of 1 and
43 | // max days entered by user
44 | List pay = getPay(maxDays, 1);
45 | for (int x = 0; x < pay.size(); x++) {
46 | System.out.println((x + 1) + "\t\t" + pay.get(x));
47 | }
48 |
49 | // Create a DecimalFormat object to format output.
50 | DecimalFormat dollar = new DecimalFormat("#,##0.00");
51 |
52 | // calculate totalPay with java 8
53 | double totalPay = pay.stream().mapToDouble(Double::doubleValue).sum();
54 | System.out.println("Total pay: $" + dollar.format(totalPay / 100.0));
55 | }
56 |
57 | /**
58 | * The method will calculate the pay period based on parameters passed.
59 | *
60 | * @param numberOfDays
61 | * @param pennies
62 | * @return list of pay period
63 | */
64 | public static List getPay(int totalNumberOfDays, int pennies) {
65 |
66 | List pay = new ArrayList<>();
67 |
68 | // add first day
69 | pay.add(new Double(1));
70 |
71 | int day = 1;
72 | while (day < totalNumberOfDays) {
73 | pay.add(new Double(pennies *= 2));
74 | day++;
75 | }
76 |
77 | return pay;
78 | }
79 |
80 | }
81 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/PhoneBookArrayList.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * This java exercise will demonstrate a solution to the phone book will array list problem.
8 | *
9 | * @author Justin Musgrove
10 | * @see Phone book arraylist
11 | */
12 | public class PhoneBookArrayList {
13 |
14 | public class PhoneBookEntry {
15 |
16 | public PhoneBookEntry(String name, String phoneNumber) {
17 | super();
18 | this.name = name;
19 | this.phoneNumber = phoneNumber;
20 | }
21 |
22 | private String name;
23 | private String phoneNumber;
24 | public String getName() {
25 | return name;
26 | }
27 | public void setName(String name) {
28 | this.name = name;
29 | }
30 | public String getPhoneNumber() {
31 | return phoneNumber;
32 | }
33 | public void setPhoneNumber(String phoneNumber) {
34 | this.phoneNumber = phoneNumber;
35 | }
36 |
37 | @Override
38 | public String toString() {
39 | return "PhoneBookEntry [name=" + name + ", phoneNumber="
40 | + phoneNumber + "]";
41 | }
42 |
43 | }
44 |
45 |
46 | public static void main(String[] args) {
47 |
48 | PhoneBookArrayList bookArrayList = new PhoneBookArrayList();
49 |
50 | PhoneBookEntry entry1 = bookArrayList.new PhoneBookEntry("Jack", "920-456-2345");
51 | PhoneBookEntry entry2 = bookArrayList.new PhoneBookEntry("Sam", "868-344-2345");
52 | PhoneBookEntry entry3 = bookArrayList.new PhoneBookEntry("George", "414-234-2345");
53 | PhoneBookEntry entry4 = bookArrayList.new PhoneBookEntry("Dimo", "608-049-2345");
54 | PhoneBookEntry entry5 = bookArrayList.new PhoneBookEntry("Jenny", "971-456-2345");
55 |
56 | List phoneNumberEntries = new ArrayList<>();
57 | phoneNumberEntries.add(entry1);
58 | phoneNumberEntries.add(entry2);
59 | phoneNumberEntries.add(entry3);
60 | phoneNumberEntries.add(entry4);
61 | phoneNumberEntries.add(entry5);
62 |
63 | phoneNumberEntries.forEach(number -> System.out.println(number));
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/PigLatin.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.List;
4 | import java.util.Scanner;
5 | import java.util.function.Function;
6 | import java.util.stream.Collectors;
7 |
8 | import com.google.common.base.Splitter;
9 | import com.google.common.collect.Lists;
10 |
11 | /**
12 | * This java example will demonstrate how to convert a phrase to pig latin.
13 | *
14 | * @author Justin Musgrove
15 | * @see Pig latin translator
16 | */
17 | public class PigLatin {
18 |
19 | public static void main(String[] args) {
20 |
21 | // Create a Scanner object for keyboard input.
22 | Scanner keyboard = new Scanner(System.in);
23 |
24 | // Ask user to enter a string to translate
25 | System.out.println("Enter a string to translate to Pig Latin.");
26 | System.out.print("> ");
27 | String input = keyboard.nextLine();
28 |
29 | // close the keyboard
30 | keyboard.close();
31 |
32 | List elementsInString = Lists.newArrayList(Splitter.on(" ")
33 | .split(input));
34 |
35 | Function swapFirstLastChar = new Function() {
36 | @Override
37 | public String apply(String s) {
38 | if (s.length() <= 1) {
39 | return s;
40 | } else {
41 | return s.substring(1, s.length()) + s.charAt(0);
42 | }
43 | }
44 | };
45 |
46 | List translatedString = elementsInString.stream()
47 | .map(String::trim).map(String::toUpperCase)
48 | .map(swapFirstLastChar).map((String s) -> {
49 | return s + "AY";
50 | }).collect(Collectors.toList());
51 |
52 |
53 | System.out.println("Translated sentence is: "
54 | + String.join(" ", translatedString));
55 | }
56 | }
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/PresentValue.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * This java example will demonstrate a solution to the present value exercise.
7 | *
8 | * @author Justin Musgrove
9 | * @see Present value
10 | */
11 | public class PresentValue {
12 |
13 | public static void main(String[] args) {
14 |
15 | // Scanner object to get input
16 | Scanner keyboard = new Scanner(System.in);
17 |
18 | // Desired future value
19 | System.out.print("Future value? ");
20 | double futureValue = keyboard.nextDouble();
21 |
22 | // Annual interest rate.
23 | System.out.print("Annual interest rate? ");
24 | double annualInterestRate = keyboard.nextDouble();
25 |
26 | // Number of years investment to draw interest
27 | System.out.print("Number of years? ");
28 | int numberOfYears = keyboard.nextInt();
29 |
30 | // close scanner
31 | keyboard.close();
32 |
33 | double present = calculatePresentValue(futureValue, annualInterestRate,
34 | numberOfYears);
35 |
36 | // Display the result to user
37 | System.out.println("You need to invest $" + present);
38 | }
39 |
40 | /**
41 | * Method should calculate present value
42 | *
43 | * @param futureValue
44 | * @param annualInterestRate
45 | * @param numberOfYears
46 | * @return present value
47 | */
48 | public static double calculatePresentValue(double futureValue,
49 | double annualInterestRate, int numberOfYears) {
50 |
51 | return futureValue / Math.pow((1 + annualInterestRate), numberOfYears);
52 | }
53 | }
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/RestaurantBill.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * This java example will demonstrate calculating the restaurant bill
7 | * which should include tax and tip.
8 | *
9 | * @author Justin Musgrove
10 | * @see Restaurant bill
11 | *
12 | */
13 | public class RestaurantBill {
14 |
15 | private static double TAX_RATE = 0.0675;
16 | private static double TIP_PERCENT = .15;
17 |
18 |
19 | public static void main(String[] args) {
20 |
21 | // Variables
22 | double mealCharge; // To hold the meal charge
23 | double tax; // To hold the amount of tax
24 | double tip; // To hold the tip amount
25 | double total; // To hold the total charge
26 |
27 | // Create a Scanner object for keyboard input.
28 | Scanner keyboard = new Scanner(System.in);
29 |
30 | // Get the charge for the meal.
31 | System.out.print("Enter the charge for the meal: ");
32 | mealCharge = keyboard.nextDouble();
33 |
34 | // Calculate the tax.
35 | tax = calculateTax (mealCharge);
36 |
37 | // Calculate the tip.
38 | tip = calculateTip (mealCharge);
39 |
40 | // Calculate the total.
41 | total = calculateTotal (mealCharge, tax, tip);
42 |
43 | // Display the results.
44 | System.out.println("Meal Charge: $" + mealCharge);
45 | System.out.println("Tax: $" + tax);
46 | System.out.println("Tip: $" + tip);
47 | System.out.println("Total: $" + total);
48 |
49 | keyboard.close();
50 | }
51 |
52 |
53 | /**
54 | * Method should calculate tax based on meal charge and tax rate
55 | * @param mealCharge
56 | * @return
57 | */
58 | static double calculateTax (double mealCharge) {
59 | return mealCharge * TAX_RATE;
60 | }
61 |
62 | /**
63 | * Method should calculate tip based on meal charge and tip %.
64 | *
65 | * @param mealCharge
66 | * @return
67 | */
68 | static double calculateTip (double mealCharge) {
69 | return mealCharge * TIP_PERCENT;
70 | }
71 |
72 | /**
73 | * Method should calculate total due based on method parameters.
74 | *
75 | * @param mealCharge
76 | * @param tax
77 | * @param tip
78 | * @return
79 | */
80 | static double calculateTotal (double mealCharge, double tax, double tip) {
81 | return mealCharge + tax + tip;
82 | }
83 |
84 |
85 | }
86 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/RockPaperScissorsGame.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import static com.google.common.base.Preconditions.checkNotNull;
4 |
5 | import java.util.Random;
6 | import java.util.Scanner;
7 |
8 | /**
9 | * This program demonstrates a solution to the rock, paper, scissor game.
10 | *
11 | * @author Justin Musgrove
12 | * @see Rock paper scissors game
13 | */
14 | public class RockPaperScissorsGame {
15 |
16 | public static void main(String[] args) {
17 |
18 | String computer;
19 | String user;
20 | Scanner keyboard = new Scanner(System.in);
21 |
22 | // Play the game as long as there is a tie.
23 | do {
24 | // Get the computer's choice.
25 | computer = computerChoice();
26 |
27 | // Get the user's choice.
28 | user = userChoice(keyboard);
29 |
30 | // Determine the winner.
31 | String output = determineWinner(computer, user);
32 | System.out.println(output);
33 |
34 | } while (user.equalsIgnoreCase(computer));
35 |
36 | keyboard.close();
37 | }
38 |
39 | /**
40 | * Method should generate a random number and then return the
41 | * computers choice.
42 | *
43 | * @return The computer's choice of "rock", "paper", or "scissors".
44 | */
45 | public static String computerChoice() {
46 |
47 | // Create a Random object.
48 | Random rand = new Random();
49 |
50 | // Generate a random number in the range of
51 | // 1 through 3.
52 | int num = rand.nextInt(3) + 1;
53 |
54 | // Return the computer's choice.
55 | return getChoice (num) ;
56 | }
57 |
58 | /**
59 | * Method will return null if an invalid choice is given.
60 | * 1=rock, 2=paper, or 3=scissors.
61 | *
62 | * @param number
63 | * @return string type
64 | *
65 | */
66 | public static String getChoice (int number) {
67 |
68 | String choice;
69 |
70 | switch (number) {
71 | case 1:
72 | choice = "rock";
73 | break;
74 | case 2:
75 | choice = "paper";
76 | break;
77 | case 3:
78 | choice = "scissors";
79 | break;
80 | default:
81 | choice = null;
82 | }
83 |
84 | return choice;
85 | }
86 |
87 | /**
88 | * Method should return the user's choice.
89 | *
90 | * @return The user's choice of "rock", "paper", or "scissors".
91 | */
92 | public static String userChoice(Scanner keyboard) {
93 |
94 | // Ask the user for input
95 | System.out.print("Enter 1 - rock, 2 - paper, or 3 - scissors: ");
96 |
97 | int userChoice = keyboard.nextInt();
98 |
99 | String play = getChoice (userChoice);
100 |
101 | // Validate the choice.
102 | while (play == null) {
103 |
104 | System.out.print("Enter 1 - rock, 2 - paper, or 3 - scissors: ");
105 | userChoice = keyboard.nextInt();
106 | play = getChoice (userChoice);
107 | }
108 |
109 | // Return the user's choice.
110 | return play;
111 | }
112 |
113 | /**
114 | * The determineWinner method returns the output based on parameters
115 | *
116 | * @param computerChoice The computer's choice.
117 | * @param userChoice The user's choice.
118 | */
119 | public static String determineWinner (String computerChoice, String userChoice) {
120 |
121 | checkNotNull(computerChoice, "computer must have a choice");
122 | checkNotNull(userChoice, "user must have a choice");
123 |
124 | String output;
125 |
126 | output = "The computer's choice was " + computerChoice + ".\n";
127 | output += "The user's choice was " + userChoice + ".\n\n";
128 |
129 | // check logic
130 | if (userChoice.equalsIgnoreCase("rock")) {
131 | if (computerChoice.equalsIgnoreCase("scissors"))
132 | output += "Rock beats scissors.\nThe user wins!";
133 | else if (computerChoice.equalsIgnoreCase("paper"))
134 | output += "Paper beats rock.\nThe computer wins!";
135 | else
136 | output += "The game is tied!\nPlay again...";
137 | } else if (userChoice.equalsIgnoreCase("paper")) {
138 | if (computerChoice.equalsIgnoreCase("scissors"))
139 | output += "Scissors beats paper.\nThe computer wins!";
140 | else if (computerChoice.equalsIgnoreCase("rock"))
141 | output += "Paper beats rock.\nThe user wins!";
142 | else
143 | output += "The game is tied!\nPlay again...";
144 | } else if (userChoice.equalsIgnoreCase("scissors")) {
145 | if (computerChoice.equalsIgnoreCase("rock"))
146 | output += "Rock beats scissors.\nThe computer wins!";
147 | else if (computerChoice.equalsIgnoreCase("paper"))
148 | output += "Scissors beats paper.\nThe user wins!";
149 | else
150 | output += "The game is tied!\nPlay again...";
151 | }
152 |
153 | return output;
154 | }
155 |
156 | }
157 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/RomanNumerals.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * This program demonstrates how to convert number to Roman numeral.
7 | *
8 | * @author Justin Musgrove
9 | * @see Roman Numerals Converter
10 | */
11 | public class RomanNumerals {
12 |
13 | public static void main(String[] args) {
14 |
15 | // Create a Scanner object for keyboard input.
16 | Scanner keyboard = new Scanner(System.in);
17 |
18 | // Get a number from the user.
19 | System.out.print("Enter a number in the range of 1 - 10: ");
20 |
21 | int number = keyboard.nextInt(); // User inputed number
22 |
23 | //close stream
24 | keyboard.close();
25 |
26 | // Get Roman numeral.
27 | String romanNumerals = convertNumberToRomanNumeral(number);
28 |
29 | // Output to user
30 | System.out.println(romanNumerals);
31 | }
32 |
33 | /**
34 | * Method should return a Roman numeral that represents
35 | * the number input.
36 | *
37 | * @param number
38 | * @return String that represents a Roman numeral
39 | */
40 | static String convertNumberToRomanNumeral(Integer number) {
41 |
42 | switch (number) {
43 | case 1:
44 | return "I";
45 |
46 | case 2:
47 | return "II";
48 |
49 | case 3:
50 | return "III";
51 |
52 | case 4:
53 | return "IV";
54 |
55 | case 5:
56 | return "V";
57 |
58 | case 6:
59 | return "VI";
60 |
61 | case 7:
62 | return "VII";
63 |
64 | case 8:
65 | return "VIII";
66 |
67 | case 9:
68 | return "IX";
69 |
70 | case 10:
71 | return "X";
72 |
73 | default:
74 | return "Invalid number.";
75 |
76 | }
77 | }
78 |
79 | }
80 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/RunningTheRace.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.Collections;
4 | import java.util.Comparator;
5 | import java.util.List;
6 | import java.util.Scanner;
7 |
8 | import com.google.common.base.Objects;
9 | import com.google.common.collect.Lists;
10 |
11 | /**
12 | * This program demonstrates a solution to the to the Running the race exercise.
13 | *
14 | * @author Justin Musgrove
15 | * @see Running the race
16 | *
17 | */
18 | public class RunningTheRace {
19 |
20 | class Runner {
21 |
22 | private String name;
23 | private double timeToCompleteRace;
24 |
25 | public Runner(String name, double timeToCompleteRace) {
26 | super();
27 | this.name = name;
28 | this.timeToCompleteRace = timeToCompleteRace;
29 | }
30 |
31 | @Override
32 | public String toString() {
33 |
34 | return Objects.toStringHelper(this)
35 | .add("name", name)
36 | .add("time to complete", timeToCompleteRace)
37 | .toString();
38 | }
39 |
40 | public String getName() {
41 | return name;
42 | }
43 |
44 | public double getTimeToCompleteRace() {
45 | return timeToCompleteRace;
46 | }
47 |
48 | }
49 |
50 | public static void main(String[] args) {
51 |
52 | List race = Lists.newArrayList();
53 |
54 | // Create a Scanner object for keyboard input.
55 | Scanner keyboard = new Scanner(System.in);
56 |
57 | String name;
58 | double raceTime;
59 |
60 | RunningTheRace runningTheRace = new RunningTheRace();
61 |
62 | // Get the user's selection.
63 | do {
64 | System.out.print("Enter name: ");
65 | name = keyboard.next();
66 |
67 | System.out.print("Enter race time: (-1 to exit): ");
68 | raceTime = keyboard.nextDouble();
69 |
70 | if (!name.equals("-1")) {
71 | race.add(runningTheRace.new Runner(name, raceTime));
72 | }
73 |
74 | } while (!name.equals("-1"));
75 |
76 | // sort collection based on time
77 | Collections.sort(race, byRaceTime);
78 |
79 | // output runners in race
80 | System.out.println("Name" + "\t" + "Time");
81 | System.out.println("---------------------");
82 |
83 | for (Runner runner : race) {
84 | System.out.println(runner.getName() + "\t" + runner.getTimeToCompleteRace());
85 | }
86 |
87 | keyboard.close();
88 | }
89 |
90 |
91 | /**
92 | * Comparator byRaceTime
93 | */
94 | static Comparator byRaceTime = new Comparator() {
95 | public int compare(Runner left, Runner right) {
96 | return Double.compare(left.getTimeToCompleteRace(), right.getTimeToCompleteRace()) ; // use your logic
97 | }
98 | };
99 |
100 |
101 | }
102 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/SalesAnalysis.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.io.IOException;
4 | import java.nio.file.Path;
5 | import java.nio.file.Paths;
6 | import java.util.ArrayList;
7 | import java.util.Arrays;
8 | import java.util.DoubleSummaryStatistics;
9 | import java.util.List;
10 |
11 | /**
12 | * This java exercises will demonstrate how to find statistics on sales
13 | * information.
14 | *
15 | * @author Justin Musgrove
16 | * @see Sales
18 | * analysis data
19 | *
20 | */
21 | public class SalesAnalysis {
22 |
23 | public static void main(String[] args) throws IOException {
24 |
25 | Path salesDataPath = Paths
26 | .get("src/main/resources/com/levelup/java/exercises/beginner/SalesData.txt")
27 | .toAbsolutePath();
28 |
29 | //read all lines into a list of strings
30 | List fileByLines = java.nio.file.Files
31 | .readAllLines(salesDataPath);
32 |
33 | //convert each string into a DoubleSummaryStatistics object
34 | List weeksSummary = new ArrayList<>();
35 | for (String row : fileByLines) {
36 | // split on comma, map to double
37 | weeksSummary.add(Arrays.stream(row.split(","))
38 | .mapToDouble(Double::valueOf).summaryStatistics());
39 | }
40 |
41 | displayWeeklyStats(weeksSummary);
42 | displaySummaryResults(weeksSummary);
43 |
44 | }
45 |
46 | public static void displayWeeklyStats(
47 | List weeksSummary) {
48 |
49 | for (int x = 0; x < weeksSummary.size(); x++) {
50 | DoubleSummaryStatistics weekStat = weeksSummary.get(x);
51 |
52 | System.out.println("Week #" + x + " sales: $" + weekStat.getSum());
53 | System.out.println("Average daily sales for week #" + x + ": $"
54 | + weekStat.getAverage());
55 | }
56 | }
57 |
58 | public static void displaySummaryResults(
59 | List weeksSummary) {
60 |
61 | System.out.println("Total sales for all weeks: $"
62 | + weeksSummary.stream().mapToDouble(p -> p.getSum()).sum());
63 |
64 | System.out.println("Average weekly sales: $"
65 | + weeksSummary.stream().mapToDouble(p -> p.getSum()).average()
66 | .getAsDouble());
67 |
68 | System.out.println("The highest sales was $"
69 | + weeksSummary.stream().mapToDouble(p -> p.getSum()).max()
70 | .getAsDouble());
71 |
72 | System.out.println("The lowest sales were made during "
73 | + weeksSummary.stream().mapToDouble(p -> p.getSum()).min()
74 | .getAsDouble());
75 |
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/SavingsAccountClass.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.text.DecimalFormat;
4 | import java.util.Scanner;
5 |
6 | /**
7 | * This java example will provide a solution to the Savings Account class
8 | * exercise.
9 | *
10 | * @author Justin Musgrove
11 | * @see SavingsAccount
13 | * class
14 | */
15 | public class SavingsAccountClass {
16 |
17 | /**
18 | * Savings account class
19 | *
20 | */
21 | class SavingsAccount {
22 |
23 | private double accountBalance;
24 | private double annualInterestRate;
25 | private double lastAmountOfInterestEarned;
26 |
27 | public SavingsAccount(double balance, double interestRate) {
28 |
29 | accountBalance = balance;
30 | annualInterestRate = interestRate;
31 | lastAmountOfInterestEarned = 0.0;
32 | }
33 |
34 | public void withdraw(double withdrawAmount) {
35 | accountBalance -= withdrawAmount;
36 | }
37 |
38 | public void deposit(double depositAmount) {
39 | accountBalance += depositAmount;
40 | }
41 |
42 | public void addInterest() {
43 |
44 | // Get the monthly interest rate.
45 | double monthlyInterestRate = annualInterestRate / 12;
46 |
47 | // Calculate the last amount of interest earned.
48 | lastAmountOfInterestEarned = monthlyInterestRate * accountBalance;
49 |
50 | // Add the interest to the balance.
51 | accountBalance += lastAmountOfInterestEarned;
52 | }
53 |
54 | public double getAccountBalance() {
55 | return accountBalance;
56 | }
57 |
58 | public double getAnnualInterestRate() {
59 | return annualInterestRate;
60 | }
61 |
62 | public double getLastAmountOfInterestEarned() {
63 | return lastAmountOfInterestEarned;
64 | }
65 | }
66 |
67 | public static void main(String args[]) {
68 |
69 | // Create a Scanner object for keyboard input.
70 | Scanner keyboard = new Scanner(System.in);
71 |
72 | // Ask user to enter starting balance
73 | System.out.print("How much money is in the account?: ");
74 | double startingBalance = keyboard.nextDouble();
75 |
76 | // Ask user for annual interest rate
77 | System.out.print("Enter the annual interest rate:");
78 | double annualInterestRate = keyboard.nextDouble();
79 |
80 | // Create class
81 | SavingsAccountClass savingAccountClass = new SavingsAccountClass();
82 | SavingsAccount savingsAccount = savingAccountClass.new SavingsAccount(
83 | startingBalance, annualInterestRate);
84 |
85 | // Ask how long account was opened
86 | System.out.print("How long has the account been opened? ");
87 | double months = keyboard.nextInt();
88 |
89 | double montlyDeposit;
90 | double monthlyWithdrawl;
91 | double interestEarned = 0.0;
92 | double totalDeposits = 0;
93 | double totalWithdrawn = 0;
94 |
95 | // For each month as user to enter information
96 | for (int i = 1; i <= months; i++) {
97 |
98 | // Get deposits for month
99 | System.out.print("Enter amount deposited for month: " + i + ": ");
100 | montlyDeposit = keyboard.nextDouble();
101 | totalDeposits += montlyDeposit;
102 |
103 | // Add deposits savings account
104 | savingsAccount.deposit(montlyDeposit);
105 |
106 | // Get withdrawals for month
107 | System.out.print("Enter amount withdrawn for " + i + ": ");
108 | monthlyWithdrawl = keyboard.nextDouble();
109 | totalWithdrawn += monthlyWithdrawl;
110 |
111 | // Subtract the withdrawals
112 | savingsAccount.withdraw(monthlyWithdrawl);
113 |
114 | // Add the monthly interest
115 | savingsAccount.addInterest();
116 |
117 | // Accumulate the amount of interest earned.
118 | interestEarned += savingsAccount.getLastAmountOfInterestEarned();
119 | }
120 |
121 | // close keyboard
122 | keyboard.close();
123 |
124 | // Create a DecimalFormat object for formatting output.
125 | DecimalFormat dollar = new DecimalFormat("#,##0.00");
126 |
127 | // Display the totals and the balance.
128 | System.out.println("Total deposited: $" + dollar.format(totalDeposits));
129 | System.out
130 | .println("Total withdrawn: $" + dollar.format(totalWithdrawn));
131 | System.out
132 | .println("Interest earned: $" + dollar.format(interestEarned));
133 | System.out.println("Ending balance: $"
134 | + dollar.format(savingsAccount.getAccountBalance()));
135 | }
136 |
137 | }
138 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/SlotMachineSimulation.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import static com.google.common.base.Preconditions.checkElementIndex;
4 |
5 | import java.text.DecimalFormat;
6 | import java.util.List;
7 | import java.util.Random;
8 | import java.util.Scanner;
9 |
10 | import com.google.common.base.Joiner;
11 | import com.google.common.collect.HashMultiset;
12 | import com.google.common.collect.ImmutableMultiset;
13 | import com.google.common.collect.Lists;
14 | import com.google.common.collect.Multiset;
15 | import com.google.common.collect.Multiset.Entry;
16 | import com.google.common.collect.Multisets;
17 |
18 | /**
19 | * This program demonstrates a solution to the slot machine simulation.
20 | *
21 | * @author Justin Musgrove
22 | * @see Slot machine simulation
23 | *
24 | */
25 | public class SlotMachineSimulation {
26 |
27 | static String[] reels = { "Cherries", "Oranges", "Plums", "Bells", "Melons", "Bars" };
28 | static int numberOfReels = 3;
29 |
30 | public static void main(String[] args) {
31 |
32 | char playAgain;
33 | double amountBet = 0;
34 | double totalWon = 0;
35 | DecimalFormat dollar = new DecimalFormat("#,##0.00");
36 |
37 |
38 | // Create a Scanner object for keyboard input.
39 | Scanner keyboard = new Scanner(System.in);
40 |
41 | // Play the slot machine once, and repeat the game as long
42 | // as the user confirms they want to continue to play.
43 | do {
44 | System.out.println("Welcome to the Slot Machine Simulation.");
45 |
46 | // Get the amount the user wants to bet.
47 | System.out.print("\nEnter the amount you would like to bet: $");
48 | amountBet = keyboard.nextDouble();
49 |
50 | // Skip a line.
51 | System.out.println();
52 |
53 | // generate random reels
54 | List reels = Lists.newArrayList();
55 | for (int x = 0; x < numberOfReels; x++) {
56 | reels.add(getRandomReel());
57 | }
58 |
59 | // display reels
60 | System.out.println(Joiner.on("--").join(reels));
61 |
62 | // determine the payout percentage
63 | int payoutPercentage = determinePayOutPercentage(reels);
64 |
65 | // calcuate the amount won
66 | double amountWon = payoutPercentage * amountBet;
67 |
68 | // keep running total of amount won
69 | totalWon += amountWon;
70 |
71 | // Display the amount won.
72 | System.out.println("\nYou win $" + dollar.format(amountWon));
73 |
74 | // Prompt the user to play again.
75 | System.out.println("\nWould you like to play again?");
76 | System.out.print("Enter Y for yes or N for no: ");
77 | String input = keyboard.next(); // Read a string.
78 | playAgain = input.charAt(0); // Get the first character.
79 |
80 | } while (playAgain == 'Y' || playAgain == 'y');
81 |
82 | // Display the totals.
83 | System.out.println("You won a total of $" + dollar.format(totalWon));
84 |
85 | keyboard.close();
86 |
87 | }
88 |
89 | /**
90 | * Method should return the number of times an occurrence of a reel
91 | *
92 | * @param reels
93 | * @return
94 | */
95 | static int determinePayOutPercentage(List reels) {
96 |
97 | Multiset reelCount = HashMultiset.create();
98 | reelCount.addAll(reels);
99 |
100 | // order the number of elements by the higest
101 | ImmutableMultiset highestCountFirst = Multisets.copyHighestCountFirst(reelCount);
102 |
103 | int count = 0;
104 | for (Entry entry : highestCountFirst.entrySet()) {
105 | count = entry.getCount();
106 | break;
107 | }
108 | return count;
109 | }
110 |
111 | /**
112 | * Method should get a reel randomly
113 | *
114 | * @return string representing reel
115 | */
116 | static String getRandomReel() {
117 |
118 | // Create a Random object, set seed to the number of elements in array
119 | Random randomNumber = new Random();
120 | return getReel(randomNumber.nextInt(reels.length));
121 | }
122 |
123 | /**
124 | * Method should return reel based on index of array 0 - cherries 1 -
125 | * oranges 2 - plums 3 - bells 4 - melons 5 - bars
126 | *
127 | * @param element
128 | * @throws IndexOutOfBoundsException
129 | * if {@code index} is negative or is not less than 6
130 | * @return reel
131 | */
132 | static String getReel(int index) {
133 |
134 | checkElementIndex(index, reels.length);
135 |
136 | return reels[index];
137 |
138 | }
139 |
140 | }
141 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/SortedNames.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.Collections;
4 | import java.util.List;
5 | import java.util.Scanner;
6 |
7 | import com.google.common.collect.Lists;
8 |
9 | /**
10 | * This program demonstrates a solution to the to Sorted names.
11 | *
12 | * @author Justin Musgrove
13 | * @see Sorted names
14 | *
15 | */
16 | public class SortedNames {
17 |
18 | public static void main(String[] args) {
19 |
20 | List names = Lists.newArrayList();
21 |
22 | // Create a Scanner object for keyboard input.
23 | Scanner keyboard = new Scanner(System.in);
24 | String name;
25 |
26 | // Get the user's selection.
27 | do {
28 | System.out.print("Enter name (-1 to exit): ");
29 | name = keyboard.next();
30 | if (!name.equals("-1")) {
31 | names.add(name);
32 | }
33 |
34 | } while (!name.equals("-1"));
35 |
36 | // sort collected names
37 | Collections.sort(names);
38 |
39 | // output names
40 | for (String name2 : names) {
41 | System.out.println(name2);
42 | }
43 |
44 | keyboard.close();
45 | }
46 |
47 | }
48 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/SpeedOfSound.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.Scanner;
4 |
5 | import static com.google.common.base.Preconditions.*;
6 |
7 | /**
8 | * This program demonstrates a solution to the to the speed of sound exercise.
9 | *
10 | * @author Justin Musgrove
11 | * @see Speed of sound
12 | *
13 | */
14 | public class SpeedOfSound {
15 |
16 | public static void main(String[] args) {
17 |
18 | double distance = 0.0; // Distance
19 | String medium; // To hold "air", "water", or "steel"
20 |
21 | // Create a Scanner object for keyboard input.
22 | Scanner keyboard = new Scanner(System.in);
23 |
24 | // Get the user's medium of choice.
25 | System.out.print("Enter one of the following: air, water, or steel: ");
26 | medium = keyboard.nextLine();
27 |
28 | // Get the distance.
29 | System.out.print("Enter the distance the sound wave will travel: ");
30 | distance = keyboard.nextDouble();
31 |
32 | // calculate
33 | double distanceTravelled = getDistanceTraveledInSeconds(medium, distance);
34 |
35 | // display output
36 | System.out.println("It will take " + distanceTravelled + " seconds.");
37 |
38 | keyboard.close();
39 | }
40 |
41 | /**
42 | * Method should return the distance traveled in seconds.
43 | *
44 | * @param medium
45 | * @param distance
46 | * @throws NullPointerException when medium is null
47 | *
48 | * @return distance traveled
49 | */
50 | static double getDistanceTraveledInSeconds(String medium, double distance) {
51 |
52 | checkNotNull(medium);
53 |
54 | if (medium.equalsIgnoreCase("air")) {
55 | return distance / 1100.0;
56 | } else {
57 | if (medium.equalsIgnoreCase("water")) {
58 | return distance / 4900.0;
59 | } else {
60 | if (medium.equalsIgnoreCase("steel")) {
61 | return distance / 16400.0;
62 | }
63 | }
64 | }
65 | return 0.0;
66 | }
67 |
68 | }
69 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/SquareDisplay.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * This java exercises will solve for the square display problem.
7 | *
8 | * @author Justin Musgrove
9 | * @see Square display
10 | *
11 | */
12 | public class SquareDisplay {
13 |
14 | public static void main(String[] args) {
15 |
16 | // Create a Scanner object for keyboard input.
17 | Scanner keyboard = new Scanner(System.in);
18 |
19 | // Get a number from the user.
20 | System.out.print("Enter a number between 1-15: ");
21 | int number = keyboard.nextInt();
22 |
23 | //validate users input
24 | validateNumber(keyboard, number);
25 |
26 | //produce matrix
27 | outputMatrix("X", number);
28 |
29 | //close scanner
30 | keyboard.close();
31 |
32 | }
33 |
34 | /**
35 | * Method should validate a input number and continue to ask if the number
36 | * is now within range
37 | *
38 | * @param keyboard
39 | * @param number
40 | */
41 | static void validateNumber(Scanner keyboard, int number) {
42 |
43 | // Validate the input.
44 | while (number < 1 || number > 15) {
45 | // Get a number from the user.
46 | System.out.println("Sorry, that's an invalid number.");
47 | System.out.print("Enter an integer in the range of 1-15: ");
48 | number = keyboard.nextInt();
49 | }
50 | }
51 |
52 | /**
53 | * Method should output a row/column of char specified
54 | *
55 | * @param charToOutput
56 | * @param number
57 | */
58 | static void outputMatrix(String charToOutput, int number) {
59 |
60 | // display square made of char
61 | for (int row = 0; row < number; row++) {
62 |
63 | // display row
64 | for (int column = 0; column < number; column++) {
65 | System.out.print(charToOutput);
66 | }
67 |
68 | // Advance to the next line.
69 | System.out.println();
70 | }
71 | }
72 |
73 | }
74 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/StockCommission.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | /**
4 | * This program demonstrates how to calculate stock commission.
5 | *
6 | * @author Justin Musgrove
7 | * @see Stock
9 | * commission
10 | *
11 | */
12 | public class StockCommission {
13 |
14 | // Constants
15 | private static final int NUMBER_OF_SHARES = 600;
16 | private static final double STOCK_PRICE = 21.77;
17 | private static final double COMMISSION_PERCENT = 0.02;
18 |
19 | public static void main(String[] args) {
20 |
21 | // Calculate the stock cost.
22 | double stockCost = calculateStockCost(STOCK_PRICE, NUMBER_OF_SHARES);
23 |
24 | // Calculate the commission.
25 | double commission = calculateCommission(stockCost, COMMISSION_PERCENT);
26 |
27 | // Calculate the total.
28 | double total = stockCost + commission;
29 |
30 | // Display the results.
31 | System.out.println("Stock cost: $" + stockCost);
32 | System.out.println("Commission: $" + commission);
33 | System.out.println("Total: $" + total);
34 | }
35 |
36 | /**
37 | * Method should calculate total stock cost
38 | *
39 | * @param stockPrice
40 | * @param commission
41 | * @return stock cost
42 | */
43 | static double calculateStockCost(double stockPrice, double commission) {
44 | return stockPrice * commission;
45 | }
46 |
47 | /**
48 | * Method should calculate commission of a stock
49 | *
50 | * @param stockCost
51 | * @param commissionPercent
52 | * @return commission
53 | */
54 | static double calculateCommission(double stockCost, double commissionPercent) {
55 | return stockCost * commissionPercent;
56 | }
57 |
58 | }
59 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/StockTransaction.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | /**
4 | * This java example will demonstrate a stock transaction program.
5 | *
6 | * @author Justin Musgrove
7 | * @see Stock transaction
8 | *
9 | */
10 | public class StockTransaction {
11 |
12 | // Named constants
13 | static final int NUM_SHARES = 1000; // Number of shares
14 | static final double PURCHASE_PRICE = 32.87; // Purchase price per share
15 | static final double SELLING_PRICE = 33.92; // Selling price per share
16 | static final double BROKER_COMM_RATE = 0.02; // Broker commission rate
17 |
18 |
19 | public static void main(String[] args) {
20 |
21 | double stockPurchase = stockPurchasePrice (NUM_SHARES, PURCHASE_PRICE);
22 |
23 | double purchaseComm = brokersCommission (stockPurchase, BROKER_COMM_RATE) ;
24 |
25 | double amountPaid = totalAmountPaid (stockPurchase, purchaseComm);
26 |
27 | double stockSale = stockSale(NUM_SHARES, SELLING_PRICE);
28 |
29 | double sellingComm = sellingCommission(NUM_SHARES, SELLING_PRICE, BROKER_COMM_RATE);
30 |
31 | double amountRecieved = totalAmountRecieved (stockSale, sellingComm);
32 |
33 | double profitOrLoss = profitOrLoss (amountRecieved, amountPaid);
34 |
35 | // Display the results.
36 | System.out.println("You paid $" + stockPurchase + " for the stock.");
37 | System.out.println("You paid his broker a commission of $"
38 | + purchaseComm + " on the purchase.");
39 | System.out.println("So, You paid a total of $" + amountPaid + "\n");
40 |
41 | System.out.println("You sold the stock for $" + stockSale);
42 | System.out.println("You paid his broker a commission of $"
43 | + sellingComm + " on the sale.");
44 | System.out.println("So, You recieved a total of $" + amountRecieved
45 | + "\n");
46 | System.out.println("You's profit or loss: $" + profitOrLoss);
47 | }
48 |
49 |
50 |
51 | /**
52 | * Method should calculate the purchase price of stock not including
53 | * brokers fees.
54 | *
55 | * @param numberOfShares
56 | * @param purchasePrice
57 | * @return stock purchase price
58 | */
59 | static double stockPurchasePrice (double numberOfShares, double purchasePrice) {
60 | return numberOfShares * purchasePrice;
61 | }
62 |
63 | /**
64 | * Method should calculate the brokers commission
65 | * @param stockPurchase
66 | * @param brokersCommissionRate
67 | * @return brokers commission
68 | */
69 | static double brokersCommission (double stockPurchase, double brokersCommissionRate) {
70 | return stockPurchase * brokersCommissionRate;
71 | }
72 |
73 | /**
74 | * Method should calculate the total amount paid which is
75 | * sum of stock purchase price and the commission of the sale.
76 | *
77 | * @param stockPurchase
78 | * @param purchaseComm
79 | * @return total amount paid
80 | */
81 | static double totalAmountPaid (double stockPurchase, double purchaseComm) {
82 | return stockPurchase + purchaseComm;
83 | }
84 |
85 | /**
86 | * Method should calculate the amount of stock sale
87 | *
88 | * @param numberOfShares
89 | * @param sellingPrice
90 | * @return stock sale amount
91 | */
92 | static double stockSale (double numberOfShares, double sellingPrice) {
93 | return numberOfShares * sellingPrice;
94 | }
95 |
96 | /**
97 | * Method should calculate the commission on a sale
98 | *
99 | * @param numberOfShares
100 | * @param sellingPrice
101 | * @param brokersCommissionRate
102 | * @return commission from the sale
103 | */
104 | static double sellingCommission (double numberOfShares, double sellingPrice, double brokersCommissionRate) {
105 | return (numberOfShares * sellingPrice) * brokersCommissionRate;
106 | }
107 |
108 | /**
109 | * Method should calculate the total amount received from the sale. This amount
110 | * is the total sale of the stock - the selling commission.
111 | *
112 | * @param stockSale
113 | * @param sellingCommission
114 | * @return total amount received from sale
115 | */
116 | static double totalAmountRecieved (double stockSale, double sellingCommission) {
117 | return stockSale - sellingCommission;
118 | }
119 |
120 | /**
121 | * Method should calculate a profit or loss. If a profit was made, the amount
122 | * will be positive. If a loss was incurred, the amount will be negative.
123 | *
124 | * @param amountRecieved
125 | * @param amountPaid
126 | * @return profit OR loss
127 | */
128 | static double profitOrLoss (double amountRecieved, double amountPaid) {
129 | return amountRecieved - amountPaid;
130 | }
131 |
132 | }
133 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/StringManipulator.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * This program demonstrates basic string manipulation.
7 | *
8 | * @author Justin Musgrove
9 | * @see String manipulator
10 | */
11 | public class StringManipulator {
12 |
13 | public static void main(String[] args) {
14 |
15 | // Create a Scanner object for keyboard input.
16 | Scanner keyboard = new Scanner(System.in);
17 |
18 | // Get the user's favorite city.
19 | System.out.print("Enter the name of your favorite city: ");
20 |
21 | String city = keyboard.nextLine();
22 |
23 | // close stream
24 | keyboard.close();
25 |
26 | // Display the number of characters.
27 | System.out.println("Number of characters: " + city.length());
28 |
29 | // Display the city name in uppercase characters.
30 | System.out.println(city.toUpperCase());
31 |
32 | // Display the city name in lowercase characters.
33 | System.out.println(city.toLowerCase());
34 |
35 | // Display the first character in the city name.
36 | System.out.println(city.charAt(0));
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/SumOfDigits.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.DoubleSummaryStatistics;
4 | import java.util.Scanner;
5 | import java.util.stream.Stream;
6 |
7 | /**
8 | * This java exercise will demonstrate summing digits from a string
9 | *
10 | * @author Justin Musgrove
11 | * @see Sum
13 | * of digits in string
14 | *
15 | */
16 | public class SumOfDigits {
17 |
18 | public static void main(String[] args) {
19 |
20 | // Create a Scanner object for keyboard input.
21 | Scanner keyboard = new Scanner(System.in);
22 |
23 | // Get a string of digits.
24 | System.out.print("Enter a string of digits: ");
25 | String input = keyboard.nextLine();
26 |
27 | // close keyboard
28 | keyboard.close();
29 |
30 | DoubleSummaryStatistics summaryStats = Stream.of(input.split(""))
31 | .mapToDouble(Double::valueOf).summaryStatistics();
32 |
33 | System.out.println("The sum of numbers " + summaryStats.getSum());
34 | System.out.println("The highest digit is " + summaryStats.getMax());
35 | System.out.println("The lowest digit is " + summaryStats.getMin());
36 | }
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/TestAverage.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.Scanner;
6 |
7 | /**
8 | * This java exercise will demonstrate asking the user for
9 | * test scores and find the average.
10 | *
11 | * @author Justin Musgrove
12 | * @see Find test average
13 | *
14 | */
15 | public class TestAverage {
16 |
17 | public static void main(String[] args) {
18 |
19 | List scores = new ArrayList();
20 |
21 | // Create a Scanner object for keyboard input.
22 | Scanner keyboard = new Scanner(System.in);
23 |
24 | // Get the user's selection.
25 | System.out.print("Enter test score (-1 to exit): ");
26 | double selection = keyboard.nextDouble();
27 |
28 | // Validate the user's selection.
29 | while (selection != -1) {
30 | System.out.print("Enter test score (-1 to exit): ");
31 | selection = keyboard.nextDouble();
32 | if (selection != -1) {
33 | scores.add(selection);
34 | }
35 | }
36 |
37 | // output list of scores
38 | System.out.println("The scores entered: " + scores);
39 |
40 | // output average
41 | System.out.print("The average: " + averageScore(scores));
42 |
43 | keyboard.close();
44 | }
45 |
46 | /**
47 | * Method should return the average score
48 | *
49 | * @param scores
50 | * @return double
51 | */
52 | static double averageScore(List scores) {
53 | double sum = 0;
54 | if (!scores.isEmpty()) {
55 | for (Double score : scores) {
56 | sum += score;
57 | }
58 | return sum / scores.size();
59 | }
60 | return sum;
61 | }
62 |
63 |
64 | }
65 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/TestScoresClassProgram.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * This java exercise will show a solution to the test scores class exercise.
7 | *
8 | * @author Justin Musgrove
9 | * @see TestScores class program
10 | */
11 | public class TestScoresClassProgram {
12 |
13 | public class TestScores {
14 |
15 | private double score1;
16 | private double score2;
17 | private double score3;
18 |
19 | public TestScores(double score1, double score2, double score3) {
20 | this.score1 = score1;
21 | this.score2 = score2;
22 | this.score3 = score3;
23 | }
24 |
25 | public void setScore1(double score) {
26 | score1 = score;
27 | }
28 |
29 | public void setScore2(double score) {
30 | score2 = score;
31 | }
32 |
33 | public void setScore3(double score) {
34 | score3 = score;
35 | }
36 |
37 | public double getScore1() {
38 | return score1;
39 | }
40 |
41 | public double getScore2() {
42 | return score2;
43 | }
44 |
45 | public double getScore3() {
46 | return score3;
47 | }
48 |
49 | public double getAverageScore() {
50 | return (score1 + score2 + score3) / 3;
51 | }
52 | }
53 |
54 | public static void main(String[] args) {
55 |
56 | double test1;
57 | double test2;
58 | double test3;
59 |
60 | // Create a scanner for keyboard input.
61 | Scanner keyboard = new Scanner(System.in);
62 |
63 | System.out.print("Enter test score: ");
64 | test1 = keyboard.nextDouble();
65 |
66 | System.out.print("Enter test score: ");
67 | test2 = keyboard.nextDouble();
68 |
69 | System.out.print("Enter test score: ");
70 | test3 = keyboard.nextDouble();
71 |
72 | // close scanner
73 | keyboard.close();
74 |
75 | TestScoresClassProgram classProgram = new TestScoresClassProgram();
76 | TestScores scores = classProgram.new TestScores(test1, test2, test3);
77 |
78 | // Display average
79 | System.out.println("The average test score: "
80 | + scores.getAverageScore());
81 | }
82 |
83 | }
84 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/TossingCoinsForADollar.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.Random;
4 |
5 | /**
6 | * This java example will demonstrate a solution for tossing coins for a dollar.
7 | *
8 | * @author Justin Musgrove
9 | * @see Tossing Coins For A Dollar
10 | */
11 | public class TossingCoinsForADollar {
12 |
13 | class Coin {
14 |
15 | private String sideUp;
16 |
17 | /**
18 | * Default constructor
19 | */
20 | public Coin() {
21 | // initialize sideUp
22 | toss();
23 | }
24 |
25 | /**
26 | * This method will simulate the tossing of a coin. It should set the
27 | * sideUp field to either "heads" or "tails".
28 | */
29 | public void toss() {
30 |
31 | Random rand = new Random();
32 |
33 | // Get a random value, 0 or 1.
34 | int value = rand.nextInt(2);
35 |
36 | if (value == 0) {
37 | this.sideUp = "heads";
38 | } else {
39 | this.sideUp = "tails";
40 | }
41 | }
42 |
43 | /**
44 | *
45 | * @return The side of the coin facing up.
46 | */
47 | public String getSideUp() {
48 | return sideUp;
49 | }
50 | }
51 |
52 | // Constants
53 | static final double PLAY_TO = 1.00;
54 | static final double TWENTY_FIVE_CENTS = 0.25;
55 | static final double TEN_CENTS = 0.10;
56 | static final double FIVE_CENTS = 0.05;
57 |
58 | public static void main(String args[]) {
59 |
60 | TossingCoinsForADollar coinTossSimulator = new TossingCoinsForADollar();
61 |
62 | Coin quarter = coinTossSimulator.new Coin();
63 | Coin dime = coinTossSimulator.new Coin();
64 | Coin nickel = coinTossSimulator.new Coin();
65 |
66 | double balance = 0;
67 |
68 | System.out.println("Ready? Set? Go!");
69 |
70 | // Play the game while the balance
71 | // is less than the PLAY_TO constant
72 | while (balance < PLAY_TO) {
73 |
74 | // toss each coin
75 | quarter.toss();
76 | dime.toss();
77 | nickel.toss();
78 |
79 | // add appropriate value to balance
80 | if (isHeadsUp(quarter)) {
81 | balance += TWENTY_FIVE_CENTS;
82 | }
83 |
84 | if (isHeadsUp(dime)) {
85 | balance += TEN_CENTS;
86 | }
87 |
88 | if (isHeadsUp(nickel)) {
89 | balance += FIVE_CENTS;
90 | }
91 | }
92 |
93 | // Display balance to user
94 | System.out.printf("Balance: $%,1.2f\n", balance);
95 |
96 | // Display whether or not they won based
97 | // on the program requirement
98 | if (balance == PLAY_TO) {
99 | System.out.println("You win!");
100 | } else {
101 | System.out.println("You did not win.");
102 | }
103 | }
104 |
105 | /**
106 | * Method will determine if the coin is heads up
107 | *
108 | * @param coin
109 | * @return true if coin is heads up
110 | */
111 | public static boolean isHeadsUp(Coin coin) {
112 |
113 | if (coin.getSideUp().equals("heads")) {
114 | return true;
115 | } else {
116 | return false;
117 | }
118 | }
119 |
120 | }
121 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/TrivaGame.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.io.IOException;
4 | import java.nio.file.Files;
5 | import java.nio.file.Paths;
6 | import java.util.List;
7 | import java.util.OptionalInt;
8 | import java.util.Random;
9 | import java.util.Scanner;
10 | import java.util.function.Function;
11 | import java.util.stream.Collectors;
12 |
13 | import com.google.common.base.Splitter;
14 |
15 | /**
16 | * This java example will demonstrate a solution to the triva game.
17 | *
18 | * @author Justin Musgrove
19 | * @see Triva game
20 | */
21 | public class TrivaGame {
22 |
23 | List questions;
24 |
25 | TrivaGame() throws IOException {
26 | questions = readQuestions();
27 | }
28 |
29 | /**
30 | * This class represents question object
31 | */
32 | class Question {
33 |
34 | private String question;
35 | private List possibleAnswers;
36 | private int answer;
37 |
38 | @Override
39 | public String toString() {
40 | return "Question [question=" + question + ", possibleAnswers="
41 | + possibleAnswers + ", answer=" + answer + "]";
42 | }
43 | }
44 |
45 | /**
46 | * This class represents player object
47 | */
48 | class Player {
49 |
50 | int playerNumber;
51 | int points;
52 |
53 | }
54 |
55 | /**
56 | * Function will accept a string based on the following format and transform
57 | * it into a Question object
58 | */
59 | Function mapLineToQuestion = new Function() {
60 |
61 | public Question apply(String line) {
62 |
63 | Question question = new Question();
64 |
65 | List questionPieces = Splitter.on("|").trimResults()
66 | .omitEmptyStrings().splitToList(line);
67 |
68 | question.question = questionPieces.get(0);
69 | question.possibleAnswers = Splitter.on(",").trimResults()
70 | .omitEmptyStrings().splitToList(questionPieces.get(1));
71 | question.answer = Integer.parseInt(questionPieces.get(2));
72 |
73 | return question;
74 | }
75 | };
76 |
77 | /**
78 | * Method will read each line of a file then mapping it to a question
79 | * object.
80 | *
81 | * @return
82 | * @throws IOException
83 | */
84 | public List readQuestions() throws IOException {
85 |
86 | List questions = Files
87 | .lines(Paths
88 | .get("src/main/resources/com/levelup/java/exercises/beginner/trivia.txt"))
89 | .map(mapLineToQuestion).collect(Collectors.toList());
90 |
91 | return questions;
92 | }
93 |
94 | public List getQuestions() {
95 | return questions;
96 | }
97 |
98 | /**
99 | * Method should generate random number based total number of questions
100 | *
101 | * @param numberOfQuestions
102 | * @return
103 | */
104 | public static int getRandomQuestionNumber(int numberOfQuestions) {
105 |
106 | Random random = new Random();
107 | OptionalInt questionNumber = random.ints(1, numberOfQuestions)
108 | .findFirst();
109 |
110 | return questionNumber.getAsInt();
111 | }
112 |
113 | /**
114 | * Method should display a question passed
115 | *
116 | * @param q
117 | * @param playerNum
118 | */
119 | public static void displayQuestion(Question q, int playerNum) {
120 |
121 | // Display the player number.
122 | System.out.println("Question for player #" + playerNum);
123 | System.out.println("------------------------");
124 |
125 | // Display the question.
126 | System.out.println(q.question);
127 | for (int i = 0; i < q.possibleAnswers.size(); i++) {
128 | System.out.println((i + 1) + ". " + q.possibleAnswers.get(i));
129 | }
130 | }
131 |
132 | /**
133 | * Method will output summary stats and declare a winner
134 | *
135 | * @param players
136 | */
137 | public static void showGameResults(Player[] players) {
138 |
139 | // Display the stats.
140 | System.out.println("Game Over!");
141 | System.out.println("---------------------");
142 | System.out.println("Player 1's points: " + players[0].points);
143 | System.out.println("Player 2's points: " + players[1].points);
144 |
145 | // Declare the winner.
146 | if (players[0].points > players[1].points) {
147 | System.out.println("Player 1 wins!");
148 | } else if (players[1].points > players[0].points) {
149 | System.out.println("Player 2 wins!");
150 | } else {
151 | System.out.println("It's a TIE!");
152 | }
153 |
154 | }
155 |
156 | static int NUMBER_OF_PLAYERS = 2;
157 | static int NUMBER_OF_CHANCES = 5;
158 |
159 | public static void main(String args[]) throws IOException {
160 |
161 | // Initiate trivia game
162 | TrivaGame trivaGame = new TrivaGame();
163 |
164 | Scanner keyboard = new Scanner(System.in);
165 |
166 | // how many total questions exist
167 | int numberOfQuestions = trivaGame.getQuestions().size();
168 |
169 | // create array of players
170 | Player[] players = { trivaGame.new Player(), trivaGame.new Player() };
171 |
172 | // Play the game for each player defined and number of chances
173 | for (int x = 0; x < players.length; x++) {
174 |
175 | Player currentPlayer = players[x];
176 |
177 | for (int i = 0; i < NUMBER_OF_CHANCES; i++) {
178 |
179 | // get random question
180 | Question question = trivaGame.getQuestions().get(
181 | getRandomQuestionNumber(numberOfQuestions));
182 |
183 | displayQuestion(question, x + 1);
184 |
185 | // ask user to enter question
186 | System.out.print("Enter the number of the correct answer: ");
187 | int currentAnswer = keyboard.nextInt();
188 |
189 | // answer logic
190 | if (currentAnswer == question.answer) {
191 | // The player's chosen answer is correct.
192 | System.out.println("Correct!\n");
193 | currentPlayer.points += 1;
194 | } else {
195 |
196 | // The player chose the wrong answer.
197 | System.out.println("Sorry, that is incorrect. The correct "
198 | + "answer is " + question.answer + ".\n");
199 | }
200 |
201 | }
202 | }
203 |
204 | // close keyboard
205 | keyboard.close();
206 |
207 | // display game results
208 | showGameResults(players);
209 | }
210 |
211 | }
212 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/TwoDimensionalArrayOperations.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | /**
4 | * This java exercise demonstrates a solution for the 2D array operations.
5 | *
6 | * @author Justin Musgrove
7 | * @see 2D array operations
8 | */
9 | public class TwoDimensionalArrayOperations {
10 |
11 | public static double getTotal(double[][] array) {
12 | double total = 0;
13 |
14 | for (int row = 0; row < array.length; row++) {
15 | for (int col = 0; col < array[row].length; col++) {
16 | total += array[row][col];
17 | }
18 | }
19 |
20 | return total;
21 | }
22 |
23 | public static double getAverage(double[][] array) {
24 | return getTotal(array) / getElementCount(array);
25 | }
26 |
27 | public static double getRowTotal(double[][] array, int row) {
28 | double total = 0;
29 |
30 | for (int col = 0; col < array[row].length; col++) {
31 | total += array[row][col];
32 | }
33 |
34 | return total;
35 | }
36 |
37 | public static double getColumnTotal(double[][] array, int col) {
38 | double total = 0;
39 |
40 | for (int row = 0; row < array.length; row++) {
41 | total += array[row][col];
42 | }
43 |
44 | return total;
45 | }
46 |
47 | public static double getHighestInRow(double[][] array, int row) {
48 | double highest = array[row][0];
49 |
50 | for (int col = 1; col < array[row].length; col++) {
51 | if (array[row][col] > highest) {
52 | highest = array[row][col];
53 | }
54 | }
55 | return highest;
56 | }
57 |
58 | public static double getLowestInRow(double[][] array, int row) {
59 | double lowest = array[row][0];
60 |
61 | for (int col = 1; col < array[row].length; col++) {
62 | if (array[row][col] < lowest) {
63 | lowest = array[row][col];
64 | }
65 | }
66 | return lowest;
67 | }
68 |
69 | public static int getElementCount(double[][] array) {
70 | int count = 0;
71 |
72 | for (int row = 0; row < array.length; row++) {
73 | count += array[row].length;
74 | }
75 | return count;
76 | }
77 |
78 | public static void main(String[] args) {
79 |
80 | double[][] studentTestScores = { { 65.5, 54.43, 23.54, 99.5 },
81 | { 33.4, 22.55, 54.66, 11.12 } };
82 |
83 | // Process the double array.
84 | System.out.println("Total : " + getTotal(studentTestScores));
85 | System.out.println("Average : " + getAverage(studentTestScores));
86 |
87 | System.out.println("Total of row 0 : "
88 | + getRowTotal(studentTestScores, 0));
89 | System.out.println("Total of row 1 : "
90 | + getRowTotal(studentTestScores, 1));
91 |
92 | System.out.println("Total of col 0 : "
93 | + getColumnTotal(studentTestScores, 0));
94 | System.out.println("Total of col 1 : "
95 | + getColumnTotal(studentTestScores, 2));
96 |
97 | System.out.println("Highest in row 0 : "
98 | + getHighestInRow(studentTestScores, 0));
99 | System.out.println("Highest in row 1 : "
100 | + getHighestInRow(studentTestScores, 1));
101 |
102 | System.out.println("Lowest in row 0 : "
103 | + getLowestInRow(studentTestScores, 0));
104 | System.out.println("Lowest in row 1 : "
105 | + getLowestInRow(studentTestScores, 1));
106 |
107 | }
108 |
109 | }
110 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/UppercaseFileConverter.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.io.IOException;
4 | import java.net.URISyntaxException;
5 | import java.nio.file.Path;
6 | import java.nio.file.Paths;
7 | import java.nio.file.StandardOpenOption;
8 | import java.util.List;
9 | import java.util.Scanner;
10 | import java.util.stream.Collectors;
11 |
12 | /**
13 | * This java example will demonstrate a solution for the upper case file
14 | * converter exercise.
15 | *
16 | * @author Justin Musgrove
17 | * @see Uppercase
19 | * File Converter
20 | */
21 | public class UppercaseFileConverter {
22 |
23 | public static void main(String[] args) throws IOException,
24 | URISyntaxException {
25 |
26 | // Create a Scanner object for keyboard input.
27 | Scanner keyboard = new Scanner(System.in);
28 |
29 | // Ask user for file name
30 | System.out.print("Enter the input file name: ");
31 | String fileToRead = keyboard.nextLine();
32 |
33 | // Ask user for output file name
34 | System.out.print("Enter the output file name: ");
35 | String outputFileName = keyboard.nextLine();
36 |
37 | // Find the path of file in class path
38 | String fileLocation = getFileLocation(fileToRead);
39 |
40 | // read all lines into file
41 | Path inputPath = Paths.get(fileLocation);
42 | List fileLines = java.nio.file.Files.readAllLines(inputPath);
43 |
44 | // iterate each line in file calling toUpperCase
45 | // using java 8 streams
46 | List linesToUpperCase = fileLines.stream()
47 | .map(s -> s.toUpperCase()).collect(Collectors.toList());
48 |
49 | // write to file
50 | Path outputPath = Paths.get(outputFileName);
51 | java.nio.file.Files.write(outputPath, linesToUpperCase,
52 | StandardOpenOption.CREATE, StandardOpenOption.WRITE);
53 |
54 | keyboard.close();
55 | }
56 |
57 | /**
58 | * Method will just return the location of the file in the class path
59 | *
60 | * @param fileName
61 | * @return
62 | */
63 | static String getFileLocation(String fileName) {
64 | return UppercaseFileConverter.class.getResource(fileName).getPath();
65 | }
66 |
67 | }
68 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/WordCounter.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.io.IOException;
4 | import java.util.Scanner;
5 | import java.util.StringTokenizer;
6 |
7 | /**
8 | * This java exercise demonstrates a solution for word counter exercises.
9 | *
10 | * @author Justin Musgrove
11 | * @see Word counter
12 | */
13 |
14 | public class WordCounter {
15 |
16 | public static void main(String[] args) throws IOException {
17 |
18 | // Scanner for keyboard input
19 | Scanner keyboard = new Scanner(System.in);
20 |
21 | System.out.print("Enter a string to count words: ");
22 |
23 | // Get input from user
24 | String input = keyboard.nextLine();
25 |
26 | // close keyboard
27 | keyboard.close();
28 |
29 | int numberOfWords = wordCount(input);
30 |
31 | // Call word count
32 | System.out.println("The string has " + numberOfWords + " words in it.");
33 | }
34 |
35 | /**
36 | * Word count should return the number of words contained within a string.
37 | *
38 | * @param String
39 | * @return number of words
40 | */
41 | static int wordCount(String str) {
42 | StringTokenizer strTok = new StringTokenizer(str);
43 | return strTok.countTokens();
44 | }
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/WordSeparator.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Arrays;
5 | import java.util.List;
6 | import java.util.Scanner;
7 | import java.util.stream.Collectors;
8 |
9 | /**
10 | * This java example will demonstrate how to split a word on capital letter.
11 | *
12 | * @author Justin Musgrove
13 | * @see Word
15 | * separator
16 | */
17 | public class WordSeparator {
18 |
19 | public static void main(String[] args) {
20 |
21 | // Create a Scanner object for keyboard input.
22 | Scanner keyboard = new Scanner(System.in);
23 |
24 | // Get a string from the user.
25 | System.out.println("Enter a sentence with no spaces "
26 | + "between the words and each " + "word is capitalized.");
27 | System.out.println("An example is: StopAndSmellTheRoses");
28 | System.out.print("> ");
29 |
30 | // get user input
31 | String userInput = keyboard.nextLine();
32 |
33 | // close keyboard
34 | keyboard.close();
35 |
36 | List sentenceElements = Arrays.stream(
37 | userInput.split("(?=[A-Z])")).collect(Collectors.toList());
38 |
39 | // properly format sentence
40 | List sentence = new ArrayList<>();
41 | for (int x = 0; x < sentenceElements.size(); x++) {
42 | if (x == 0) {
43 | sentence.add(sentenceElements.get(x));
44 | } else {
45 | sentence.add(sentenceElements.get(x).toLowerCase());
46 | }
47 | }
48 |
49 | System.out.println(String.join(" ", sentence));
50 | }
51 |
52 | }
53 |
--------------------------------------------------------------------------------
/src/main/java/com/levelup/java/exercises/beginner/WorldSeriesChampion.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import java.io.IOException;
4 | import java.nio.file.Files;
5 | import java.nio.file.Path;
6 | import java.nio.file.Paths;
7 | import java.util.List;
8 | import java.util.Scanner;
9 | import java.util.stream.Collectors;
10 |
11 | /**
12 | * This java exercise will demonstrate a solution to the world series champion
13 | * program.
14 | *
15 | * @author Justin Musgrove
16 | * @see Wor
18 | * l d Series Champions
19 | */
20 | public class WorldSeriesChampion {
21 |
22 | public static void main(String args[]) throws IOException {
23 |
24 | Path worldSeriesWinners = Paths
25 | .get("src/main/resources/com/levelup/java/exercises/beginner/WorldSeriesWinners.txt")
26 | .toAbsolutePath();
27 |
28 | // read all lines of file into arraylist
29 | List winners = Files.lines(worldSeriesWinners).collect(
30 | Collectors.toList());
31 |
32 | // ask user to enter a team
33 | String teamName = getTeamName();
34 |
35 | // use a stream to filter elements based on user input
36 | // count the number of elements left
37 | long numberOfWins = winners.stream()
38 | .filter(p -> p.equalsIgnoreCase(teamName)).count();
39 |
40 | // show output
41 | output(teamName, numberOfWins);
42 |
43 | }
44 |
45 | /**
46 | * This method should return a string which represents a world series
47 | * champion entered by a user.
48 | *
49 | * @return string
50 | */
51 | public static String getTeamName() {
52 |
53 | Scanner keyboard = new Scanner(System.in);
54 |
55 | System.out.println("World Series Champions");
56 | System.out.print("Enter the name of a team: ");
57 |
58 | // Return the name input by the user.
59 | String team = keyboard.nextLine();
60 |
61 | // close scanner
62 | keyboard.close();
63 |
64 | return team;
65 | }
66 |
67 | /**
68 | * This method will format the output to the user
69 | *
70 | * @param teamName
71 | * @param numberOfWins
72 | */
73 | public static void output(String teamName, long numberOfWins) {
74 |
75 | // Display the result
76 | System.out.println(teamName + " won the World Series a total of "
77 | + numberOfWins + " times.");
78 |
79 | }
80 |
81 | }
82 |
--------------------------------------------------------------------------------
/src/main/resources/com/levelup/java/exercises/beginner/BoyNames.txt:
--------------------------------------------------------------------------------
1 | Jacob
2 | Michael
3 | Joshua
4 | Matthew
5 | Daniel
6 | Christopher
7 | Andrew
8 | Ethan
9 | Joseph
10 | William
11 | Anthony
12 | David
13 | Alexander
14 | Nicholas
15 | Ryan
16 | Tyler
17 | James
18 | John
19 | Jonathan
20 | Noah
21 | Brandon
22 | Christian
23 | Dylan
24 | Samuel
25 | Benjamin
26 | Zachary
27 | Nathan
28 | Logan
29 | Justin
30 | Gabriel
31 | Jose
32 | Austin
33 | Kevin
34 | Elijah
35 | Caleb
36 | Robert
37 | Thomas
38 | Jordan
39 | Cameron
40 | Jack
41 | Hunter
42 | Jackson
43 | Angel
44 | Isaiah
45 | Evan
46 | Isaac
47 | Mason
48 | Luke
49 | Jason
50 | Gavin
51 | Jayden
52 | Aaron
53 | Connor
54 | Aiden
55 | Aidan
56 | Kyle
57 | Juan
58 | Charles
59 | Luis
60 | Adam
61 | Lucas
62 | Brian
63 | Eric
64 | Adrian
65 | Nathaniel
66 | Sean
67 | Alex
68 | Carlos
69 | Bryan
70 | Ian
71 | Owen
72 | Jesus
73 | Landon
74 | Julian
75 | Chase
76 | Cole
77 | Diego
78 | Jeremiah
79 | Steven
80 | Sebastian
81 | Xavier
82 | Timothy
83 | Carter
84 | Wyatt
85 | Brayden
86 | Blake
87 | Hayden
88 | Devin
89 | Cody
90 | Richard
91 | Seth
92 | Dominic
93 | Jaden
94 | Antonio
95 | Miguel
96 | Liam
97 | Patrick
98 | Carson
99 | Jesse
100 | Tristan
101 | Alejandro
102 | Henry
103 | Victor
104 | Trevor
105 | Bryce
106 | Jake
107 | Riley
108 | Colin
109 | Jared
110 | Jeremy
111 | Mark
112 | Caden
113 | Garrett
114 | Parker
115 | Marcus
116 | Vincent
117 | Kaleb
118 | Kaden
119 | Brady
120 | Colton
121 | Kenneth
122 | Joel
123 | Oscar
124 | Josiah
125 | Jorge
126 | Cooper
127 | Ashton
128 | Tanner
129 | Eduardo
130 | Paul
131 | Edward
132 | Ivan
133 | Preston
134 | Maxwell
135 | Alan
136 | Levi
137 | Stephen
138 | Grant
139 | Nicolas
140 | Omar
141 | Dakota
142 | Alexis
143 | George
144 | Collin
145 | Eli
146 | Spencer
147 | Gage
148 | Max
149 | Cristian
150 | Ricardo
151 | Derek
152 | Micah
153 | Brody
154 | Francisco
155 | Nolan
156 | Ayden
157 | Dalton
158 | Shane
159 | Peter
160 | Damian
161 | Jeffrey
162 | Brendan
163 | Travis
164 | Fernando
165 | Peyton
166 | Conner
167 | Andres
168 | Javier
169 | Giovanni
170 | Shawn
171 | Braden
172 | Jonah
173 | Cesar
174 | Bradley
175 | Emmanuel
176 | Manuel
177 | Edgar
178 | Erik
179 | Mario
180 | Edwin
181 | Johnathan
182 | Devon
183 | Erick
184 | Wesley
185 | Oliver
186 | Trenton
187 | Hector
188 | Malachi
189 | Jalen
190 | Raymond
191 | Gregory
192 | Abraham
193 | Elias
194 | Leonardo
195 | Sergio
196 | Donovan
197 | Colby
198 | Marco
199 | Bryson
200 | Martin
--------------------------------------------------------------------------------
/src/main/resources/com/levelup/java/exercises/beginner/Deposits.txt:
--------------------------------------------------------------------------------
1 | 100.00
2 | 124.00
3 | 78.92
4 | 37.55
5 |
--------------------------------------------------------------------------------
/src/main/resources/com/levelup/java/exercises/beginner/GirlNames.txt:
--------------------------------------------------------------------------------
1 | Emily
2 | Madison
3 | Emma
4 | Olivia
5 | Hannah
6 | Abigail
7 | Isabella
8 | Samantha
9 | Elizabeth
10 | Ashley
11 | Alexis
12 | Sarah
13 | Sophia
14 | Alyssa
15 | Grace
16 | Ava
17 | Taylor
18 | Brianna
19 | Lauren
20 | Chloe
21 | Natalie
22 | Kayla
23 | Jessica
24 | Anna
25 | Victoria
26 | Mia
27 | Hailey
28 | Sydney
29 | Jasmine
30 | Julia
31 | Morgan
32 | Destiny
33 | Rachel
34 | Ella
35 | Kaitlyn
36 | Megan
37 | Katherine
38 | Savannah
39 | Jennifer
40 | Alexandra
41 | Allison
42 | Haley
43 | Maria
44 | Kaylee
45 | Lily
46 | Makayla
47 | Brooke
48 | Mackenzie
49 | Nicole
50 | Addison
51 | Stephanie
52 | Lillian
53 | Andrea
54 | Zoe
55 | Faith
56 | Kimberly
57 | Madeline
58 | Alexa
59 | Katelyn
60 | Gabriella
61 | Gabrielle
62 | Trinity
63 | Amanda
64 | Kylie
65 | Mary
66 | Paige
67 | Riley
68 | Jenna
69 | Leah
70 | Sara
71 | Rebecca
72 | Michelle
73 | Sofia
74 | Vanessa
75 | Jordan
76 | Angelina
77 | Caroline
78 | Avery
79 | Audrey
80 | Evelyn
81 | Maya
82 | Claire
83 | Autumn
84 | Jocelyn
85 | Ariana
86 | Nevaeh
87 | Arianna
88 | Jada
89 | Bailey
90 | Brooklyn
91 | Aaliyah
92 | Amber
93 | Isabel
94 | Danielle
95 | Mariah
96 | Melanie
97 | Sierra
98 | Erin
99 | Molly
100 | Amelia
101 | Isabelle
102 | Madelyn
103 | Melissa
104 | Jacqueline
105 | Marissa
106 | Shelby
107 | Angela
108 | Leslie
109 | Katie
110 | Jade
111 | Catherine
112 | Diana
113 | Aubrey
114 | Mya
115 | Amy
116 | Briana
117 | Sophie
118 | Gabriela
119 | Breanna
120 | Gianna
121 | Kennedy
122 | Gracie
123 | Peyton
124 | Adriana
125 | Christina
126 | Courtney
127 | Daniela
128 | Kathryn
129 | Lydia
130 | Valeria
131 | Layla
132 | Alexandria
133 | Natalia
134 | Angel
135 | Laura
136 | Charlotte
137 | Margaret
138 | Cheyenne
139 | Mikayla
140 | Miranda
141 | Naomi
142 | Kelsey
143 | Payton
144 | Ana
145 | Alicia
146 | Jillian
147 | Daisy
148 | Mckenzie
149 | Ashlyn
150 | Caitlin
151 | Sabrina
152 | Summer
153 | Ruby
154 | Rylee
155 | Valerie
156 | Skylar
157 | Lindsey
158 | Kelly
159 | Genesis
160 | Zoey
161 | Eva
162 | Sadie
163 | Alexia
164 | Cassidy
165 | Kylee
166 | Kendall
167 | Jordyn
168 | Kate
169 | Jayla
170 | Karen
171 | Tiffany
172 | Cassandra
173 | Juliana
174 | Reagan
175 | Caitlyn
176 | Giselle
177 | Serenity
178 | Alondra
179 | Lucy
180 | Kiara
181 | Bianca
182 | Crystal
183 | Erica
184 | Angelica
185 | Hope
186 | Chelsea
187 | Alana
188 | Liliana
189 | Brittany
190 | Camila
191 | Makenzie
192 | Veronica
193 | Lilly
194 | Abby
195 | Jazmin
196 | Adrianna
197 | Karina
198 | Delaney
199 | Ellie
200 | Jasmin
--------------------------------------------------------------------------------
/src/main/resources/com/levelup/java/exercises/beginner/SalesData.txt:
--------------------------------------------------------------------------------
1 | 1245.67,1490.07,1679.87,2371.46,1783.92,1461.99,2059.77
2 | 2541.36,2965.88,1965.32,1845.23,7021.11,9652.74,1469.36
3 | 2513.45,1963.22,1568.35,1966.35,1893.25,1025.36,1128.36
--------------------------------------------------------------------------------
/src/main/resources/com/levelup/java/exercises/beginner/Withdrawls.txt:
--------------------------------------------------------------------------------
1 | 29.88
2 | 110.00
3 | 27.52
4 | 50.00
5 | 12.90
--------------------------------------------------------------------------------
/src/main/resources/com/levelup/java/exercises/beginner/WorldSeriesWinners.txt:
--------------------------------------------------------------------------------
1 | Boston Americans
2 | New York Giants
3 | Chicago White Sox
4 | Chicago Cubs
5 | Chicago Cubs
6 | Pittsburgh Pirates
7 | Philadelphia Athletics
8 | Philadelphia Athletics
9 | Boston Red Sox
10 | Philadelphia Athletics
11 | Boston Braves
12 | Boston Red Sox
13 | Boston Red Sox
14 | Chicago White Sox
15 | Boston Red Sox
16 | Cincinnati Reds
17 | Cleveland Indians
18 | New York Giants
19 | New York Giants
20 | New York Yankees
21 | Washington Senators
22 | Pittsburgh Pirates
23 | St. Louis Cardinals
24 | New York Yankees
25 | New York Yankees
26 | Philadelphia Athletics
27 | Philadelphia Athletics
28 | St. Louis Cardinals
29 | New York Yankees
30 | New York Giants
31 | St. Louis Cardinals
32 | Detroit Tigers
33 | New York Yankees
34 | New York Yankees
35 | New York Yankees
36 | New York Yankees
37 | Cincinnati Reds
38 | New York Yankees
39 | St. Louis Cardinals
40 | New York Yankees
41 | St. Louis Cardinals
42 | Detroit Tigers
43 | St. Louis Cardinals
44 | New York Yankees
45 | Cleveland Indians
46 | New York Yankees
47 | New York Yankees
48 | New York Yankees
49 | New York Yankees
50 | New York Yankees
51 | New York Giants
52 | Brooklyn Dodgers
53 | New York Yankees
54 | Milwaukee Braves
55 | New York Yankees
56 | Los Angeles Dodgers
57 | Pittsburgh Pirates
58 | New York Yankees
59 | New York Yankees
60 | Los Angeles Dodgers
61 | St. Louis Cardinals
62 | Los Angeles Dodgers
63 | Baltimore Orioles
64 | St. Louis Cardinals
65 | Detroit Tigers
66 | New York Mets
67 | Baltimore Orioles
68 | Pittsburgh Pirates
69 | Oakland Athletics
70 | Oakland Athletics
71 | Oakland Athletics
72 | Cincinnati Reds
73 | Cincinnati Reds
74 | New York Yankees
75 | New York Yankees
76 | Pittsburgh Pirates
77 | Philadelphia Phillies
78 | Los Angeles Dodgers
79 | St. Louis Cardinals
80 | Baltimore Orioles
81 | Detroit Tigers
82 | Kansas City Royals
83 | New York Mets
84 | Minnesota Twins
85 | Los Angeles Dodgers
86 | Oakland Athletics
87 | Cincinnati Reds
88 | Minnesota Twins
89 | Toronto Blue Jays
90 | Toronto Blue Jays
91 | Atlanta Braves
92 | New York Yankees
93 | Florida Marlins
94 | New York Yankees
95 | New York Yankees
96 | New York Yankees
97 | Arizona Diamondbacks
98 | Anaheim Angels
99 | Florida Marlins
100 | Boston Red Sox
101 | Chicago White Sox
102 | St. Louis Cardinals
103 | Boston Red Sox
104 | Philadelphia Phillies
--------------------------------------------------------------------------------
/src/main/resources/com/levelup/java/exercises/beginner/trivia.txt:
--------------------------------------------------------------------------------
1 | Which singer joined Mel Gibson in the movie Mad Max: Beyond The Thunderdome?|TINA TURNER,Hugh Keays-Byrne, Joanne Samuel, Roger Ward|1
2 | Vodka, Galliano and orange juice are used to make which classic cocktail?|HARVEY WALLBANGER, Old Fashioned, Manhattan, Bloody Mary|1
3 | Which American state is nearest to the former Soviet Union?|Hawaii, ALASKA, California, Florida|2
4 | In which year did Foinavon win the Grand National?|1967, 1988, 2900, 1340|1
5 | At which battle of 1314 did Robert The Bruce defeat the English forces?|BANNOCKBURN, Sally Joe, Gettysburg, Shiloh|1
6 | Consecrated in 1962, where is the Cathedral Church of St Michael?|COVENTRY, Church of Hope, Sagrada Familia, Notre Dame de Paris|1
7 | On TV, who did the character Lurch work for?|ADDAMS FAMILY, Modern Family, 3.5 Men, I ain't your momma|1
8 | Which children's classic book was written by Anna Sewell?|BLACK BEAUTY, Where the red fern grows,Java control structures, Something to do|1
9 | How many tentacles does a squid have?|TEN, Eight, Nine, Five, Four|1
10 | Which reggae singing star died 11th May 1981?|BOB MARLEY, Jessica Dubroff, Eddie Cochran, Aaliyah|1
--------------------------------------------------------------------------------
/src/test/java/com/levelup/java/exercises/beginner/AverageRainfallTest.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import static org.junit.Assert.assertEquals;
4 |
5 | import java.util.ArrayList;
6 | import java.util.List;
7 |
8 | import org.junit.Test;
9 |
10 | /**
11 | * Unit test for {@link AverageRainfall}
12 | *
13 | * @author Justin Musgrove
14 | * @see Average rainfall
15 | *
16 | */
17 | public class AverageRainfallTest {
18 |
19 | @Test
20 | public void test_calculateTotalRainFall () {
21 |
22 | List listToSum = new ArrayList();
23 | listToSum.add(new Double(10));
24 | listToSum.add(new Double(10));
25 | listToSum.add(new Double(10));
26 | listToSum.add(new Double(10));
27 | listToSum.add(new Double(10));
28 |
29 | Double sum = AverageRainfall.calculateTotalRainFall(listToSum);
30 |
31 | assertEquals(50, sum, 0);
32 | }
33 |
34 | @Test
35 | public void test_calculateAverageRainFall () {
36 |
37 | List listToSum = new ArrayList();
38 | listToSum.add(new Double(10));
39 | listToSum.add(new Double(10));
40 | listToSum.add(new Double(10));
41 | listToSum.add(new Double(10));
42 | listToSum.add(new Double(10));
43 |
44 | Double sum = AverageRainfall.calculateAverageRainFall(listToSum);
45 |
46 | assertEquals(10, sum, 0);
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/test/java/com/levelup/java/exercises/beginner/BarChartTest.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import static org.junit.Assert.assertTrue;
4 |
5 | import org.junit.Test;
6 |
7 | /**
8 | * Unit test for {@link BarChart}
9 | *
10 | * @author Justin Musgrove
11 | * @see Bar chart
12 | *
13 | */
14 |
15 | public class BarChartTest {
16 |
17 | @Test
18 | public void chart_length() {
19 |
20 | String chars = BarChart.getBar(1000);
21 |
22 | assertTrue(chars.length() == 10);
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/src/test/java/com/levelup/java/exercises/beginner/BodyMassIndexTest.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import static org.junit.Assert.assertEquals;
4 | import static org.junit.Assert.assertTrue;
5 |
6 | import org.junit.Test;
7 |
8 | /**
9 | * Unit test for {@link BodyMassIndex}
10 | *
11 | * @author Justin Musgrove
12 | * @see Body mass index
13 | *
14 | */
15 | public class BodyMassIndexTest {
16 |
17 | @Test
18 | public void calculate_bmi () {
19 | assertTrue(BodyMassIndex.calculateBMI(73, 250) == 32.9799211859636);
20 | }
21 |
22 | @Test
23 | public void bmiDescription_underweight () {
24 | assertEquals("You are underweight.", BodyMassIndex.bmiDescription(16));
25 | }
26 |
27 | @Test
28 | public void bmiDescription_overweight () {
29 | assertEquals("You are overweight.", BodyMassIndex.bmiDescription(78));
30 | }
31 |
32 | @Test
33 | public void bmiDescription_optimal () {
34 | assertEquals("Your weight is optimal.", BodyMassIndex.bmiDescription(20));
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/test/java/com/levelup/java/exercises/beginner/BookClubPointsTest.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import static org.junit.Assert.assertEquals;
4 |
5 | import org.junit.Test;
6 |
7 | /**
8 | * Unit test for {@link BookClubPoints}
9 | *
10 | * @author Justin Musgrove
11 | * @see Book club points
12 | *
13 | */
14 | public class BookClubPointsTest {
15 |
16 | @Test
17 | public void test_getPointsEarned_0() {
18 |
19 | int points = BookClubPoints.getPointsEarned(0);
20 |
21 | assertEquals(0, points);
22 | }
23 |
24 | @Test
25 | public void test_getPointsEarned_1() {
26 |
27 | int points = BookClubPoints.getPointsEarned(1);
28 |
29 | assertEquals(5, points);
30 | }
31 |
32 | @Test
33 | public void test_getPointsEarned_2() {
34 |
35 | int points = BookClubPoints.getPointsEarned(2);
36 |
37 | assertEquals(15, points);
38 | }
39 |
40 | @Test
41 | public void test_getPointsEarned_3() {
42 |
43 | int points = BookClubPoints.getPointsEarned(3);
44 |
45 | assertEquals(30, points);
46 | }
47 |
48 | @Test
49 | public void test_getPointsEarned_4() {
50 |
51 | int points = BookClubPoints.getPointsEarned(4);
52 |
53 | assertEquals(60, points);
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/src/test/java/com/levelup/java/exercises/beginner/CelsiusToFahrenheitTableTest.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import static org.junit.Assert.assertEquals;
4 |
5 | import org.junit.Test;
6 |
7 | /**
8 | * Unit test for {@link CelsiusToFahrenheitTable}
9 | *
10 | * @author Justin Musgrove
11 | * @see
12 | *
13 | */
14 | public class CelsiusToFahrenheitTableTest {
15 |
16 | @Test
17 | public void test_celsius () {
18 | assertEquals(35, CelsiusToFahrenheitTable.celsius(95), 0);
19 | }
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/src/test/java/com/levelup/java/exercises/beginner/CharacterCounterTest.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import static org.junit.Assert.assertTrue;
4 |
5 | import org.junit.Test;
6 |
7 | /**
8 | * Unit test for {@link CharacterCounter}
9 | *
10 | * @author Justin Musgrove
11 | * @see Character counter
12 | *
13 | */
14 | public class CharacterCounterTest {
15 |
16 | @Test(expected=NullPointerException.class)
17 | public void count_letters_null_to_search () {
18 | CharacterCounter.countLetters(null, "");
19 | }
20 |
21 | @Test(expected=NullPointerException.class)
22 | public void count_letters_null_letter () {
23 | CharacterCounter.countLetters("", null);
24 | }
25 |
26 | @Test
27 | public void count_letters () {
28 |
29 | double count = CharacterCounter.countLetters("aaaa", "a");
30 | assertTrue(count == 4);
31 |
32 | }
33 |
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/src/test/java/com/levelup/java/exercises/beginner/CircleClassTest.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import static org.junit.Assert.assertEquals;
4 |
5 | import org.junit.Test;
6 |
7 | import com.levelup.java.exercises.beginner.CircleClass.Circle;
8 |
9 | /**
10 | * Unit test for {@link CircleClass}
11 | *
12 | * @author Justin Musgrove
13 | * @see Circle class test
14 | */
15 | public class CircleClassTest {
16 |
17 | @Test
18 | public void test_getArea() {
19 |
20 | CircleClass circleClass = new CircleClass();
21 | Circle circle = circleClass.new Circle(10);
22 |
23 | assertEquals(314.159, circle.getArea(), 0);
24 | }
25 |
26 | @Test
27 | public void test_getDiameter() {
28 |
29 | CircleClass circleClass = new CircleClass();
30 | Circle circle = circleClass.new Circle(10);
31 |
32 | assertEquals(20, circle.getDiameter(), 0);
33 | }
34 |
35 | @Test
36 | public void test_getCircumference() {
37 |
38 | CircleClass circleClass = new CircleClass();
39 | Circle circle = circleClass.new Circle(10);
40 |
41 | assertEquals(62.8318, circle.getCircumference(), 0);
42 | }
43 |
44 | }
--------------------------------------------------------------------------------
/src/test/java/com/levelup/java/exercises/beginner/CircuitBoardProfitTest.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import static org.junit.Assert.assertEquals;
4 |
5 | import org.junit.Test;
6 |
7 | /**
8 | * Unit test for {@link CircuitBoardProfit}
9 | *
10 | * @author Justin Musgrove
11 | * @see Circui
13 | * t board profit
14 | *
15 | */
16 |
17 | public class CircuitBoardProfitTest {
18 |
19 | @Test
20 | public void test_calculateProfit() {
21 |
22 | double value = CircuitBoardProfit.calculateProfit(100);
23 |
24 | assertEquals(40, value, 0);
25 | }
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/src/test/java/com/levelup/java/exercises/beginner/DiceGameTest.java:
--------------------------------------------------------------------------------
1 | package com.levelup.java.exercises.beginner;
2 |
3 | import static org.hamcrest.CoreMatchers.is;
4 | import static org.hamcrest.number.OrderingComparison.lessThan;
5 | import static org.junit.Assert.assertThat;
6 |
7 | import java.util.Arrays;
8 | import java.util.List;
9 |
10 | import org.junit.Test;
11 | import org.junit.runner.RunWith;
12 | import org.junit.runners.Parameterized;
13 |
14 |
15 | /**
16 | * Unit test for {@link DiceGame}
17 | *
18 | * @author Justin Musgrove
19 | * @see Dice game
20 | *
21 | */
22 | @RunWith(Parameterized.class)
23 | public class DiceGameTest {
24 |
25 | @Parameterized.Parameters
26 | public static List