├── .gitignore ├── Professional Java Developer Career Starter Java Foundations Exercises & Supplements.pages ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src ├── main └── java │ └── com │ └── neutrinosys │ └── java │ └── foundations │ └── solutions │ ├── section10_streams_lambdas │ ├── Exercise1.java │ ├── Exercise2.java │ ├── Exercise4.java │ ├── Exercise4_2.java │ ├── Exercise5.java │ ├── Exercise5_1.java │ ├── Exercise6.java │ └── Exercise7.java │ ├── section11_loose_ends │ ├── Exercise3.java │ ├── Exercise4.java │ ├── Exercise5.java │ └── Exercise7.java │ ├── section2_classes_objects │ ├── Exercise2.java │ ├── Exercise3.java │ ├── Exercise4.java │ ├── Exercise5.java │ ├── Exercise6.java │ ├── ex10 │ │ └── NeutrinoMath.java │ ├── ex11 │ │ └── People.java │ ├── ex7 │ │ └── Car.java │ ├── ex8 │ │ ├── Customer.java │ │ └── bank │ │ │ ├── Bank.java │ │ │ └── BankManager.java │ └── ex9 │ │ └── Customer.java │ ├── section3_text │ ├── Exercise2.java │ ├── Exercise3.java │ ├── Exercise4.java │ ├── Exercise5.java │ └── ex1 │ │ └── Person.java │ ├── section4_regex │ ├── Exercise1.java │ ├── Exercise2.java │ ├── Exercise3.java │ ├── Exercise4.java │ └── Exercise5.java │ ├── section5_numbers │ ├── Exercise1.java │ ├── Exercise10.java │ ├── Exercise11.java │ ├── Exercise2.java │ ├── Exercise3.java │ ├── Exercise4.java │ ├── Exercise5.java │ ├── Exercise6.java │ ├── Exercise7.java │ ├── Exercise8.java │ └── Exercise9.java │ ├── section6_control_flow │ ├── Exercise1.java │ ├── Exercise2.java │ ├── Exercise4.java │ ├── Exercise5.java │ ├── Exercise6.java │ ├── Exercise7.java │ └── Exercise8.java │ ├── section7_testing │ ├── Exercise1.java │ ├── Exercise3.java │ └── ex2 │ │ └── Person.java │ ├── section8_more_oop │ ├── Exercise1.java │ ├── Exercise4.java │ ├── Exercise5.java │ ├── Exercise6.java │ ├── Exercise7.java │ ├── ex2_3 │ │ ├── DayOfWeek.java │ │ ├── Exercise2.java │ │ └── Exercise3.java │ └── ex8 │ │ ├── ChessBoard.java │ │ ├── ChessPiece.java │ │ ├── Coordinates.java │ │ ├── Knight.java │ │ └── Pawn.java │ └── section9_collections │ ├── Exercise1.java │ ├── Exercise2.java │ ├── Exercise3.java │ ├── Exercise5.java │ └── Exercise6.java └── test └── java └── com └── neutrinosys └── java └── foundations └── solutions ├── section7_testing ├── Exercise1Test.java ├── Exercise3Test.java └── ex2 │ └── PersonTest.java └── section8_more_oop ├── Exercise4Test.java ├── Exercise5Test.java └── ex8 ├── ChessBoardTest.java ├── ChessPieceTest.java ├── KnightTest.java └── PawnTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | # Project exclude paths 2 | /.gradle/ 3 | /build/ 4 | /build/classes/java/main/ 5 | /build/classes/java/test/ -------------------------------------------------------------------------------- /Professional Java Developer Career Starter Java Foundations Exercises & Supplements.pages: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NeutrinoSys/java-foundations-solutions/a336582457550ac8c15eb351f5136b4bd2680983/Professional Java Developer Career Starter Java Foundations Exercises & Supplements.pages -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # java-foundations-solutions 2 | Professional Java Developer Career Starter: Java Foundations Course Exercise Solutions 3 | 4 | The solutions are generally to be found in src/main/java folder. Solutions for each section/module will be in packages ending with the name of the section. 5 | So, solutions for section 2 or in the package, com.neutrinosys.java.foundations.solutions.section2_classes_objects, for example. 6 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | } 4 | 5 | group 'com.neutrinosys.java.foundations.solutions' 6 | version '1.0-SNAPSHOT' 7 | 8 | repositories { 9 | mavenCentral() 10 | } 11 | 12 | dependencies { 13 | testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.2' 14 | testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.2' 15 | } 16 | 17 | test { 18 | useJUnitPlatform() 19 | } -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NeutrinoSys/java-foundations-solutions/a336582457550ac8c15eb351f5136b4bd2680983/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MSYS* | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'Java Foundations Exercise Solutions' 2 | 3 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section10_streams_lambdas/Exercise1.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section10_streams_lambdas; 2 | 3 | import java.time.Year; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | public class Exercise1 { 8 | record Car(String make, String model, Year year){} 9 | 10 | public static void main(String[] args) { 11 | List cars = new ArrayList<>(); 12 | cars.add(new Car("Tesla", "S", Year.of(2014))); 13 | cars.add(new Car("Tesla", "X", Year.of(2015))); 14 | cars.add(new Car("Tesla", "3", Year.of(2016))); 15 | cars.add(new Car("Tesla", "Y", Year.of(2017))); 16 | cars.add(new Car("Tesla", "Roadster", Year.of(2009))); 17 | 18 | cars.stream() 19 | .map(Car::model) 20 | .forEach(System.out::println); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section10_streams_lambdas/Exercise2.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section10_streams_lambdas; 2 | 3 | import java.time.Year; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | public class Exercise2 { 8 | record Car(String make, String model, Year year){} 9 | 10 | public static void main(String[] args) { 11 | List cars = new ArrayList<>(); 12 | cars.add(new Car("Tesla", "S", Year.of(2014))); 13 | cars.add(new Car("Tesla", "X", Year.of(2015))); 14 | cars.add(new Car("Tesla", "3", Year.of(2016))); 15 | cars.add(new Car("Tesla", "Y", Year.of(2017))); 16 | cars.add(new Car("Tesla", "Roadster", Year.of(2009))); 17 | 18 | cars.stream() 19 | .filter(c -> c.year.isAfter(Year.of(2014))) 20 | .forEach(System.out::println); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section10_streams_lambdas/Exercise4.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section10_streams_lambdas; 2 | 3 | import java.time.Year; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | import java.util.stream.Collectors; 7 | import java.util.stream.Stream; 8 | 9 | public class Exercise4 { 10 | record Car(String make, String model, Year year, int price){} 11 | 12 | public static void main(String[] args) { 13 | // Just showing an alternative way of creating the stream of cars 14 | // without first creating an explicity collection/List. This 15 | // approach is not necessarily better, just an alternative. 16 | int sum = Stream.of( 17 | new Car("Tesla", "S", Year.of(2014), 90000), 18 | new Car("Tesla", "X", Year.of(2015), 110000), 19 | new Car("Tesla", "3", Year.of(2016), 55000), 20 | new Car("Tesla", "Y", Year.of(2017), 60000), 21 | new Car("Tesla", "Roadster", Year.of(2009), 135000)) 22 | // .mapToInt(Car::price) // this is first way you could do it 23 | // .sum(); // first way you could do it 24 | .collect(Collectors.summingInt(Car::price)); // this is second way you could do it 25 | System.out.println(sum); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section10_streams_lambdas/Exercise4_2.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section10_streams_lambdas; 2 | 3 | import java.math.BigDecimal; 4 | import java.text.NumberFormat; 5 | import java.time.Year; 6 | import java.util.stream.Collectors; 7 | import java.util.stream.Stream; 8 | 9 | import static java.util.stream.Collectors.collectingAndThen; 10 | import static java.util.stream.Collectors.reducing; 11 | 12 | public class Exercise4_2 { 13 | record Car(String make, String model, Year year, BigDecimal price){} 14 | 15 | public static void main(String[] args) { 16 | // Just showing an alternative way of creating the stream of cars 17 | // without first creating an explicity collection/List. This 18 | // approach is not necessarily better, just an alternative. 19 | 20 | BigDecimal sum = // solution for 4.2 21 | // String sum = // solution for 4.3 22 | Stream.of( 23 | new Car("Tesla", "S", Year.of(2014), new BigDecimal("90000.99")), 24 | new Car("Tesla", "X", Year.of(2015), new BigDecimal("110000.99")), 25 | new Car("Tesla", "3", Year.of(2016), new BigDecimal("55000.99")), 26 | new Car("Tesla", "Y", Year.of(2017), new BigDecimal("60000.99")), 27 | new Car("Tesla", "Roadster", Year.of(2009), new BigDecimal("135000.99"))) 28 | .map(Car::price) 29 | 30 | // solution for 4.2 31 | .reduce(BigDecimal.ZERO, BigDecimal::add); 32 | 33 | // solution for 4.3 34 | // .collect(collectingAndThen(reducing(BigDecimal.ZERO, BigDecimal::add), NumberFormat.getCurrencyInstance()::format)); 35 | System.out.println(sum); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section10_streams_lambdas/Exercise5.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section10_streams_lambdas; 2 | 3 | import java.time.Year; 4 | import java.util.ArrayList; 5 | import java.util.Comparator; 6 | import java.util.List; 7 | 8 | public class Exercise5 { 9 | record Car(String make, String model, Year year){} 10 | 11 | public static void main(String[] args) { 12 | List cars = new ArrayList<>(); 13 | cars.add(new Car("Tesla", "S", Year.of(2014))); 14 | cars.add(new Car("Tesla", "X", Year.of(2015))); 15 | cars.add(new Car("Tesla", "3", Year.of(2016))); 16 | cars.add(new Car("Tesla", "Y", Year.of(2017))); 17 | cars.add(new Car("Tesla", "Roadster", Year.of(2009))); 18 | 19 | cars.stream() 20 | .sorted(Comparator.comparing(Car::model).reversed()) 21 | .forEach(System.out::println); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section10_streams_lambdas/Exercise5_1.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section10_streams_lambdas; 2 | 3 | import java.time.Year; 4 | import java.util.ArrayList; 5 | import java.util.Comparator; 6 | import java.util.List; 7 | 8 | import static java.util.Comparator.comparing; 9 | 10 | public class Exercise5_1 { 11 | record Car(String make, String model, Year year){} 12 | 13 | public static void main(String[] args) { 14 | List cars = new ArrayList<>(); 15 | cars.add(new Car("Tesla", "S", Year.of(2014))); 16 | cars.add(new Car("Tesla", "X", Year.of(2015))); 17 | cars.add(new Car("Tesla", "3", Year.of(2016))); 18 | cars.add(new Car("Tesla", "Y", Year.of(2017))); 19 | cars.add(new Car("Tesla", "Roadster", Year.of(2009))); 20 | 21 | cars.stream() 22 | .sorted( 23 | comparing(Car::make) // notice I've statically imported 'comparing' here 24 | .thenComparing(Car::model).reversed() 25 | .thenComparing(Car::year) 26 | ) 27 | .forEach(System.out::println); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section10_streams_lambdas/Exercise6.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section10_streams_lambdas; 2 | 3 | import java.time.Year; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | import java.util.Optional; 7 | 8 | public class Exercise6 { 9 | record Car(String make, String model, Year year){} 10 | 11 | public static void main(String[] args) { 12 | List cars = new ArrayList<>(); 13 | cars.add(new Car("Tesla", "S", Year.of(2014))); 14 | cars.add(new Car("Tesla", "X", Year.of(2015))); 15 | cars.add(new Car("Tesla", "3", Year.of(2016))); 16 | cars.add(new Car("Tesla", "Y", Year.of(2017))); 17 | cars.add(new Car("Tesla", "Roadster", Year.of(2009))); 18 | 19 | StringBuilder sb = new StringBuilder(); 20 | 21 | Optional models = cars.stream() 22 | .map(Car::model) 23 | .reduce((a, b) -> a.concat(", ").concat(b)); 24 | System.out.println(models.get()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section10_streams_lambdas/Exercise7.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section10_streams_lambdas; 2 | 3 | import java.math.BigDecimal; 4 | import java.text.NumberFormat; 5 | import java.time.Year; 6 | import java.util.HashMap; 7 | import java.util.List; 8 | import java.util.Map; 9 | import java.util.stream.Collectors; 10 | import java.util.stream.Stream; 11 | 12 | import static java.util.stream.Collectors.*; 13 | 14 | public class Exercise7 { 15 | record Car(String make, String model, Year year, BigDecimal price){} 16 | 17 | public static void main(String[] args) { 18 | List cars = List.of( 19 | new Car("Tesla", "S", Year.of(2014), new BigDecimal("90000.99")), 20 | new Car("Tesla", "X", Year.of(2015), new BigDecimal("110000.99")), 21 | new Car("Tesla", "3", Year.of(2016), new BigDecimal("55000.99")), 22 | new Car("Tesla", "Y", Year.of(2017), new BigDecimal("60000.99")), 23 | new Car("Tesla", "Roadster", Year.of(2009), new BigDecimal("135000.99")), 24 | new Car("Lucid", "Air", Year.of(2021), new BigDecimal("77399.99")), 25 | new Car("Hyundai", "Ioniq", Year.of(2021), new BigDecimal("34250.00")), 26 | new Car("Hyundai", "Kona", Year.of(2021), new BigDecimal("38575.00")), 27 | new Car("Porsche", "Taycan", Year.of(2021), new BigDecimal("81250.00")), 28 | new Car("Audi", "e-tron", Year.of(2021), new BigDecimal("66995.00")), 29 | new Car("Volkswagen", "ID.4", Year.of(2021), new BigDecimal("41190")) 30 | ); 31 | 32 | // Exercise 7.1 33 | Map sumByMake = cars.stream() 34 | .collect(groupingBy( 35 | Car::make, 36 | reducing(BigDecimal.ZERO, Car::price, BigDecimal::add))); 37 | System.out.println(sumByMake); 38 | 39 | // Exercise 7.2.1 40 | Map averageByMake = cars.stream() 41 | .collect(groupingBy( 42 | Car::make, 43 | teeing( 44 | reducing(BigDecimal.ZERO, Car::price, BigDecimal::add), 45 | counting(), 46 | (sum, count) -> sum.divide(new BigDecimal(count)) 47 | ) 48 | )); 49 | System.out.println(averageByMake); 50 | 51 | 52 | // Exercise 7.2.2 53 | Map formattedAverageByMake = cars.stream() 54 | .collect(groupingBy( 55 | Car::make, 56 | collectingAndThen(teeing( 57 | reducing(BigDecimal.ZERO, Car::price, BigDecimal::add), 58 | counting(), 59 | (sum, count) -> sum.divide(new BigDecimal(count)) 60 | ), NumberFormat.getCurrencyInstance()::format) 61 | )); 62 | System.out.println(formattedAverageByMake); 63 | 64 | 65 | // Exercise 7.3 66 | Map> countByYearAndMake = cars.stream() 67 | .collect(groupingBy(Car::year, 68 | groupingBy(Car::make, counting()) 69 | ) 70 | ); 71 | System.out.println(countByYearAndMake); 72 | 73 | 74 | // Exercise 7.4 75 | Map countsByMake = new HashMap<>(); 76 | cars.stream() 77 | .forEach(car -> countsByMake.merge(car.make, 1, Integer::sum)); 78 | System.out.println(countsByMake); 79 | } 80 | 81 | } 82 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section11_loose_ends/Exercise3.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section11_loose_ends; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.Optional; 6 | 7 | public class Exercise3 { 8 | record Person(String firstName, String lastName){} 9 | public static void main(String[] args) { 10 | List people = new ArrayList<>(); 11 | people.add(new Person("Jake", "Johnson")); 12 | people.add(new Person("Jerry", "Smith")); 13 | people.add(new Person("Mary", "Smith")); 14 | people.add(null); 15 | people.add(new Person("Sam", "Jackson")); 16 | people.add(null); 17 | people.add(new Person("Sarah", "Doe")); 18 | 19 | for (Person person : people) { 20 | // Several ways to solve this. You could do what I'm doing below. 21 | // Or you could wrap each entry in an Optional as you add() to the collection 22 | // So, you'd end up with a List> instead of List 23 | System.out.println(Optional.ofNullable(person) 24 | .map(Person::firstName) 25 | .filter(n -> n.length() > 3) // Exercise 3.1 26 | .orElse("Unknown")); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section11_loose_ends/Exercise4.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section11_loose_ends; 2 | 3 | 4 | import java.time.LocalDateTime; 5 | import java.time.ZoneId; 6 | import java.time.ZonedDateTime; 7 | import java.time.format.DateTimeFormatter; 8 | import java.time.temporal.TemporalAccessor; 9 | 10 | public class Exercise4 { 11 | public static void main(String[] args) { 12 | String dateTimeText = "July 12, 1984 13:47:00"; 13 | 14 | DateTimeFormatter df = DateTimeFormatter.ofPattern("MMMM dd, yyyy kk:mm:ss"); 15 | TemporalAccessor dateTime = df.parse(dateTimeText); 16 | LocalDateTime localDateTime = LocalDateTime.from(dateTime); 17 | ZonedDateTime startZDT = ZonedDateTime.of(localDateTime, ZoneId.of("-8")); 18 | ZonedDateTime endZDT = startZDT.withZoneSameInstant(ZoneId.of("+0")); 19 | System.out.println(startZDT); 20 | System.out.println(endZDT); 21 | 22 | // Exercise 3.1 23 | // You can always get the full list of ZoneIds by googling or this code... 24 | // ZoneId.getAvailableZoneIds().stream() 25 | // .map(String::toLowerCase) 26 | // .sorted() 27 | // .forEach(System.out::println); 28 | ZonedDateTime japan = startZDT.plusDays(179).plusHours(7).plusMinutes(27).withZoneSameInstant(ZoneId.of("Asia/Tokyo")); 29 | System.out.println(japan); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section11_loose_ends/Exercise5.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section11_loose_ends; 2 | 3 | import java.time.*; 4 | import java.time.temporal.ChronoUnit; 5 | 6 | public class Exercise5 { 7 | public static void main(String[] args) { 8 | LocalDate independanceDay = LocalDate.of(1776, 7, 4); 9 | LocalDate today = LocalDate.now(); 10 | Period ageOfUS = Period.between(independanceDay, today); 11 | System.out.println(ageOfUS); 12 | 13 | // Exercise 5.2 14 | LocalDate newYear = LocalDate.ofYearDay(2023, 1); 15 | long daysToNewYear = ChronoUnit.DAYS.between(today, newYear); 16 | System.out.println(daysToNewYear); 17 | 18 | // Exercise 5.3 19 | LocalTime activityStart = LocalTime.of(9, 37, 20); 20 | LocalTime activityStop = LocalTime.of(19, 13, 41); 21 | Duration activityDuration = Duration.between(activityStart, activityStop); 22 | System.out.println(activityDuration); 23 | // Exercise 5.3.1 24 | System.out.println(activityDuration.toMinutes()); 25 | 26 | // Exercise 6 27 | ZonedDateTime departure = ZonedDateTime.of(2022, 2, 3, 13, 15, 0, 0, ZoneId.of("Asia/Seoul")); 28 | ZonedDateTime arrival = ZonedDateTime.of(2022,2,3,20,02,13,0,ZoneId.of("Europe/London")); 29 | System.out.println(Duration.between(departure, arrival)); 30 | System.out.println(arrival.withZoneSameInstant(ZoneId.of("America/Los_Angeles"))); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section11_loose_ends/Exercise7.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section11_loose_ends; 2 | 3 | import java.io.IOException; 4 | import java.time.Instant; 5 | import java.time.ZoneId; 6 | import java.time.ZonedDateTime; 7 | import java.time.format.DateTimeFormatter; 8 | 9 | import static java.time.format.DateTimeFormatter.ISO_INSTANT; 10 | import static java.time.format.DateTimeFormatter.ofPattern; 11 | 12 | public class Exercise7 { 13 | public static void main(String[] args) throws IOException { 14 | // Sample date/time 1 15 | // The format of the input String matches the pattern of 16 | // DateTimeFormatter.ISO_INSTANT (look at the Javadoc for DateTimeFormatter) 17 | // This formatter wants to parse its Strings into an Instant object 18 | // So, you see me using Instant.from() to receive the output from parse() 19 | System.out.println(Instant.from(ISO_INSTANT.parse("2022-02-09T05:02:01Z"))); 20 | 21 | // Sample date/time 2 22 | // Didn't see a ready-made format for this String as with the previous one, so 23 | // chose to use ofPattern() & specify manually. The single tick ' symbol is 24 | // used to indicate the pattern should expect a literal "T" at that position 25 | // You could find that out by looking at the Javadoc for DateTimeFormatter in detail 26 | // (you may need to read it thoroughly to find that out) 27 | // Note, I'm able to use ZonedDateTime.from() here, though Instant.from() also would work 28 | System.out.println(ZonedDateTime.from(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'kk:mm:ssxx").parse("2022-02-09T05:02:01+0000"))); 29 | 30 | // Sample date/time 3 31 | System.out.println(ZonedDateTime.from(DateTimeFormatter.ofPattern("E, dd MMM yyyy kk:mm:ss xx").parse("Wed, 09 Feb 2022 05:02:01 +0000"))); 32 | 33 | // Sample date/time 4 34 | // Notice I use ZonedDateTime.parse() taking the String to parse and a DateTimeFormatter 35 | // This is no different from the previous approach - just another way of doing it so you can see alternatives. 36 | // It is about 3 characters shorter I suppose. 37 | System.out.println(ZonedDateTime.parse("Wednesday, 09-Feb-22 05:02:01 UTC", DateTimeFormatter.ofPattern("EEEE, dd-MMM-yy kk:mm:ss z"))); 38 | 39 | 40 | // Sample date/time 5 41 | // Here, I chose to use ofPattern() as a static import to shorten the line further 42 | System.out.println(ZonedDateTime.parse("Wed, 09 Feb 22 05:02:01 +0000", ofPattern("E, dd MMM yy kk:mm:ss xx"))); 43 | 44 | 45 | // Sample date/time 13 46 | // The key to this one is recognizing that 1644382921 is an epoch time. I understood this 47 | // because this whole exercise is about dealing with & converting times, and any example 48 | // nothing but a long number is almost certainly going to be an epoch time. 49 | // You learned that Unix/epoch times are represented by the Instant class, so it would 50 | // follow that there should be a way to create an Instant from just the epoch number 51 | // That turns out to be done with the ofEpochSecond() method. I then proceed 52 | // to convert the Instant to a ZonedDateTime object by calling Instant.atZone() 53 | // and specify I want the newly-created ZonedDateTime to be at time zone +0 54 | // somewhat arbitrarily 55 | System.out.println(Instant.ofEpochSecond(1644382921).atZone(ZoneId.of("+0"))); 56 | 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section2_classes_objects/Exercise2.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section2_classes_objects; 2 | 3 | public class Exercise2 { 4 | public static void main(String[] args) { 5 | String[] daysOfWeek = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; 6 | System.out.println(daysOfWeek.length); // Print # of item in array 7 | System.out.println(daysOfWeek[3]); // Print 4th day in the array. Note: arrays are zero-based, so 1st item is 0 & 4th item is 3. 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section2_classes_objects/Exercise3.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section2_classes_objects; 2 | 3 | public class Exercise3 { 4 | public static void main(String[] args) { 5 | int[] numbers = {1,2,3,4,5,6,7,8,9,10}; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section2_classes_objects/Exercise4.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section2_classes_objects; 2 | 3 | public class Exercise4 { 4 | public static void main(String[] args) { 5 | char[][] ticTacToeBoard = { 6 | {'O','X','X'}, 7 | {'X','O','O'}, 8 | {'X','O','O'} 9 | }; 10 | System.out.println(ticTacToeBoard[2][2]); // How would you access the bottom right square? 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section2_classes_objects/Exercise5.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section2_classes_objects; 2 | 3 | public class Exercise5 { 4 | public static void main(String[] args) { 5 | Exercise5 exercise5 = new Exercise5(); 6 | exercise5.myMultiInputMethod("one", "two", "three", "four"); 7 | exercise5.myMultiInputMethod("apple", "orange", "pineapple"); 8 | exercise5.myMultiInputMethod("Bobby"); 9 | } 10 | 11 | /* A method that allows any number of Strings to be passed as parameter inputs without an array */ 12 | private void myMultiInputMethod(String...args) {} 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section2_classes_objects/Exercise6.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section2_classes_objects; 2 | 3 | public class Exercise6 { 4 | public static void mySpecialMethod() { 5 | System.out.println("My special method needs no class instance to run."); 6 | } 7 | 8 | public static void main(String[] args) { 9 | // No need to call "new Exercise6().mySpecialMethod()" 10 | Exercise6.mySpecialMethod(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section2_classes_objects/ex10/NeutrinoMath.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section2_classes_objects.ex10; 2 | 3 | public class NeutrinoMath { 4 | public static final double E = Math.E; 5 | 6 | public static void main(String[] args) { 7 | System.out.println(NeutrinoMath.E); // Constants of this sort are typically modeled as a public static final 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section2_classes_objects/ex11/People.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section2_classes_objects.ex11; 2 | 3 | public class People { 4 | public static final String friends[] = {"Sam", "Jake", "Sarah"}; 5 | 6 | public String[] getFriends() { 7 | return People.friends; 8 | } 9 | 10 | /** 11 | * The key here is that the People class stores the three friends in a static field, which causes the friends to be shared 12 | * amongst all instances of the People class. The use of an array to store the friends allows us to associate a number with 13 | * each friend. 14 | */ 15 | public static void main(String[] args) { 16 | People f1 = new People(); 17 | People f2 = new People(); 18 | People f3 = new People(); 19 | 20 | System.out.println(f1.getFriends()[0]); 21 | System.out.println(f1.getFriends()[1]); 22 | System.out.println(f1.getFriends()[2]); 23 | 24 | System.out.println(f2.getFriends()[0]); 25 | System.out.println(f2.getFriends()[1]); 26 | System.out.println(f2.getFriends()[2]); 27 | 28 | System.out.println(f3.getFriends()[0]); 29 | System.out.println(f3.getFriends()[1]); 30 | System.out.println(f3.getFriends()[2]); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section2_classes_objects/ex7/Car.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section2_classes_objects.ex7; 2 | 3 | import java.time.Year; 4 | 5 | public class Car { 6 | private String make; 7 | private String model; 8 | private Year modelYear; 9 | 10 | public Car(String make, String model, Year modelYear) { 11 | this.make = make; 12 | this.model = model; 13 | this.modelYear = modelYear; 14 | } 15 | 16 | /* The key is to generate a toString() method that prints all the properties */ 17 | @Override 18 | public String toString() { 19 | return "Car{" + 20 | "make='" + make + '\'' + 21 | ", model='" + model + '\'' + 22 | ", modelYear=" + modelYear + 23 | '}'; 24 | } 25 | 26 | public static void main(String[] args) { 27 | Car myCar = new Car("Tesla", "X", Year.of(2020)); 28 | System.out.println(myCar); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section2_classes_objects/ex8/Customer.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section2_classes_objects.ex8; 2 | 3 | import com.neutrinosys.java.foundations.solutions.section2_classes_objects.ex8.bank.Bank; 4 | import com.neutrinosys.java.foundations.solutions.section2_classes_objects.ex8.bank.BankManager; 5 | 6 | public class Customer { 7 | 8 | public void accessBankVault(Bank bank) { 9 | // bank.accessVault(); // If you uncomment this method (remove // from beginning of this line), you'll have an error because bank.accessVault() is package protected & customer is not in the bank package 10 | } 11 | 12 | public void accessBankVault(BankManager manager, Bank bank) { 13 | manager.accessVault(bank); 14 | } 15 | 16 | public static void main(String[] args) { 17 | Customer customer = new Customer(); 18 | Bank bank = new Bank(); 19 | BankManager manager = new BankManager(); 20 | 21 | customer.accessBankVault(bank); // This way won't work. cmd/ctrl-click on .accessBankVault to see why 22 | customer.accessBankVault(manager, bank); // This way DOES work because manager IS allowed to access Bank.accessVault() 23 | 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section2_classes_objects/ex8/bank/Bank.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section2_classes_objects.ex8.bank; 2 | 3 | public class Bank { 4 | private String name; 5 | 6 | /* Notice this method does not have public or private keywords (protected would also work). Without those, it is 'package protected'. */ 7 | void accessVault() { 8 | System.out.println("You're in the vault now"); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section2_classes_objects/ex8/bank/BankManager.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section2_classes_objects.ex8.bank; 2 | 3 | public class BankManager { 4 | public void accessVault(Bank bank) { 5 | bank.accessVault(); // Perfectly fine here because Manager & Bank are in the same package and Bank.accessVault is package protected 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section2_classes_objects/ex9/Customer.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section2_classes_objects.ex9; 2 | 3 | public class Customer { 4 | private String name; 5 | private float deposit; 6 | 7 | public Customer(String name, float deposit) { 8 | this.name = name; 9 | this.deposit = deposit; 10 | } 11 | 12 | public static void main(String[] args) { 13 | Customer customer = new Customer("Frank", 1234.83f); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section3_text/Exercise2.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section3_text; 2 | 3 | public class Exercise2 { 4 | public static void main(String[] args) { 5 | String sentence = "I love to play with cats because cats are really fun."; 6 | System.out.println(sentence.replaceAll("cat", "dog")); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section3_text/Exercise3.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section3_text; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * You can run this class' main method within IDE normally 7 | * since it does not use the console() 8 | * After running, just enter some text at the prompt followed by 9 | */ 10 | public class Exercise3 { 11 | public static void main(String[] args) { 12 | Scanner scanner = new Scanner(System.in); 13 | String userInput = scanner.nextLine().strip(); // important part here 14 | System.out.printf("'%s'%n", userInput); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section3_text/Exercise4.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section3_text; 2 | 3 | public class Exercise4 { 4 | public static void main(String[] args) { 5 | String input = " alphabet "; 6 | String strippedInput = input.strip(); 7 | String firstPart = strippedInput.substring(0, strippedInput.length() - 1); 8 | Character lastLetter = strippedInput.charAt(strippedInput.length() - 1); 9 | // or 10 | // String lastLetter = strippedInput.substring(strippedInput.length() - 1); 11 | System.out.println(firstPart + lastLetter.toString().toUpperCase()); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section3_text/Exercise5.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section3_text; 2 | 3 | public class Exercise5 { 4 | public static void main(String[] args) { 5 | String address = "12345 Big St., Alphabet City, CA 90210"; 6 | 7 | String buildingNumber = address.split(" ")[0]; 8 | String street = findStreet(address); 9 | String city = findCity(address); 10 | String state = findState(address); 11 | String postCode = findPostCode(address); 12 | 13 | System.out.println(buildingNumber); 14 | System.out.println(street); 15 | System.out.println(city); 16 | System.out.println(state); 17 | System.out.println(postCode); 18 | 19 | } 20 | 21 | public static String findStreet(String address) { 22 | int firstSpace = address.indexOf(" "); 23 | int firstComma = address.indexOf(","); 24 | String street = address.substring(firstSpace + 1, firstComma); 25 | return street; 26 | } 27 | 28 | public static String findCity(String address) { 29 | return address.split(",")[1].strip(); 30 | } 31 | 32 | public static String findState(String address) { 33 | // First split address on commas, which returns an array with 3 elements 34 | // Then get the 3rd element (arrays are zero-based, so 3rd element is [2]) which contains: " CA 90210" 35 | // Strip leading & trailing spaces 36 | // Then split 3rd element on spaces, which return array with 2 elements 37 | // Then get 1st element which contains: "CA" & return it 38 | return address.split(",")[2].strip().split(" ")[0]; 39 | } 40 | 41 | public static String findPostCode(String address) { 42 | // same as findState() except gets second element at the end 43 | return address.split(",")[2].strip().split(" ")[1]; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section3_text/ex1/Person.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section3_text.ex1; 2 | 3 | public class Person { 4 | private String firstName; 5 | private String lastName; 6 | 7 | public String getFirstName() { 8 | return firstName; 9 | } 10 | 11 | public void setFirstName(String firstName) { 12 | this.firstName = firstName.toUpperCase(); // Here's the important part 13 | } 14 | 15 | public String getLastName() { 16 | return lastName; 17 | } 18 | 19 | public void setLastName(String lastName) { 20 | this.lastName = lastName; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section4_regex/Exercise1.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section4_regex; 2 | 3 | public class Exercise1 { 4 | public static void main(String[] args) { 5 | String regex = "[DbL]ark"; 6 | String regex2 = "(St|[DbL])ark"; // Exercise 1.1 extra challenge 7 | System.out.println("Dark".matches(regex)); 8 | System.out.println("bark".matches(regex)); 9 | System.out.println("Lark".matches(regex)); 10 | 11 | System.out.println("Stark".matches(regex2)); 12 | System.out.println("Dark".matches(regex2)); 13 | System.out.println("bark".matches(regex2)); 14 | System.out.println("Lark".matches(regex2)); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section4_regex/Exercise2.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section4_regex; 2 | 3 | public class Exercise2 { 4 | public static void main(String[] args) { 5 | String regex = "A[bg]racada[bg]ra"; 6 | System.out.println("Abracadabra".matches(regex)); 7 | System.out.println("Agracadagra".matches(regex)); 8 | 9 | // Alternatively 10 | String regex2 = "A([bg])racada\\1ra"; // This would prevent matching Abracadagra - for example 11 | System.out.println("Abracadabra".matches(regex2)); 12 | System.out.println("Agracadagra".matches(regex2)); 13 | 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section4_regex/Exercise3.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section4_regex; 2 | 3 | public class Exercise3 { 4 | public static void main(String[] args) { 5 | String regex2 = "A(?:[bg])racada[bg]ra"; // Can no longer use '\\1' backreference since no longer capturing group 6 | System.out.println("Abracadabra".matches(regex2)); 7 | System.out.println("Agracadagra".matches(regex2)); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section4_regex/Exercise4.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section4_regex; 2 | 3 | import java.util.regex.Matcher; 4 | import java.util.regex.Pattern; 5 | 6 | public class Exercise4 { 7 | public static void main(String[] args) { 8 | String address = "12345 Funny St., Big City, NY 90210"; 9 | String regex = "(?\\d+)\\s+(?.*?),\\s*(?.*?),\\s*(?[A-Z]{2})\\s*(?\\d{5})"; 10 | Pattern pat = Pattern.compile(regex); 11 | Matcher matcher = pat.matcher(address); 12 | matcher.find(); 13 | System.out.println(matcher.group("streetNum")); 14 | System.out.println(matcher.group("streetName")); 15 | System.out.println(matcher.group("city")); 16 | System.out.println(matcher.group("state")); 17 | System.out.println(matcher.group("postCode")); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section4_regex/Exercise5.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section4_regex; 2 | 3 | public class Exercise5 { 4 | public static void main(String[] args) { 5 | String email = "jerry.seinfeld@jokes.nbc.com"; 6 | String regex = "\\w+\\.?\\w*@(\\w+\\.)+\\w+"; // allows for jokes.com or jokes.blah.com or jokes.blah.blah.com, etc. 7 | System.out.println(email.matches(regex)); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section5_numbers/Exercise1.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section5_numbers; 2 | 3 | public class Exercise1 { 4 | public static void main(String[] args) { 5 | // Let H G F E D C B A - be assigned values 6 | // 128 64 32 16 8 4 2 1 7 | int signalABC = 1 | 2 | 4; // 7 8 | int signalAD = 1 | 8; // 9 9 | int signalADC = 1 | 8 | 4; // 13 10 | 11 | // test if signal D is present in ADC 12 | System.out.println((13 & 8) == 8); // Logical AND of original signal (13) AND 'D' (8) will equal 8 IF and only IF 'D' was present in original signal 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section5_numbers/Exercise10.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section5_numbers; 2 | 3 | import java.text.DecimalFormat; 4 | 5 | public class Exercise10 { 6 | public static void main(String[] args) { 7 | System.out.println(new DecimalFormat("$,###.##").format(123456.783)); // you could also do "$#,###.##" 8 | System.out.println(new DecimalFormat(",###.###;(#)").format(-9876.32532)); 9 | System.out.println(new DecimalFormat("0.######E00f").format( 23.19283928394829182)); // not possible to get the plus sign in "...e+01f" with format string 10 | System.out.println(new DecimalFormat("0000000000").format(123456)); 11 | System.out.println(new DecimalFormat(",###.#;-").format(-9876.35532)); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section5_numbers/Exercise11.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section5_numbers; 2 | 3 | public class Exercise11 { 4 | private static int addStringIntegers(String num1, String num2) { 5 | int n1 = Integer.parseInt(num1); 6 | int n2 = Integer.parseInt(num2); 7 | return n1 + n2; 8 | } 9 | 10 | public static void main(String[] args) { 11 | System.out.println(addStringIntegers("37", "13")); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section5_numbers/Exercise2.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section5_numbers; 2 | 3 | public class Exercise2 { 4 | public static void main(String[] args) { 5 | System.out.println(2 | 4); 6 | System.out.println(2 + 4); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section5_numbers/Exercise3.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section5_numbers; 2 | 3 | public class Exercise3 { 4 | private String[] people = {"bob", "larry", "sammy", "johnny", "rohith", "sally", "susan", "betty", "jane", "samantha"}; 5 | private int currentPersonIndex = 0; 6 | 7 | public String next() { 8 | String person = people[currentPersonIndex++]; 9 | return person.substring(0,1).toUpperCase() + person.substring(1); 10 | } 11 | 12 | public static void main(String[] args) { 13 | Exercise3 exercise3 = new Exercise3(); 14 | System.out.println(exercise3.next()); 15 | System.out.println(exercise3.next()); 16 | System.out.println(exercise3.next()); 17 | System.out.println(exercise3.next()); 18 | System.out.println(exercise3.next()); 19 | System.out.println(exercise3.next()); 20 | System.out.println(exercise3.next()); 21 | System.out.println(exercise3.next()); 22 | System.out.println(exercise3.next()); 23 | System.out.println(exercise3.next()); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section5_numbers/Exercise4.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section5_numbers; 2 | 3 | public class Exercise4 { 4 | private int[] nums = {13, 49, 90, 130, 175, 181, 255, 310, 330, 359}; 5 | private int currentNumIndex = 0; 6 | 7 | public int next() { 8 | return nums[currentNumIndex++] / 90; 9 | } 10 | 11 | public static void main(String[] args) { 12 | Exercise4 exercise4 = new Exercise4(); 13 | System.out.println(exercise4.next()); 14 | System.out.println(exercise4.next()); 15 | System.out.println(exercise4.next()); 16 | System.out.println(exercise4.next()); 17 | System.out.println(exercise4.next()); 18 | System.out.println(exercise4.next()); 19 | System.out.println(exercise4.next()); 20 | System.out.println(exercise4.next()); 21 | System.out.println(exercise4.next()); 22 | System.out.println(exercise4.next()); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section5_numbers/Exercise5.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section5_numbers; 2 | 3 | import java.util.Random; 4 | 5 | public class Exercise5 { 6 | private int sum = 0; 7 | 8 | public int next() { 9 | this.sum += new Random().nextInt(10); 10 | return this.sum; 11 | } 12 | 13 | public static void main(String[] args) { 14 | Exercise5 exercise5 = new Exercise5(); 15 | System.out.println(exercise5.next()); 16 | System.out.println(exercise5.next()); 17 | System.out.println(exercise5.next()); 18 | System.out.println(exercise5.next()); 19 | System.out.println(exercise5.next()); 20 | System.out.println(exercise5.next()); 21 | System.out.println(exercise5.next()); 22 | System.out.println(exercise5.next()); 23 | System.out.println(exercise5.next()); 24 | System.out.println(exercise5.next()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section5_numbers/Exercise6.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section5_numbers; 2 | 3 | import java.math.BigDecimal; 4 | import java.text.NumberFormat; 5 | import java.util.Locale; 6 | 7 | public class Exercise6 { 8 | 9 | public static String formatMoney(String money) { 10 | return NumberFormat.getCurrencyInstance(Locale.FRANCE).format(new BigDecimal(money)); 11 | } 12 | 13 | public static void main(String[] args) { 14 | System.out.println(formatMoney("149.32")); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section5_numbers/Exercise7.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section5_numbers; 2 | 3 | import java.math.BigDecimal; 4 | import java.math.MathContext; 5 | import java.text.NumberFormat; 6 | import java.text.ParseException; 7 | 8 | public class Exercise7 { 9 | 10 | public static String calculate(String formattedMoney) throws ParseException { 11 | NumberFormat formatter = NumberFormat.getCurrencyInstance(); 12 | Number value = formatter.parse(formattedMoney); 13 | BigDecimal result = new BigDecimal(value.toString()).divide(new BigDecimal("32.19"), MathContext.DECIMAL32); 14 | // Used MathContext.DECIMAL32 above so I wouldn't have to create one myself. Chose 32 instead of the others 15 | // because it was the smallest one, in terms of precision. 16 | return formatter.format(result); 17 | } 18 | 19 | public static void main(String[] args) throws ParseException { 20 | System.out.println(calculate("$12,345.83")); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section5_numbers/Exercise8.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section5_numbers; 2 | 3 | public class Exercise8 { 4 | public static void main(String[] args) { 5 | System.out.printf("$%,.2f%n", 123456.783); 6 | System.out.printf("%,(.3f%n", -9876.32532); 7 | System.out.printf("%ef%n", 23.19283928394829182); 8 | System.out.printf("%010d%n", 123456); 9 | System.out.printf("%,+.1f%n", -9876.35532); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section5_numbers/Exercise9.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section5_numbers; 2 | 3 | public class Exercise9 { 4 | public static void main(String[] args) { 5 | String v1 = String.format("$%,.2f%n", 123456.783); 6 | String v2 = String.format("%,(.3f%n", -9876.32532); 7 | String v3 = String.format("%ef%n", 23.19283928394829182); 8 | String v4 = String.format("%010d%n", 123456); 9 | String v5 = String.format("%,+.1f%n", -9876.35532); 10 | 11 | System.out.print(v1); 12 | System.out.print(v2); 13 | System.out.print(v3); 14 | System.out.print(v4); 15 | System.out.print(v5); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section6_control_flow/Exercise1.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section6_control_flow; 2 | 3 | public class Exercise1 { 4 | public static void main(String[] args) { 5 | String[] days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; 6 | for (int day=0; day < days.length; day++) { 7 | System.out.println(days[day]); 8 | } 9 | 10 | // Using enhanced for-loop 11 | for (String day : days) { 12 | System.out.println(day); 13 | } 14 | 15 | // Alternating capitalization 16 | for (int day=0; day < days.length; day++) { 17 | if (day % 2 == 0) { // Review Numbers section for reminder of how this works 18 | System.out.println(days[day]); 19 | } else { 20 | System.out.println(days[day].toUpperCase()); 21 | } 22 | } 23 | 24 | // Alternating capitalization - shorter 25 | for (int day=0; day < days.length; day++) { 26 | String output = day % 2 == 0 ? days[day] : days[day].toUpperCase(); 27 | System.out.println(output); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section6_control_flow/Exercise2.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section6_control_flow; 2 | 3 | public class Exercise2 { 4 | public static void main(String[] args) { 5 | String[] days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; 6 | int day = 0; 7 | while (day < days.length) { 8 | System.out.println(days[day++]); 9 | } 10 | 11 | // Alternating capitalization 12 | day = 0; 13 | while (day < days.length) { 14 | if (day % 2 == 0) { 15 | System.out.println(days[day++]); 16 | } else { 17 | System.out.println(days[day++].toUpperCase()); 18 | } 19 | } 20 | System.out.println("---"); 21 | 22 | // Alternating capitalization - shorter 23 | day = 0; 24 | while (day < days.length) { 25 | String output = day % 2 == 0 ? days[day++] : days[day++].toUpperCase(); 26 | System.out.println(output); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section6_control_flow/Exercise4.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section6_control_flow; 2 | 3 | public class Exercise4 { 4 | public static void main(String[] args) { 5 | String[] days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; 6 | for (String day : days) { 7 | if ("Sunday".equals(day)) { 8 | System.out.println("We eat pot roast on Sunday"); 9 | } else if ("Monday".equals(day)) { 10 | System.out.println("We eat spaghetti on Monday"); 11 | } else if ("Tuesday".equals(day)) { 12 | System.out.println("We eat tacos on Tuesday"); 13 | } else if ("Wednesday".equals(day)) { 14 | System.out.println("We eat chicken on Wednesday"); 15 | } else if ("Thursday".equals(day)) { 16 | System.out.println("We eat meatloaf on Thursday"); 17 | } else if ("Friday".equals(day)) { 18 | System.out.println("We eat hamburgers on Friday"); 19 | } else { // technically, no need for another "else if" since there's only one remaining option 20 | System.out.println("We eat pizza on Saturday"); 21 | } 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section6_control_flow/Exercise5.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section6_control_flow; 2 | 3 | public class Exercise5 { 4 | public static void main(String[] args) { 5 | String[] days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; 6 | for (String day : days) { 7 | switch (day) { 8 | case "Sunday": 9 | System.out.println("We eat pot roast on Sunday"); 10 | break; 11 | case "Monday": 12 | System.out.println("We eat spaghetti on Monday"); 13 | break; 14 | case "Tuesday": 15 | System.out.println("We eat tacos on Tuesday"); 16 | break; 17 | case "Wednesday": 18 | System.out.println("We eat chicken on Wednesday"); 19 | break; 20 | case "Thursday": 21 | System.out.println("We eat meatloaf on Thursday"); 22 | break; 23 | case "Friday": 24 | System.out.println("We eat hamburgers on Friday"); 25 | break; 26 | default: // Be careful here with 'default'. We could use default for remaining day of Saturday, OR we could use it in case something other than standard 7 days shows up 27 | System.out.println("We eat pizza on Saturday"); 28 | break; 29 | } 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section6_control_flow/Exercise6.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section6_control_flow; 2 | 3 | public class Exercise6 { 4 | public static void main(String[] args) { 5 | String[] days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; 6 | for (String day : days) { 7 | String meal = switch (day) { 8 | case "Sunday" -> "pot roast"; 9 | case "Monday" -> "spaghetti"; 10 | case "Tuesday" -> "tacos"; 11 | case "Wednesday" -> "chicken"; 12 | case "Thursday" -> "meatloaf"; 13 | case "Friday" -> "hamburgers"; 14 | default -> "pizza"; 15 | }; 16 | System.out.printf("We eat %s on %s%n", meal, day); 17 | // System.out.printf("We eat %s on %s%n", capitalize(meal), day); // 6.1 solution 18 | // System.out.printf("We eat %s on %s%n", capitalizeMultiWord(meal), day); // 6.2 solution 19 | } 20 | } 21 | 22 | public static String capitalize(String word) { 23 | return word.substring(0,1).toUpperCase() + word.substring(1); 24 | } 25 | 26 | public static String capitalizeMultiWord(String meal) { 27 | String[] words = meal.split(" "); 28 | 29 | // I am initializing the StringBuilder because I am able to determine the exact needed size from the incoming 30 | // 'meal' variable. I am adding '+1' because after capitalizing each word in the meal, I will automatically 31 | // add a space. In case of "pot roast", which is 9 characters long, if I add space to each word, it would be 32 | // "pot " & "roast ", which is 10 characters, so, meal.length() + 1. 33 | // If I do not add space at end of each word, I will return "PotRoast", incorrectly. 34 | // Notice how I reuse the capitalize() method even here. Always good to be able to build on top of existing 35 | // functionality. 36 | StringBuilder sb = new StringBuilder(meal.length() + 1); 37 | for (String word : words) { 38 | sb.append(capitalize(word)).append(" "); 39 | } 40 | // Since I am automatically adding space to the end of each word, I must strip() trailing space, 41 | // otherwise, I'd return "Pot Roast " instead of "Pot Roast". 42 | return sb.toString().strip(); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section6_control_flow/Exercise7.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section6_control_flow; 2 | 3 | public class Exercise7 { 4 | public static void main(String[] args) { 5 | String[] days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; 6 | int totalChars = 0; 7 | for (String day : days) { 8 | totalChars+=day.length(); 9 | } 10 | System.out.println(totalChars); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section6_control_flow/Exercise8.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section6_control_flow; 2 | 3 | import java.util.regex.Matcher; 4 | import java.util.regex.Pattern; 5 | 6 | public class Exercise8 { 7 | public static void main(String[] args) { 8 | String addresses = """ 9 | 12345 First Street, First City, AA 90210 10 | 22222 Second Street, Second City, BB 22222 11 | 33333 Third Street, Third City, CC 33333 12 | 44444 Fourth Street, Fourth City, DD 44444 13 | 55555 Fifth Street, Fifth City, EE 55555 14 | 66666 Sixth Street, Sixth City, FF 66666 15 | 77777 Seventh Street, Seventh City, GG 77777 16 | 88888 Eighth Street, Eighth City, HH 88888 17 | 99999 Ninth Street, Ninth City, II 99999 18 | 00000 Tenth Street, Tenth City, JJ 00000 19 | """; 20 | Pattern pat = Pattern.compile(""" 21 | (?.*?),\\s+(?.*?),\\s+(?[A-Z]{2})\\s+(?\\d{5})$ 22 | """, Pattern.MULTILINE | Pattern.COMMENTS); 23 | Matcher mat = pat.matcher(addresses); 24 | while(mat.find()) { 25 | System.out.println(mat.group("street")); 26 | System.out.println(mat.group("city")); 27 | System.out.println(mat.group("state")); 28 | System.out.println(mat.group("zip")); 29 | System.out.println("--------------------------------------"); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section7_testing/Exercise1.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section7_testing; 2 | 3 | public class Exercise1 { 4 | public static String alternateCaps(String word) { 5 | StringBuilder sb = new StringBuilder(word.length()); // Place to store new string as we build it one character at a time 6 | for (int index=0; index "at" 20 | String firstWordStripped = firstWord.substring(firstWordPrefix.length()); 21 | String secondWord = words[1]; // repeat for second word (arrays are zero-based, so words[1] is second word - "cap" 22 | String secondWordPrefix = findPrefix(secondWord); // returns just "c" since "cap" doesn't start with a known cluster 23 | String secondWordStripped = secondWord.substring(secondWordPrefix.length()); // returns "ap" 24 | StringBuilder sb = new StringBuilder() // going to build a new phrase 25 | .append(secondWordPrefix) // "c" 26 | .append(firstWordStripped) // "c" + "at" = "cat" 27 | .append(" ") // "cat" + " " (space) = "cat " 28 | .append(firstWordPrefix) // "cat " + "fl" = "cat fl" 29 | .append(secondWordStripped); // "cat fl" + "ap" = "cat flap" 30 | return sb.toString(); // "cat flap" 31 | } 32 | 33 | /** 34 | * If the word begins with a known English word cluster, such as: 35 | * 'tr', 'fl', 'pl', 'sn', etc. 36 | * this method will determine that and return that matching prefix. 37 | * Otherwise, it will simply return the first letter of the word. 38 | * It finds the cluster by iterating over the class's internal array 39 | * of known clusters, one at a time, testing if the word "startsWith()" 40 | * that cluster and returning it if it does. This means this program 41 | * can only 'spoonerize' words with clusters it knows about. 42 | * @param word 43 | * @return 44 | */ 45 | private static String findPrefix(String word) { 46 | for (String cluster : clusters) { // iterate over each cluster in clusters array "tr", "fl", "pl", "sn" - one at a time 47 | if (word.startsWith(cluster)) { // does "flat" start with "tr"? no? does "flat" start with "fl"?, yes? then return "fl" 48 | return cluster; 49 | } 50 | } 51 | // to get down this far, it means our word doesn't start with any known cluster, so for example, let's assume 52 | // the word is "cat"... 53 | // if "cat" doesn't start with any clusters, then just return the first letter of "cat", "c" 54 | return word.substring(0, 1); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section7_testing/ex2/Person.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section7_testing.ex2; 2 | 3 | import java.util.Objects; 4 | 5 | public class Person { 6 | private String firstName; 7 | private String lastName; 8 | private String streetAddress; 9 | private String city; 10 | private String state; 11 | private String zipcode; 12 | 13 | public Person(String firstName, String lastName, String streetAddress, String city, String state, String zipcode) { 14 | this.firstName = firstName; 15 | this.lastName = lastName; 16 | this.streetAddress = streetAddress; 17 | this.city = city; 18 | this.state = state; 19 | this.zipcode = zipcode; 20 | } 21 | 22 | public static Person[] convertMulti(String input) { 23 | // We're splitting on the pipe symbol ' | ', however, that symbol 24 | // is a special character in regex. The split() method takes input 25 | // of a regex String. So, we must escape the ' | ' symbol with 26 | // two backslashes ' \\ ' to tell the regex engine to interpret 27 | // it literally 28 | String[] peopleStrings = input.split("\\|"); 29 | Person[] people = new Person[peopleStrings.length]; 30 | for (int index=0; index < peopleStrings.length; index++) { 31 | people[index] = convert(peopleStrings[index]); 32 | } 33 | return people; 34 | } 35 | 36 | public static Person convert(String csv) { 37 | String[] parts = csv.split(","); 38 | String firstName = parts[0].strip(); 39 | String lastName = parts[1].strip(); 40 | String streetAddress = parts[2].strip(); 41 | String city = parts[3].strip(); 42 | String state = parts[4].strip(); 43 | String zipcode = parts[5].strip(); 44 | return new Person(firstName, lastName, streetAddress, city, state, zipcode); 45 | } 46 | 47 | @Override 48 | public boolean equals(Object o) { 49 | if (this == o) return true; 50 | if (o == null || getClass() != o.getClass()) return false; 51 | Person person = (Person) o; 52 | return Objects.equals(firstName, person.firstName) && Objects.equals(lastName, person.lastName) && Objects.equals(streetAddress, person.streetAddress) && Objects.equals(city, person.city) && Objects.equals(state, person.state) && Objects.equals(zipcode, person.zipcode); 53 | } 54 | 55 | @Override 56 | public int hashCode() { 57 | return Objects.hash(firstName, lastName, streetAddress, city, state, zipcode); 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section8_more_oop/Exercise1.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section8_more_oop; 2 | 3 | import java.util.Random; 4 | 5 | public class Exercise1 { 6 | enum DayOfWeek { 7 | SUNDAY, 8 | MONDAY, 9 | TUESDAY, 10 | WEDNESDAY, 11 | THURSDAY, 12 | FRIDAY, 13 | SATURDAY 14 | } 15 | public static void main(String[] args) { 16 | for (DayOfWeek day : DayOfWeek.values()) { 17 | System.out.println(day); 18 | } 19 | 20 | // Exercise 1.1 21 | for (DayOfWeek day : DayOfWeek.values()) { 22 | String dayText = day.toString().toLowerCase(); 23 | System.out.println(dayText.substring(0,1).toUpperCase() + dayText.substring(1)); 24 | } 25 | 26 | // Exercise 1.2 27 | int index = 0; 28 | for (DayOfWeek day : DayOfWeek.values()) { 29 | String dayText = day.toString().toLowerCase(); 30 | if (index % 2 == 0) { 31 | System.out.println(dayText.substring(0, 1).toUpperCase() + dayText.substring(1)); 32 | } else { 33 | int middleIndex = dayText.length() / 2; 34 | StringBuilder sb = new StringBuilder(); 35 | sb.append(dayText.substring(0,middleIndex)); 36 | sb.append(dayText.substring(middleIndex, middleIndex+1).toUpperCase()); 37 | sb.append(dayText.substring(middleIndex + 1)); 38 | System.out.println(sb.toString()); 39 | } 40 | index++; 41 | } 42 | 43 | // Exercise 1.3 44 | Random random = new Random(); 45 | for (int counter = 0; counter < 10; counter++) { 46 | int dayIndex = random.nextInt(7); 47 | System.out.println(DayOfWeek.values()[dayIndex]); 48 | } 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section8_more_oop/Exercise4.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section8_more_oop; 2 | 3 | public class Exercise4 { 4 | 5 | public static int convert(char letter) { 6 | return letter - 96; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section8_more_oop/Exercise5.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section8_more_oop; 2 | 3 | public class Exercise5 { 4 | public static char convert(int num) { 5 | return (char)(num + 96); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section8_more_oop/Exercise6.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section8_more_oop; 2 | 3 | public class Exercise6 { 4 | public static void main(String[] args) { 5 | System.out.println(convert(8)); 6 | System.out.println(convert(7)); 7 | System.out.println(convert(6)); 8 | System.out.println(convert(5)); 9 | System.out.println(convert(4)); 10 | System.out.println(convert(3)); 11 | // etc. etc. 12 | } 13 | 14 | private static int convert(int num) { 15 | return 8 - num; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section8_more_oop/Exercise7.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section8_more_oop; 2 | 3 | public class Exercise7 { 4 | public static void main(String[] args) { 5 | System.out.println(getArrayCoords("a8")); 6 | System.out.println(getArrayCoords("h1")); 7 | System.out.println(getArrayCoords("g5")); 8 | System.out.println(getArrayCoords("d4")); 9 | } 10 | 11 | private static String getArrayCoords(String chessCoords) { 12 | char file = chessCoords.charAt(0); 13 | int rank = Integer.parseInt(Character.toString(chessCoords.charAt(1))); 14 | int x = getXForFile(file); 15 | int y = getYForRank(rank); 16 | return String.format("%d, %d", x, y); 17 | } 18 | 19 | private static int getXForFile(char file) { 20 | return file - 97; 21 | } 22 | 23 | private static int getYForRank(int rank) { 24 | return 8 - rank; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section8_more_oop/ex2_3/DayOfWeek.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section8_more_oop.ex2_3; 2 | 3 | public enum DayOfWeek { 4 | SUNDAY("pot roast"), 5 | MONDAY("spaghetti"), 6 | TUESDAY("tacos"), 7 | WEDNESDAY("chicken"), 8 | THURSDAY("meatloaf"), 9 | FRIDAY("hamburgers"), 10 | SATURDAY("pizza"); 11 | 12 | private String meal; 13 | 14 | DayOfWeek(String meal) { 15 | this.meal = meal; 16 | } 17 | 18 | public String getMeal() { 19 | return meal; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section8_more_oop/ex2_3/Exercise2.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section8_more_oop.ex2_3; 2 | 3 | public class Exercise2 { 4 | public static void main(String[] args) { 5 | for(DayOfWeek day : DayOfWeek.values()) { 6 | System.out.printf("We eat %s on %s%n", day.getMeal(), capitalize(day.name())); 7 | } 8 | } 9 | 10 | private static String capitalize(String day) { 11 | String lowercaseDay = day.toLowerCase(); 12 | return lowercaseDay.substring(0,1).toUpperCase() + lowercaseDay.substring(1); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section8_more_oop/ex2_3/Exercise3.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section8_more_oop.ex2_3; 2 | 3 | public class Exercise3 { 4 | public static void main(String[] args) { 5 | String meals = getMealsForDays("friday, thursday, monday, saturday, tuesday"); 6 | System.out.println(meals); 7 | } 8 | 9 | private static String getMealsForDays(String dayCSV) { 10 | String[] days = dayCSV.split(","); 11 | StringBuilder sb = new StringBuilder(); 12 | for (String day : days) { 13 | sb.append(DayOfWeek.valueOf(day.strip().toUpperCase()).getMeal()); 14 | 15 | // notice we add a comma & a space after each meal. 16 | // The last comma-space will need to be removed 17 | // otherwise, we'll return "...pizza, tacos, " 18 | // instead of "...pizza, tacos" 19 | sb.append(", "); 20 | } 21 | 22 | // Get index of the last comma because that needs to be removed 23 | // We could do this by simply getting the length of the StringBuilder minus 2 24 | // (2 because ", " is two characters long and it's at the end of the String) 25 | // (the String of meals we're about to return) OR we could alternatively 26 | // call StringBuilder.lastIndexOf(", "); which would give us the same thing 27 | // Also, need to remove the space character right after the last comma 28 | int lastCommaIndex = sb.length() - 2; 29 | // int lastCommaSpaceIndex = sb.lastIndexOf(", "); 30 | sb.delete(lastCommaIndex, lastCommaIndex + 1); // lastCommaIndex + 1 represents the space following the comma 31 | return sb.toString(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section8_more_oop/ex8/ChessBoard.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section8_more_oop.ex8; 2 | 3 | import java.util.Arrays; 4 | 5 | import static com.neutrinosys.java.foundations.solutions.section8_more_oop.ex8.ChessPiece.Color.WHITE; 6 | 7 | public class ChessBoard { 8 | private ChessPiece[][] internalBoard = new ChessPiece[8][8]; 9 | private ChessPiece[] whiteCapturedPieces = new ChessPiece[0]; 10 | private ChessPiece[] blackCapturedPieces = new ChessPiece[0]; 11 | 12 | public void add(ChessPiece piece, String chessCoords) { 13 | Coordinates coords = new Coordinates(chessCoords); 14 | piece.setCoordinates(coords); 15 | internalBoard[coords.getX()][coords.getY()] = piece; 16 | } 17 | 18 | public ChessPiece getPieceAtCoords(String chessCoords) { 19 | Coordinates coords = new Coordinates(chessCoords); 20 | return internalBoard[coords.getX()][coords.getY()]; 21 | } 22 | 23 | public void move(ChessPiece piece, String destCoords) { 24 | Coordinates origin = piece.coordinates; 25 | Coordinates destination = new Coordinates(destCoords); 26 | if (destinationIsOccupiedByFriendly(piece, destination)) { 27 | return; 28 | } else if (destinationIsOccupiedByEnemy(piece, destination)) { 29 | ChessPiece capturedPiece = getPieceAtCoords(destCoords); 30 | capturedPiece.setCoordinates(null); 31 | if (piece.color == WHITE) { 32 | whiteCapturedPieces = addToCapturedPieces(capturedPiece, whiteCapturedPieces); 33 | } else { 34 | blackCapturedPieces = addToCapturedPieces(capturedPiece, blackCapturedPieces); 35 | } 36 | } 37 | 38 | // if (existsAmongValidMoves(piece.getValidMoves(), destination)) { 39 | performActualMove(piece, destCoords, origin, destination); 40 | } 41 | 42 | private ChessPiece[] addToCapturedPieces(ChessPiece capturedPiece, ChessPiece[] capturedPieces) { 43 | ChessPiece[] tmpCaptures = Arrays.copyOf(capturedPieces, capturedPieces.length + 1); 44 | tmpCaptures[capturedPieces.length] = capturedPiece; 45 | return tmpCaptures; 46 | } 47 | 48 | private void performActualMove(ChessPiece piece, String destCoords, Coordinates origin, Coordinates destination) { 49 | if (destination.isPermittedMove(piece.getValidMoves())) { 50 | internalBoard[origin.getX()][origin.getY()] = null; // remove from original square 51 | add(piece, destCoords); 52 | } 53 | } 54 | 55 | private boolean destinationIsOccupiedByFriendly(ChessPiece piece, Coordinates destination) { 56 | ChessPiece destinationPiece = internalBoard[destination.getX()][destination.getY()]; 57 | return destinationPiece != null && destinationPiece.color == piece.color; 58 | } 59 | 60 | private boolean destinationIsOccupiedByEnemy(ChessPiece piece, Coordinates destination) { 61 | ChessPiece destinationPiece = internalBoard[destination.getX()][destination.getY()]; 62 | return destinationPiece != null && destinationPiece.color != piece.color; 63 | } 64 | 65 | public ChessPiece[] getWhiteCapturedPieces() { 66 | return whiteCapturedPieces; 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section8_more_oop/ex8/ChessPiece.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section8_more_oop.ex8; 2 | 3 | import static com.neutrinosys.java.foundations.solutions.section8_more_oop.ex8.ChessPiece.Color.WHITE; 4 | 5 | public abstract class ChessPiece { 6 | protected Coordinates coordinates; 7 | protected Color color; 8 | 9 | public ChessPiece(Color color) { 10 | this.color = color; 11 | } 12 | 13 | public void setCoordinates(Coordinates coordinates) { 14 | this.coordinates = coordinates; 15 | } 16 | 17 | public Coordinates getCoordinates() { 18 | return coordinates; 19 | } 20 | 21 | protected int calcYWithDirFactor(int yOffset) { 22 | int dirFactor = color == WHITE ? 1 : -1; 23 | return yOffset * dirFactor; 24 | } 25 | 26 | abstract Coordinates[] getValidMoves(); 27 | 28 | enum Color { 29 | BLACK, 30 | WHITE; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section8_more_oop/ex8/Coordinates.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section8_more_oop.ex8; 2 | 3 | import java.util.Objects; 4 | 5 | public class Coordinates { 6 | private final int x; 7 | private final int y; 8 | private String chessCoords; 9 | 10 | public Coordinates(String chessCoords) { 11 | this.chessCoords = chessCoords; 12 | char file = chessCoords.charAt(0); 13 | int rank = Integer.parseInt(Character.toString(chessCoords.charAt(1))); 14 | x = getXForFile(file); 15 | y = getYForRank(rank); 16 | } 17 | 18 | public Coordinates(int x, int y) { 19 | this.x = x; 20 | this.y = y; 21 | } 22 | 23 | public Coordinates getOffset(int x, int y) { 24 | return new Coordinates(this.x + x, this.y + y); 25 | } 26 | 27 | private String getArrayCoords(String chessCoords) { 28 | char file = chessCoords.charAt(0); 29 | int rank = Integer.parseInt(Character.toString(chessCoords.charAt(1))); 30 | int x = getXForFile(file); 31 | int y = getYForRank(rank); 32 | return String.format("%d, %d", x, y); 33 | } 34 | 35 | public boolean isPermittedMove(Coordinates[] moves) { 36 | for (int x=0; x < moves.length; x++) { 37 | if (moves[x].equals(this)) return true; 38 | } 39 | return false; 40 | } 41 | 42 | private int getXForFile(char file) { 43 | return file - 97; 44 | } 45 | 46 | private int getYForRank(int rank) { 47 | return 8 - rank; 48 | } 49 | 50 | public int getX() { 51 | return x; 52 | } 53 | 54 | public int getY() { 55 | return y; 56 | } 57 | 58 | @Override 59 | public boolean equals(Object o) { 60 | if (this == o) return true; 61 | if (o == null || getClass() != o.getClass()) return false; 62 | Coordinates that = (Coordinates) o; 63 | return x == that.x && y == that.y; 64 | } 65 | 66 | @Override 67 | public int hashCode() { 68 | return Objects.hash(x, y); 69 | } 70 | 71 | @Override 72 | public String toString() { 73 | return String.format("%s -> (%d, %d)", chessCoords, x, y); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section8_more_oop/ex8/Knight.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section8_more_oop.ex8; 2 | 3 | public class Knight extends ChessPiece { 4 | public Knight(Color color) { 5 | super(color); 6 | } 7 | 8 | @Override 9 | Coordinates[] getValidMoves() { 10 | Coordinates[] validMoves = new Coordinates[8]; 11 | 12 | validMoves[0] = getCoordinates().getOffset(1, calcYWithDirFactor(-2)); // north-east 13 | validMoves[1] = getCoordinates().getOffset(-1, calcYWithDirFactor(-2)); // north-west 14 | validMoves[2] = getCoordinates().getOffset(2, calcYWithDirFactor(-1)); // east-north 15 | validMoves[3] = getCoordinates().getOffset(2, calcYWithDirFactor(1)); // east-south 16 | validMoves[4] = getCoordinates().getOffset(-2, calcYWithDirFactor(-1)); // west-north 17 | validMoves[5] = getCoordinates().getOffset(-2, calcYWithDirFactor(1)); // west-south 18 | validMoves[6] = getCoordinates().getOffset(1, calcYWithDirFactor(2)); // south-east 19 | validMoves[7] = getCoordinates().getOffset(-1, calcYWithDirFactor(2)); // south-west 20 | return validMoves; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section8_more_oop/ex8/Pawn.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section8_more_oop.ex8; 2 | 3 | 4 | public class Pawn extends ChessPiece { 5 | private boolean hasMoved = false; 6 | 7 | public Pawn(Color color) { 8 | super(color); 9 | } 10 | 11 | public Coordinates[] getValidMoves() { 12 | 13 | int numOfPossibleMoves = hasMoved ? 3 : 4; 14 | Coordinates[] validMoves = new Coordinates[numOfPossibleMoves]; 15 | 16 | Coordinates forwardOne = getCoordinates().getOffset(0, calcYWithDirFactor(-1)); 17 | validMoves[0] = forwardOne; 18 | 19 | Coordinates diagonallyRightOne = getCoordinates().getOffset(1, calcYWithDirFactor(-1)); 20 | validMoves[1] = diagonallyRightOne; 21 | 22 | Coordinates diagonallyLeftOne = getCoordinates().getOffset(-1, calcYWithDirFactor(-1)); 23 | validMoves[2] = diagonallyLeftOne; 24 | 25 | if (!hasMoved) { 26 | Coordinates forwardTwo = getCoordinates().getOffset(0, calcYWithDirFactor(-2)); 27 | validMoves[3] = forwardTwo; 28 | } 29 | return validMoves; 30 | } 31 | 32 | @Override 33 | public void setCoordinates(Coordinates coordinates) { 34 | if (this.coordinates != null) { 35 | hasMoved = true; 36 | } 37 | super.setCoordinates(coordinates); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section9_collections/Exercise1.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section9_collections; 2 | 3 | import java.time.Year; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | public class Exercise1 { 8 | record Car(String make, String model, Year year){} 9 | 10 | public static void main(String[] args) { 11 | List cars = new ArrayList<>(); 12 | cars.add(new Car("Tesla", "S", Year.of(2014))); 13 | cars.add(new Car("Tesla", "X", Year.of(2015))); 14 | cars.add(new Car("Tesla", "3", Year.of(2016))); 15 | cars.add(new Car("Tesla", "Y", Year.of(2017))); 16 | cars.add(new Car("Tesla", "Roadster", Year.of(2009))); 17 | 18 | for (Car car : cars) { 19 | System.out.println(car); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section9_collections/Exercise2.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section9_collections; 2 | 3 | import java.time.Year; 4 | import java.util.HashSet; 5 | import java.util.Set; 6 | 7 | public class Exercise2 { 8 | // I chose to use a nested record only for less typing 9 | // You could model Car as a full class, nested or in separate file. Doesn't matter, but more work 10 | record Car(String make, String model, Year year){} 11 | 12 | public static void main(String[] args) { 13 | Set cars = new HashSet<>(); 14 | cars.add(new Exercise1.Car("Tesla", "S", Year.of(2014))); 15 | cars.add(new Exercise1.Car("Tesla", "X", Year.of(2015))); 16 | cars.add(new Exercise1.Car("Tesla", "X", Year.of(2015))); // duplicate 17 | cars.add(new Exercise1.Car("Tesla", "3", Year.of(2016))); 18 | cars.add(new Exercise1.Car("Tesla", "3", Year.of(2016))); // duplicate 19 | cars.add(new Exercise1.Car("Tesla", "Y", Year.of(2017))); 20 | cars.add(new Exercise1.Car("Tesla", "Roadster", Year.of(2009))); 21 | 22 | // should only print out 5 cars still 23 | for (Exercise1.Car car : cars) { 24 | System.out.println(car); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section9_collections/Exercise3.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section9_collections; 2 | 3 | import java.time.Year; 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | 7 | public class Exercise3 { 8 | record Car(String make, String model, Year year){} 9 | 10 | public static void main(String[] args) { 11 | Map cars = new HashMap<>(); 12 | cars.put("Bob", new Car("Tesla", "S", Year.of(2014))); 13 | cars.put("Jenny", new Car("Tesla", "X", Year.of(2015))); 14 | cars.put("Sarah", new Car("Tesla", "3", Year.of(2016))); 15 | cars.put("John", new Car("Tesla", "Y", Year.of(2017))); 16 | cars.put("Srinath", new Car("Tesla", "Roadster", Year.of(2009))); 17 | 18 | for (Map.Entry entry : cars.entrySet()) { 19 | // '\t' for tab space between owner name & car details - you could use anything to separate 20 | System.out.printf("%s\t%s%n", entry.getKey(), entry.getValue()); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section9_collections/Exercise5.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section9_collections; 2 | 3 | import java.time.Year; 4 | import java.util.Set; 5 | import java.util.TreeSet; 6 | 7 | public class Exercise5 { 8 | record Car(String make, String model, Year year) implements Comparable { 9 | @Override 10 | public int compareTo(Car o) { 11 | return this.model.compareTo(o.model); 12 | } 13 | } 14 | 15 | public static void main(String[] args) { 16 | Set cars = new TreeSet<>(); 17 | cars.add(new Car("Tesla", "S", Year.of(2014))); 18 | cars.add(new Car("Tesla", "X", Year.of(2015))); 19 | cars.add(new Car("Tesla", "X", Year.of(2015))); // duplicate 20 | cars.add(new Car("Tesla", "3", Year.of(2016))); 21 | cars.add(new Car("Tesla", "3", Year.of(2016))); // duplicate 22 | cars.add(new Car("Tesla", "Y", Year.of(2017))); 23 | cars.add(new Car("Tesla", "Roadster", Year.of(2009))); 24 | 25 | // should only print out 5 cars still 26 | for (Car car : cars) { 27 | System.out.println(car); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/neutrinosys/java/foundations/solutions/section9_collections/Exercise6.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section9_collections; 2 | 3 | import java.time.Year; 4 | import java.util.*; 5 | 6 | public class Exercise6 { 7 | record Car(String make, String model, Year year) implements Comparable { 8 | @Override 9 | public int compareTo(Car o) { 10 | return this.model.compareTo(o.model); 11 | } 12 | } 13 | 14 | public static void main(String[] args) { 15 | Set cars = new TreeSet<>(); 16 | cars.add(new Car("Tesla", "S", Year.of(2014))); 17 | cars.add(new Car("Tesla", "X", Year.of(2015))); 18 | cars.add(new Car("Tesla", "X", Year.of(2015))); // duplicate 19 | cars.add(new Car("Tesla", "3", Year.of(2016))); 20 | cars.add(new Car("Tesla", "3", Year.of(2016))); // duplicate 21 | cars.add(new Car("Tesla", "Y", Year.of(2017))); 22 | cars.add(new Car("Tesla", "Roadster", Year.of(2009))); 23 | 24 | for (Iterator it = cars.iterator(); it.hasNext();) { 25 | if (it.next().model().equals(args[0])) { 26 | it.remove(); 27 | } 28 | } 29 | 30 | // should only print out 5 cars still 31 | for (Car car : cars) { 32 | System.out.println(car); 33 | } 34 | 35 | // Code for exercise 8 36 | Car[] carArray = cars.toArray(new Car[0]); 37 | List carList = Arrays.asList(carArray); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/test/java/com/neutrinosys/java/foundations/solutions/section7_testing/Exercise1Test.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section7_testing; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | /** 8 | * You may think of additional tests that make sense, but these are some good ones. 9 | */ 10 | class Exercise1Test { 11 | 12 | /** 13 | * In true TDD fashion, you can start with something simple & obvious and simply 14 | * hard-code the correct answer into your Exercise1 method. 15 | */ 16 | @Test 17 | public void testAlternateCapsWithCat() { 18 | String output = Exercise1.alternateCaps("cat"); 19 | assertEquals("cAt", output); 20 | } 21 | 22 | /** 23 | * However, if you hard-coded the solution in the first test, you'll need a second test 24 | * to force yourself to probably implement the real solution. 25 | */ 26 | @Test 27 | public void testAlternateCapsWithApple() { 28 | String output = Exercise1.alternateCaps("apple"); 29 | assertEquals("aPpLe", output); 30 | } 31 | 32 | /** 33 | * Good idea to test some edge cases, like blank/empty String 34 | */ 35 | @Test 36 | public void testAlternateCapsWithBlank() { 37 | String output = Exercise1.alternateCaps(""); 38 | assertEquals("", output); 39 | } 40 | 41 | /** 42 | * Not sure if this should be considered an edge case, but it's one 43 | * you may not want to just assume the behavior of. 44 | * 45 | * May also want to consider null input, numbers, etc. 46 | */ 47 | @Test 48 | public void testAlternateCapsWithAllCapsApple() { 49 | String output = Exercise1.alternateCaps("APPLE"); 50 | assertEquals("APPLE", output); 51 | } 52 | 53 | } -------------------------------------------------------------------------------- /src/test/java/com/neutrinosys/java/foundations/solutions/section7_testing/Exercise3Test.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section7_testing; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class Exercise3Test { 8 | 9 | @Test 10 | public void trailMix() { 11 | String spoon = Exercise3.spoonerize("trail mix"); 12 | assertEquals("mail trix", spoon); 13 | } 14 | 15 | @Test 16 | public void soundBite() { 17 | String spoon = Exercise3.spoonerize("sound bite"); 18 | assertEquals("bound site", spoon); 19 | } 20 | 21 | @Test 22 | public void flatCap() { 23 | String spoon = Exercise3.spoonerize("flat cap"); 24 | assertEquals("cat flap", spoon); 25 | } 26 | 27 | @Test 28 | public void sadBallad() { 29 | String spoon = Exercise3.spoonerize("sad ballad"); 30 | assertEquals("bad sallad", spoon); 31 | } 32 | 33 | @Test 34 | public void masterPlan() { 35 | String spoon = Exercise3.spoonerize("master plan"); 36 | assertEquals("plaster man", spoon); 37 | } 38 | 39 | @Test 40 | public void trailSnacks() { 41 | String spoon = Exercise3.spoonerize("trail snacks"); 42 | assertEquals("snail tracks", spoon); 43 | } 44 | 45 | @Test 46 | public void crushingBlow() { 47 | String spoon = Exercise3.spoonerize("crushing blow"); 48 | assertEquals("blushing crow", spoon); 49 | } 50 | 51 | } -------------------------------------------------------------------------------- /src/test/java/com/neutrinosys/java/foundations/solutions/section7_testing/ex2/PersonTest.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section7_testing.ex2; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.assertArrayEquals; 6 | import static org.junit.jupiter.api.Assertions.assertEquals; 7 | 8 | class PersonTest { 9 | 10 | @Test 11 | public void canConvertCSVToPerson() { 12 | Person person = Person.convert("Billy, Bob, 1234 Big St., Big City, California, 90210"); 13 | assertEquals(person, new Person("Billy", "Bob", "1234 Big St.", "Big City", "California", "90210")); 14 | } 15 | 16 | @Test 17 | public void canConvertMultiCSVtoPeople() { 18 | String multiCSV = "Billy, Bob, 1234 Big St., Big City, California, 90210|Jackson, Joe, 4321 Little St., Little City, New York, 20109"; 19 | Person[] people = Person.convertMulti(multiCSV); 20 | Person[] expPeople = { 21 | new Person("Billy", "Bob", "1234 Big St.", "Big City", "California", "90210"), 22 | new Person("Jackson", "Joe", "4321 Little St.", "Little City", "New York", "20109") 23 | }; 24 | assertArrayEquals(expPeople, people); 25 | } 26 | 27 | } -------------------------------------------------------------------------------- /src/test/java/com/neutrinosys/java/foundations/solutions/section8_more_oop/Exercise4Test.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section8_more_oop; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.assertEquals; 6 | 7 | class Exercise4Test { 8 | 9 | @Test 10 | public void canConvertA() { 11 | int num = Exercise4.convert('a'); 12 | assertEquals(1, num); 13 | } 14 | 15 | @Test 16 | public void canConvertZ() { 17 | int num = Exercise4.convert('z'); 18 | assertEquals(26, num); 19 | } 20 | 21 | @Test 22 | public void canConvertW() { 23 | int num = Exercise4.convert('w'); 24 | assertEquals(23, num); 25 | } 26 | 27 | @Test 28 | public void canConvertF() { 29 | int num = Exercise4.convert('f'); 30 | assertEquals(6, num); 31 | } 32 | 33 | @Test 34 | public void canConvertC() { 35 | int num = Exercise4.convert('c'); 36 | assertEquals(3, num); 37 | } 38 | 39 | @Test 40 | public void canConvertH() { 41 | int num = Exercise4.convert('h'); 42 | assertEquals(8, num); 43 | } 44 | 45 | } -------------------------------------------------------------------------------- /src/test/java/com/neutrinosys/java/foundations/solutions/section8_more_oop/Exercise5Test.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section8_more_oop; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class Exercise5Test { 8 | 9 | @Test 10 | public void convert1() { 11 | char letter = Exercise5.convert(1); 12 | assertEquals('a', letter); 13 | } 14 | 15 | @Test 16 | public void convert26() { 17 | char letter = Exercise5.convert(26); 18 | assertEquals('z', letter); 19 | } 20 | 21 | @Test 22 | public void convert23() { 23 | char letter = Exercise5.convert(23); 24 | assertEquals('w', letter); 25 | } 26 | 27 | @Test 28 | public void convert6() { 29 | char letter = Exercise5.convert(6); 30 | assertEquals('f', letter); 31 | } 32 | 33 | @Test 34 | public void convert3() { 35 | char letter = Exercise5.convert(3); 36 | assertEquals('c', letter); 37 | } 38 | 39 | @Test 40 | public void convert8() { 41 | char letter = Exercise5.convert(8); 42 | assertEquals('h', letter); 43 | } 44 | } -------------------------------------------------------------------------------- /src/test/java/com/neutrinosys/java/foundations/solutions/section8_more_oop/ex8/ChessBoardTest.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section8_more_oop.ex8; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static com.neutrinosys.java.foundations.solutions.section8_more_oop.ex8.ChessPiece.Color.BLACK; 6 | import static com.neutrinosys.java.foundations.solutions.section8_more_oop.ex8.ChessPiece.Color.WHITE; 7 | import static org.junit.jupiter.api.Assertions.*; 8 | 9 | class ChessBoardTest { 10 | 11 | @Test 12 | public void canAddPawn() { 13 | ChessBoard board = new ChessBoard(); 14 | Pawn pawn = new Pawn(WHITE); 15 | board.add(pawn, "a2"); 16 | Pawn foundPawn = (Pawn) board.getPieceAtCoords("a2"); 17 | assertEquals(pawn, foundPawn); 18 | } 19 | 20 | @Test 21 | public void canAddKnight() { 22 | ChessBoard board = new ChessBoard(); 23 | Knight knight = new Knight(BLACK); 24 | 25 | board.add(knight, "c1"); 26 | 27 | Knight foundKnight = (Knight) board.getPieceAtCoords("c1"); 28 | assertEquals(knight, foundKnight); 29 | } 30 | 31 | @Test 32 | public void canMoveC1KnightToD3() { 33 | ChessBoard board = new ChessBoard(); 34 | Knight knight = new Knight(WHITE); 35 | board.add(knight, "c1"); 36 | assertEquals(knight, board.getPieceAtCoords("c1"), "Knight should initially be @ c1"); 37 | 38 | board.move(knight, "d3"); 39 | 40 | assertNull(board.getPieceAtCoords("c1"), "After move, Knight should no longer be @ c1"); 41 | assertEquals(knight, board.getPieceAtCoords("d3"), "Knight should now be @ d3"); 42 | } 43 | 44 | @Test() 45 | public void canNotMoveC1KnightToInvalidSquare() { 46 | ChessBoard board = new ChessBoard(); 47 | Knight knight = new Knight(WHITE); 48 | board.add(knight, "c1"); 49 | assertEquals(knight, board.getPieceAtCoords("c1"), "Knight should initially be @ c1"); 50 | 51 | board.move(knight, "d4"); 52 | 53 | assertNull(board.getPieceAtCoords("d4"), "After move, Knight should not be @ d4"); 54 | assertEquals(knight, board.getPieceAtCoords("c1"), "Knight should still be @ c1"); 55 | } 56 | 57 | @Test 58 | public void canNotMoveC1KnightToFriendlyOccupiedSquare() { 59 | ChessBoard board = new ChessBoard(); 60 | Pawn pawn = new Pawn(WHITE); 61 | board.add(pawn, "d3"); 62 | Knight knight = new Knight(WHITE); 63 | board.add(knight, "c1"); 64 | assertEquals(knight, board.getPieceAtCoords("c1"), "Knight should initially be @ c1"); 65 | 66 | board.move(knight, "d3"); 67 | 68 | assertEquals(pawn, board.getPieceAtCoords("d3"), "After move attempt, pawn should still be @ d3"); 69 | assertEquals(knight, board.getPieceAtCoords("c1"), "Knight should still be @ c1"); 70 | } 71 | 72 | @Test 73 | public void canMoveC1KnightToEnemyOccupiedSquare() { 74 | ChessBoard board = new ChessBoard(); 75 | Pawn pawn = new Pawn(BLACK); 76 | board.add(pawn, "d3"); 77 | Knight knight = new Knight(WHITE); 78 | board.add(knight, "c1"); 79 | assertEquals(knight, board.getPieceAtCoords("c1"), "Knight should initially be @ c1"); 80 | 81 | board.move(knight, "d3"); 82 | 83 | assertTrue(elementExists(board.getWhiteCapturedPieces(), pawn), "Pawn should now be among white's captured pieces"); 84 | assertEquals(knight, board.getPieceAtCoords("d3"), "Knight should now be @ d3"); 85 | } 86 | 87 | private boolean elementExists(Object[] array, Object element) { 88 | for (Object object : array) { 89 | if (object == element) return true; 90 | } 91 | return false; 92 | } 93 | 94 | } -------------------------------------------------------------------------------- /src/test/java/com/neutrinosys/java/foundations/solutions/section8_more_oop/ex8/ChessPieceTest.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section8_more_oop.ex8; 2 | 3 | public class ChessPieceTest { 4 | protected boolean isMoveFoundInArray(Coordinates[] moves, Coordinates expectedMove) { 5 | for (int x=0; x < moves.length; x++) { 6 | if (moves[x].equals(expectedMove)) return true; 7 | } 8 | return false; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/test/java/com/neutrinosys/java/foundations/solutions/section8_more_oop/ex8/KnightTest.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section8_more_oop.ex8; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static com.neutrinosys.java.foundations.solutions.section8_more_oop.ex8.ChessPiece.Color.BLACK; 6 | import static com.neutrinosys.java.foundations.solutions.section8_more_oop.ex8.ChessPiece.Color.WHITE; 7 | import static org.junit.jupiter.api.Assertions.*; 8 | 9 | class KnightTest extends ChessPieceTest { 10 | 11 | @Test 12 | public void knightCanMoveNorthEast() { 13 | Knight knight = new Knight(WHITE); 14 | knight.setCoordinates(new Coordinates("c1")); 15 | Coordinates[] validMoves = knight.getValidMoves(); 16 | Coordinates expectedDestination = new Coordinates("d3"); 17 | assertTrue(isMoveFoundInArray(validMoves, expectedDestination)); 18 | } 19 | 20 | @Test 21 | public void knightCanMoveNorthWest() { 22 | Knight knight = new Knight(WHITE); 23 | knight.setCoordinates(new Coordinates("c1")); 24 | Coordinates[] validMoves = knight.getValidMoves(); 25 | Coordinates expectedDestination = new Coordinates("b3"); 26 | assertTrue(isMoveFoundInArray(validMoves, expectedDestination)); 27 | } 28 | 29 | @Test 30 | public void knightCanMoveEastNorth() { 31 | Knight knight = new Knight(WHITE); 32 | knight.setCoordinates(new Coordinates("c1")); 33 | Coordinates[] validMoves = knight.getValidMoves(); 34 | Coordinates expectedDestination = new Coordinates("e2"); 35 | assertTrue(isMoveFoundInArray(validMoves, expectedDestination)); 36 | } 37 | 38 | @Test 39 | public void knightCanMoveEastSouth() { 40 | Knight knight = new Knight(WHITE); 41 | knight.setCoordinates(new Coordinates("c3")); 42 | Coordinates[] validMoves = knight.getValidMoves(); 43 | Coordinates expectedDestination = new Coordinates("e2"); 44 | assertTrue(isMoveFoundInArray(validMoves, expectedDestination)); 45 | } 46 | 47 | @Test 48 | public void knightCanMoveWestNorth() { 49 | Knight knight = new Knight(WHITE); 50 | knight.setCoordinates(new Coordinates("c3")); 51 | Coordinates[] validMoves = knight.getValidMoves(); 52 | Coordinates expectedDestination = new Coordinates("a4"); 53 | assertTrue(isMoveFoundInArray(validMoves, expectedDestination)); 54 | } 55 | 56 | @Test 57 | public void knightCanMoveWestSouth() { 58 | Knight knight = new Knight(WHITE); 59 | knight.setCoordinates(new Coordinates("c3")); 60 | Coordinates[] validMoves = knight.getValidMoves(); 61 | Coordinates expectedDestination = new Coordinates("a2"); 62 | assertTrue(isMoveFoundInArray(validMoves, expectedDestination)); 63 | } 64 | 65 | @Test 66 | public void knightCanMoveSouthEast() { 67 | Knight knight = new Knight(WHITE); 68 | knight.setCoordinates(new Coordinates("c3")); 69 | Coordinates[] validMoves = knight.getValidMoves(); 70 | Coordinates expectedDestination = new Coordinates("d1"); 71 | assertTrue(isMoveFoundInArray(validMoves, expectedDestination)); 72 | } 73 | 74 | @Test 75 | public void knightCanMoveSouthWest() { 76 | Knight knight = new Knight(WHITE); 77 | knight.setCoordinates(new Coordinates("c3")); 78 | Coordinates[] validMoves = knight.getValidMoves(); 79 | Coordinates expectedDestination = new Coordinates("b1"); 80 | assertTrue(isMoveFoundInArray(validMoves, expectedDestination)); 81 | } 82 | 83 | @Test 84 | public void blackKnightCanMoveSouthWest() { 85 | Knight knight = new Knight(BLACK); 86 | knight.setCoordinates(new Coordinates("d5")); 87 | Coordinates[] validMoves = knight.getValidMoves(); 88 | Coordinates expectedDestination = new Coordinates("c7"); 89 | assertTrue(isMoveFoundInArray(validMoves, expectedDestination)); 90 | } 91 | 92 | } -------------------------------------------------------------------------------- /src/test/java/com/neutrinosys/java/foundations/solutions/section8_more_oop/ex8/PawnTest.java: -------------------------------------------------------------------------------- 1 | package com.neutrinosys.java.foundations.solutions.section8_more_oop.ex8; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static com.neutrinosys.java.foundations.solutions.section8_more_oop.ex8.ChessPiece.Color.BLACK; 6 | import static com.neutrinosys.java.foundations.solutions.section8_more_oop.ex8.ChessPiece.Color.WHITE; 7 | import static org.junit.jupiter.api.Assertions.assertFalse; 8 | import static org.junit.jupiter.api.Assertions.assertTrue; 9 | 10 | class PawnTest extends ChessPieceTest { 11 | 12 | @Test 13 | public void pawnCanMoveOneForward() { 14 | Pawn pawn = new Pawn(WHITE); 15 | pawn.setCoordinates(new Coordinates("a2")); 16 | Coordinates[] validMoves = pawn.getValidMoves(); 17 | Coordinates expectedDestination = new Coordinates("a3"); 18 | // assertEquals(expectedDestination, validMoves[0]); 19 | assertTrue(isMoveFoundInArray(validMoves, expectedDestination), String.format("Move '%s' not found.", expectedDestination)); 20 | } 21 | 22 | @Test 23 | public void pawnCanMoveTwoForwardOnFirstMove() { 24 | Pawn pawn = new Pawn(WHITE); 25 | pawn.setCoordinates(new Coordinates("a2")); 26 | Coordinates[] validMoves = pawn.getValidMoves(); 27 | Coordinates expectedDestination = new Coordinates("a4"); 28 | assertTrue(isMoveFoundInArray(validMoves, expectedDestination)); 29 | } 30 | 31 | @Test 32 | public void canNotMoveTwoAfterFirstMove() { 33 | Pawn pawn = new Pawn(WHITE); 34 | pawn.setCoordinates(new Coordinates("a2")); 35 | pawn.setCoordinates(new Coordinates("a3")); 36 | Coordinates[] validMoves = pawn.getValidMoves(); 37 | Coordinates expectedDestination = new Coordinates("a5"); 38 | assertFalse(isMoveFoundInArray(validMoves, expectedDestination)); 39 | } 40 | 41 | @Test 42 | public void canMoveOneDiagonallyRight() { 43 | Pawn pawn = new Pawn(WHITE); 44 | pawn.setCoordinates(new Coordinates("a2")); 45 | Coordinates[] validMoves = pawn.getValidMoves(); 46 | assertTrue(isMoveFoundInArray(validMoves, new Coordinates("b3"))); 47 | } 48 | 49 | @Test 50 | public void canMoveOneDiagonallyLeft() { 51 | Pawn pawn = new Pawn(WHITE); 52 | pawn.setCoordinates(new Coordinates("b2")); 53 | Coordinates[] validMoves = pawn.getValidMoves(); 54 | assertTrue(isMoveFoundInArray(validMoves, new Coordinates("a3"))); 55 | } 56 | 57 | @Test 58 | public void blackPawnCanMoveOneForward() { 59 | Pawn pawn = new Pawn(BLACK); 60 | pawn.setCoordinates(new Coordinates("a7")); 61 | Coordinates[] validMoves = pawn.getValidMoves(); 62 | Coordinates expectedDestination = new Coordinates("a6"); 63 | assertTrue(isMoveFoundInArray(validMoves, expectedDestination)); 64 | } 65 | 66 | @Test 67 | public void blackPawnCanMoveTwoForwardOnFirstMove() { 68 | Pawn pawn = new Pawn(BLACK); 69 | pawn.setCoordinates(new Coordinates("b7")); 70 | Coordinates[] validMoves = pawn.getValidMoves(); 71 | Coordinates expectedDestination = new Coordinates("b5"); 72 | assertTrue(isMoveFoundInArray(validMoves, expectedDestination)); 73 | } 74 | 75 | 76 | } --------------------------------------------------------------------------------