From f44f03150eb819f48cf4a7bab732af30d91dc83c Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Mon, 5 Jul 2021 19:20:25 +0300 Subject: [PATCH 01/69] Change "Hello World" to "Hello Russia" --- src/main/java/Main.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/Main.java b/src/main/java/Main.java index 9f28e436..480e20d3 100644 --- a/src/main/java/Main.java +++ b/src/main/java/Main.java @@ -1,7 +1,7 @@ public class Main { public static void main(String[] args) { - System.out.println("Hello, World!"); + System.out.println("Hello, Russia"); } } From c82e811d2a5c6305907d2267b958ce941259a8b9 Mon Sep 17 00:00:00 2001 From: Ilia Date: Mon, 5 Jul 2021 19:53:41 +0300 Subject: [PATCH 02/69] Change "Hello, Russia" to "Hello, Epam" --- gradlew | 0 src/main/java/Main.java | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) mode change 100644 => 100755 gradlew diff --git a/gradlew b/gradlew old mode 100644 new mode 100755 diff --git a/src/main/java/Main.java b/src/main/java/Main.java index 480e20d3..7f6b1170 100644 --- a/src/main/java/Main.java +++ b/src/main/java/Main.java @@ -1,7 +1,7 @@ public class Main { public static void main(String[] args) { - System.out.println("Hello, Russia"); + System.out.println("Hello, Epam"); } } From 67e53ab7e55c8462f6fbc1aad36f0c67da6ae49f Mon Sep 17 00:00:00 2001 From: Ilia Date: Mon, 5 Jul 2021 20:04:25 +0300 Subject: [PATCH 03/69] .gitignore update --- .gitignore | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 8a0a60d2..2b1fb1b8 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,7 @@ # Project exclude paths /.gradle/ /build/ -/build/classes/java/main/ \ No newline at end of file +/build/classes/java/main/ +/.idea/ +/gradle/ +/.DS_Store/ \ No newline at end of file From 58734b17fbb29d5f69bd6b1c32a2533e2725c59e Mon Sep 17 00:00:00 2001 From: Ilia Date: Tue, 6 Jul 2021 02:32:19 +0300 Subject: [PATCH 04/69] Add new folder called homework_1 and complete homework --- src/main/java/homework_1/CharCount.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 src/main/java/homework_1/CharCount.java diff --git a/src/main/java/homework_1/CharCount.java b/src/main/java/homework_1/CharCount.java new file mode 100644 index 00000000..9154000d --- /dev/null +++ b/src/main/java/homework_1/CharCount.java @@ -0,0 +1,18 @@ +package homework_1; + +public class CharCount { + public static final String RED_BOLD = "\033[1;31m"; + + public static void main(String[] args) { + System.out.println("Count of Char's in words:"); + for (String arg : args) { + if (arg.equals("ошибка")) { + System.out.println(RED_BOLD + "Тревога!"); + break; + } else { + System.out.println(arg + ": " + arg.toCharArray().length); + } + } + } + +} From 0fcb85494ed06e543f497cb430c34ff1bf19ae55 Mon Sep 17 00:00:00 2001 From: Ilia Date: Tue, 6 Jul 2021 02:46:15 +0300 Subject: [PATCH 05/69] Edit args output a bit --- src/main/java/homework_1/CharCount.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/homework_1/CharCount.java b/src/main/java/homework_1/CharCount.java index 9154000d..b3833ff4 100644 --- a/src/main/java/homework_1/CharCount.java +++ b/src/main/java/homework_1/CharCount.java @@ -10,7 +10,7 @@ public static void main(String[] args) { System.out.println(RED_BOLD + "Тревога!"); break; } else { - System.out.println(arg + ": " + arg.toCharArray().length); + System.out.println(arg + ": " + arg.length()); } } } From e4d75d5035143e3735827bc8ff9d3b9392f29471 Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Tue, 6 Jul 2021 14:12:42 +0300 Subject: [PATCH 06/69] Change russian words to english --- src/main/java/homework_1/CharCount.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/homework_1/CharCount.java b/src/main/java/homework_1/CharCount.java index b3833ff4..e4514f66 100644 --- a/src/main/java/homework_1/CharCount.java +++ b/src/main/java/homework_1/CharCount.java @@ -6,8 +6,8 @@ public class CharCount { public static void main(String[] args) { System.out.println("Count of Char's in words:"); for (String arg : args) { - if (arg.equals("ошибка")) { - System.out.println(RED_BOLD + "Тревога!"); + if (arg.equals("error")) { + System.out.println(RED_BOLD + "Alarm!"); break; } else { System.out.println(arg + ": " + arg.length()); From 56a06cf0958270c4ca1e54bc589f746421de9f44 Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Tue, 6 Jul 2021 20:14:19 +0300 Subject: [PATCH 07/69] Update .gitignore --- .gitignore | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 2b1fb1b8..e9ca4654 100644 --- a/.gitignore +++ b/.gitignore @@ -4,4 +4,5 @@ /build/classes/java/main/ /.idea/ /gradle/ -/.DS_Store/ \ No newline at end of file +/.DS_Store/ +/gradlew \ No newline at end of file From f5f49ac36fa0283dbbc02409662e9f5d52490f62 Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Wed, 7 Jul 2021 13:16:13 +0300 Subject: [PATCH 08/69] Add if(args.length == 0) validation --- src/main/java/homework_1/CharCount.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/main/java/homework_1/CharCount.java b/src/main/java/homework_1/CharCount.java index e4514f66..25a1d5c4 100644 --- a/src/main/java/homework_1/CharCount.java +++ b/src/main/java/homework_1/CharCount.java @@ -4,6 +4,12 @@ public class CharCount { public static final String RED_BOLD = "\033[1;31m"; public static void main(String[] args) { + if (args.length == 0) + { + System.out.println("There is no parameters, exit program."); + } + else { + System.out.println("Count of Char's in words:"); for (String arg : args) { if (arg.equals("error")) { @@ -13,6 +19,7 @@ public static void main(String[] args) { System.out.println(arg + ": " + arg.length()); } } + } } } From 8201f13cb3619916bd48da20679d1cc2136b14b9 Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Wed, 7 Jul 2021 21:34:44 +0300 Subject: [PATCH 09/69] Update .gitignore --- .gitignore | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index e9ca4654..6bf4d305 100644 --- a/.gitignore +++ b/.gitignore @@ -5,4 +5,6 @@ /.idea/ /gradle/ /.DS_Store/ -/gradlew \ No newline at end of file +/gradlew +/gradlew.bat +/settings.gradle \ No newline at end of file From 3b147852901a912c9149bfdf0e29d7acc3c3e96f Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Wed, 7 Jul 2021 21:38:55 +0300 Subject: [PATCH 10/69] Delete unnecessary files --- gradlew | 185 ------------------------------------------------ gradlew.bat | 89 ----------------------- settings.gradle | 2 - 3 files changed, 276 deletions(-) delete mode 100755 gradlew delete mode 100644 gradlew.bat delete mode 100644 settings.gradle diff --git a/gradlew b/gradlew deleted file mode 100755 index 4f906e0c..00000000 --- a/gradlew +++ /dev/null @@ -1,185 +0,0 @@ -#!/usr/bin/env sh - -# -# Copyright 2015 the original author or authors. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -############################################################################## -## -## Gradle start up script for UN*X -## -############################################################################## - -# Attempt to set APP_HOME -# Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi -done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" - -warn () { - echo "$*" -} - -die () { - echo - echo "$*" - echo - exit 1 -} - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; -esac - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." -fi - -# Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi -fi - -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi - -# For Cygwin or MSYS, switch paths to Windows format before running java -if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi - # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" - fi - i=`expr $i + 1` - done - case $i in - 0) set -- ;; - 1) set -- "$args0" ;; - 2) set -- "$args0" "$args1" ;; - 3) set -- "$args0" "$args1" "$args2" ;; - 4) set -- "$args0" "$args1" "$args2" "$args3" ;; - 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac -fi - -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=`save "$@"` - -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" - -exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat deleted file mode 100644 index 107acd32..00000000 --- a/gradlew.bat +++ /dev/null @@ -1,89 +0,0 @@ -@rem -@rem Copyright 2015 the original author or authors. -@rem -@rem Licensed under the Apache License, Version 2.0 (the "License"); -@rem you may not use this file except in compliance with the License. -@rem You may obtain a copy of the License at -@rem -@rem https://www.apache.org/licenses/LICENSE-2.0 -@rem -@rem Unless required by applicable law or agreed to in writing, software -@rem distributed under the License is distributed on an "AS IS" BASIS, -@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -@rem See the License for the specific language governing permissions and -@rem limitations under the License. -@rem - -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Resolve any "." and ".." in APP_HOME to make it shorter. -for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto execute - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto execute - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/settings.gradle b/settings.gradle deleted file mode 100644 index 61b34d09..00000000 --- a/settings.gradle +++ /dev/null @@ -1,2 +0,0 @@ -rootProject.name = 'Java Core June 2021' - From 7e09d62c69953e3b24ce32e3a9a3d51d9324ba16 Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Wed, 7 Jul 2021 21:43:44 +0300 Subject: [PATCH 11/69] Add README.md and update .gitignore --- .gitignore | 6 ++---- README.md | 6 +++--- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/.gitignore b/.gitignore index d36c0316..0abf35df 100644 --- a/.gitignore +++ b/.gitignore @@ -35,9 +35,7 @@ out target *.iml .idea -/.idea/ -/gradle/ -/.DS_Store/ /gradlew /gradlew.bat -/settings.gradle \ No newline at end of file +/settings.gradle +/build.gradle \ No newline at end of file diff --git a/README.md b/README.md index 5d686e9f..96157819 100644 --- a/README.md +++ b/README.md @@ -2,8 +2,8 @@ ## *Nikolaev Artem* -| Number | Solution | Short description +| Index | Solution | Short description | --- | --- | --- | -| HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/master/src/main/java/homework_1) | The app that reads input arguments and prints them, until "error" argument | +| HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_1) | The app that reads input arguments and prints them, until "error" argument | + -[Link to markdown giude](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) From 6898d5c1eeef2fb85955a15df4b3a8b639aab649 Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Wed, 7 Jul 2021 21:45:03 +0300 Subject: [PATCH 12/69] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 96157819..5d2c93f0 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Java Core June 2021 -## *Nikolaev Artem* +## *Prokofev Ilia* | Index | Solution | Short description | --- | --- | --- | From 5d50400e3cd272690f2120b0c5d307ebcd29fda9 Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Wed, 7 Jul 2021 21:46:07 +0300 Subject: [PATCH 13/69] Delete build.gradle --- build.gradle | 19 ------------------- 1 file changed, 19 deletions(-) delete mode 100644 build.gradle diff --git a/build.gradle b/build.gradle deleted file mode 100644 index b91dc843..00000000 --- a/build.gradle +++ /dev/null @@ -1,19 +0,0 @@ -plugins { - id 'java' -} - -group 'epam.javacore' -version '1.0-SNAPSHOT' - -repositories { - mavenCentral() -} - -dependencies { - testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0' - testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0' -} - -test { - useJUnitPlatform() -} \ No newline at end of file From 5477b927b32d33109e8a23fef279e445054c6bc9 Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Wed, 7 Jul 2021 21:47:38 +0300 Subject: [PATCH 14/69] Delete Main.java from wrong folder --- src/main/java/homework_1/Main.java | 10 ---------- 1 file changed, 10 deletions(-) delete mode 100644 src/main/java/homework_1/Main.java diff --git a/src/main/java/homework_1/Main.java b/src/main/java/homework_1/Main.java deleted file mode 100644 index 848afca2..00000000 --- a/src/main/java/homework_1/Main.java +++ /dev/null @@ -1,10 +0,0 @@ -package homework_1; - -public class Main { - - public static void main(String[] args) { - System.out.println("Hello, Epam"); - System.out.println("Hello homework!"); - } - -} From 6af1c99fff23491f2409a53de02463a52a619a17 Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Fri, 9 Jul 2021 13:28:52 +0300 Subject: [PATCH 15/69] Ignore .gitignore for push --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 0abf35df..5061f0d7 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,7 @@ /.idea/ /gradle/ /.DS_Store/ +/.gitignore # Compiled class file *.class From ee5f09cfbe1b5c425c4c0194505f4f06b707fc84 Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Fri, 9 Jul 2021 13:29:39 +0300 Subject: [PATCH 16/69] Delete .gitignore from remote repo --- .gitignore | 42 ------------------------------------------ 1 file changed, 42 deletions(-) delete mode 100644 .gitignore diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 5061f0d7..00000000 --- a/.gitignore +++ /dev/null @@ -1,42 +0,0 @@ -# Project exclude paths -/.gradle/ -/build/ -/build/classes/java/main/ -/.idea/ -/gradle/ -/.DS_Store/ -/.gitignore - -# Compiled class file -*.class - -# Log file -*.log - -# BlueJ files -*.ctxt - -# Mobile Tools for Java (J2ME) -.mtj.tmp/ - -# Package Files # -*.jar -*.war -*.nar -*.ear -*.zip -*.tar.gz -*.rar - -# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml -hs_err_pid* - -#Ignore files -out -target -*.iml -.idea -/gradlew -/gradlew.bat -/settings.gradle -/build.gradle \ No newline at end of file From 3f56714f8429d720acc7c7c4dc2f47808833a3af Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Fri, 9 Jul 2021 13:29:39 +0300 Subject: [PATCH 17/69] Restore .gitignore to remote repo --- .gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 5061f0d7..229f7f57 100644 --- a/.gitignore +++ b/.gitignore @@ -5,7 +5,7 @@ /.idea/ /gradle/ /.DS_Store/ -/.gitignore + # Compiled class file *.class From 13ff7901d6e18779d3fdd3cd01cd526e587a7935 Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Fri, 9 Jul 2021 13:54:55 +0300 Subject: [PATCH 18/69] Restore .gitignore to remote repo --- .gitignore | 1 - 1 file changed, 1 deletion(-) diff --git a/.gitignore b/.gitignore index 229f7f57..0abf35df 100644 --- a/.gitignore +++ b/.gitignore @@ -6,7 +6,6 @@ /gradle/ /.DS_Store/ - # Compiled class file *.class From c998ab110ac3a9a0a29af0a1df5974115caf976e Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Fri, 9 Jul 2021 14:26:08 +0300 Subject: [PATCH 19/69] Fix indentation and RED-text output --- src/main/java/homework_1/CharCount.java | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/main/java/homework_1/CharCount.java b/src/main/java/homework_1/CharCount.java index 25a1d5c4..8cd25d10 100644 --- a/src/main/java/homework_1/CharCount.java +++ b/src/main/java/homework_1/CharCount.java @@ -1,8 +1,6 @@ package homework_1; public class CharCount { - public static final String RED_BOLD = "\033[1;31m"; - public static void main(String[] args) { if (args.length == 0) { @@ -13,13 +11,11 @@ public static void main(String[] args) { System.out.println("Count of Char's in words:"); for (String arg : args) { if (arg.equals("error")) { - System.out.println(RED_BOLD + "Alarm!"); + System.err.println("Alarm!"); break; - } else { - System.out.println(arg + ": " + arg.length()); } + System.out.println(arg + ": " + arg.length()); } } } - } From 265a86f9ae9d04c0758ba38eed8b6a636e2b0619 Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Fri, 9 Jul 2021 14:46:02 +0300 Subject: [PATCH 20/69] Restore deleted files --- .gitignore | 6 +- build.gradle | 19 +++++ gradlew | 185 ++++++++++++++++++++++++++++++++++++++++++++++++ gradlew.bat | 89 +++++++++++++++++++++++ settings.gradle | 2 + 5 files changed, 296 insertions(+), 5 deletions(-) create mode 100644 build.gradle create mode 100644 gradlew create mode 100644 gradlew.bat create mode 100644 settings.gradle diff --git a/.gitignore b/.gitignore index 0abf35df..14f3f265 100644 --- a/.gitignore +++ b/.gitignore @@ -34,8 +34,4 @@ hs_err_pid* out target *.iml -.idea -/gradlew -/gradlew.bat -/settings.gradle -/build.gradle \ No newline at end of file +.idea \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 00000000..b91dc843 --- /dev/null +++ b/build.gradle @@ -0,0 +1,19 @@ +plugins { + id 'java' +} + +group 'epam.javacore' +version '1.0-SNAPSHOT' + +repositories { + mavenCentral() +} + +dependencies { + testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0' + testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0' +} + +test { + useJUnitPlatform() +} \ No newline at end of file diff --git a/gradlew b/gradlew new file mode 100644 index 00000000..4f906e0c --- /dev/null +++ b/gradlew @@ -0,0 +1,185 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=`expr $i + 1` + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 00000000..107acd32 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 00000000..61b34d09 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = 'Java Core June 2021' + From 121d8e27f7793e48c5f17c9a6a1e6a6350d0f359 Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Fri, 9 Jul 2021 16:09:17 +0300 Subject: [PATCH 21/69] Fix indentation --- src/main/java/homework_1/CharCount.java | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/src/main/java/homework_1/CharCount.java b/src/main/java/homework_1/CharCount.java index 8cd25d10..3da0d42a 100644 --- a/src/main/java/homework_1/CharCount.java +++ b/src/main/java/homework_1/CharCount.java @@ -2,20 +2,18 @@ public class CharCount { public static void main(String[] args) { - if (args.length == 0) - { + if (args.length == 0) { System.out.println("There is no parameters, exit program."); - } - else { + } else { - System.out.println("Count of Char's in words:"); - for (String arg : args) { - if (arg.equals("error")) { - System.err.println("Alarm!"); - break; - } + System.out.println("Count of Char's in words:"); + for (String arg : args) { + if (arg.equals("error")) { + System.err.println("Alarm!"); + break; + } System.out.println(arg + ": " + arg.length()); - } + } } } } From 0421d59bcce2bf86b82c25cbee9895bfdc5ec759 Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Mon, 12 Jul 2021 00:17:42 +0300 Subject: [PATCH 22/69] Refactoring --- src/main/java/homework_1/CharCount.java | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/src/main/java/homework_1/CharCount.java b/src/main/java/homework_1/CharCount.java index 3da0d42a..87b1da54 100644 --- a/src/main/java/homework_1/CharCount.java +++ b/src/main/java/homework_1/CharCount.java @@ -2,18 +2,12 @@ public class CharCount { public static void main(String[] args) { - if (args.length == 0) { - System.out.println("There is no parameters, exit program."); - } else { - - System.out.println("Count of Char's in words:"); - for (String arg : args) { - if (arg.equals("error")) { - System.err.println("Alarm!"); - break; - } - System.out.println(arg + ": " + arg.length()); + for (String arg : args) { + if (arg.equals("error")) { + System.err.println("Alarm!"); + break; } + System.out.println(arg + ": " + arg.length() + " letters"); } } } From d1f46cb7ce29511258bb60f56401f629e016d16e Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Mon, 12 Jul 2021 11:09:24 +0300 Subject: [PATCH 23/69] Refactoring --- src/main/java/homework_1/CharCount.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/homework_1/CharCount.java b/src/main/java/homework_1/CharCount.java index 87b1da54..f2ba9288 100644 --- a/src/main/java/homework_1/CharCount.java +++ b/src/main/java/homework_1/CharCount.java @@ -6,8 +6,9 @@ public static void main(String[] args) { if (arg.equals("error")) { System.err.println("Alarm!"); break; + } else { + System.out.println(arg + ": " + arg.length() + " letters"); } - System.out.println(arg + ": " + arg.length() + " letters"); } } -} +} \ No newline at end of file From 2fc8a831f5f1a9957e1dfe2114bfb6ad5b508038 Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Mon, 12 Jul 2021 16:23:24 +0300 Subject: [PATCH 24/69] Final refactoring --- src/main/java/homework_1/CharCount.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/main/java/homework_1/CharCount.java b/src/main/java/homework_1/CharCount.java index f2ba9288..a930c463 100644 --- a/src/main/java/homework_1/CharCount.java +++ b/src/main/java/homework_1/CharCount.java @@ -1,10 +1,13 @@ package homework_1; public class CharCount { + public static final String ANSI_RED = "\u001B[31m"; + public static final String ANSI_RESET = "\u001B[0m"; + public static void main(String[] args) { for (String arg : args) { if (arg.equals("error")) { - System.err.println("Alarm!"); + System.out.println(ANSI_RED + "Alarm!" + ANSI_RESET); break; } else { System.out.println(arg + ": " + arg.length() + " letters"); From 03eb76fea76a6a52240447e1160144165705cdb0 Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Wed, 14 Jul 2021 20:21:58 +0300 Subject: [PATCH 25/69] Complete Homework_2 --- .../pyramid_printer/PyramidPrinter.java | 18 +++ .../random_chars_table/RandomCharsTable.java | 62 ++++++++++ .../homework_2/traffic_light/ColorTable.java | 8 ++ .../traffic_light/TrafficLight.java | 117 ++++++++++++++++++ 4 files changed, 205 insertions(+) create mode 100644 src/main/java/homework_2/pyramid_printer/PyramidPrinter.java create mode 100644 src/main/java/homework_2/random_chars_table/RandomCharsTable.java create mode 100644 src/main/java/homework_2/traffic_light/ColorTable.java create mode 100644 src/main/java/homework_2/traffic_light/TrafficLight.java diff --git a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java new file mode 100644 index 00000000..67aaab69 --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -0,0 +1,18 @@ +package homework_2.pyramid_printer; + +import java.util.Scanner; + +public class PyramidPrinter { + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + System.out.println("Enter a valid INT value for create a pyramid:"); + int x = scanner.nextInt(); + + for (int i = 1; i <= x; ++i) { + for (int j = 1; j <= i; ++j) { + System.out.print(x); + } + System.out.println(); + } + } +} diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java new file mode 100644 index 00000000..49fb1a0c --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -0,0 +1,62 @@ +package homework_2.random_chars_table; + +import java.lang.reflect.Array; +import java.util.InputMismatchException; +import java.util.Random; +import java.util.Scanner; + +public class RandomCharsTable { + public static Scanner scanner = new Scanner(System.in); + private static int length; + private static int width; + + public static void main(String[] args) { + System.out.println("Enter valid length, width and strategy in format \"length width strategy\" "); + printRandomCharsTable(); + } + + public static void printRandomCharsTable() { + try { + length = scanner.nextInt(); + width = scanner.nextInt(); + String strategy = scanner.next(); + char[][] table = new char[length][width]; + + Random random = new Random(); + + for (int i = 0; i < length; i++) { + for (int j = 0; j < width; j++) { + table[i][j] = (char) (random.nextInt((90 - 65) + 1) + 65); + System.out.print("|" + table[i][j] + "|"); + } + System.out.println(); + } + checkStratAndExecute(strategy, table); + } catch (InputMismatchException e) { + System.out.println("You entered invalid value, try again."); + System.exit(0); + } + } + + private static void checkStratAndExecute(String strat, char[][] table) { + if (strat.equals("even")) { + System.out.print("Even letters - "); + for (int i = 0; i < length; i++) { + for (int j = 0; j < width; j++) { + if (table[i][j] % 2 == 0) { + System.out.print(table[i][j] + " "); + } + } + } + } else if (strat.equals("odd")) { + System.out.print("Odd letters - "); + for (int i = 0; i < length; i++) { + for (int j = 0; j < width; j++) { + if (table[i][j] % 2 != 0) { + System.out.print(table[i][j] + " "); + } + } + } + } + } +} diff --git a/src/main/java/homework_2/traffic_light/ColorTable.java b/src/main/java/homework_2/traffic_light/ColorTable.java new file mode 100644 index 00000000..c7e09799 --- /dev/null +++ b/src/main/java/homework_2/traffic_light/ColorTable.java @@ -0,0 +1,8 @@ +package homework_2.traffic_light; + +public class ColorTable { + public static final String ANSI_RESET = "\u001B[0m"; + public static final String ANSI_RED = "\u001B[31m"; + public static final String ANSI_GREEN = "\u001B[32m"; + public static final String ANSI_YELLOW = "\u001B[33m"; +} diff --git a/src/main/java/homework_2/traffic_light/TrafficLight.java b/src/main/java/homework_2/traffic_light/TrafficLight.java new file mode 100644 index 00000000..f0132055 --- /dev/null +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -0,0 +1,117 @@ +package homework_2.traffic_light; + +import java.util.Arrays; +import java.util.InputMismatchException; +import java.util.Scanner; + +import static homework_2.traffic_light.ColorTable.*; + +public class TrafficLight { + private static Scanner scan = new Scanner(System.in); + + public static void main(String[] args) { + System.out.println("Pick mode: 1 - provide seconds, 2 - provide time in format \"hh:mm:ss\": "); + try { + int mode = scan.nextInt(); + selectMode(mode); + } catch (InputMismatchException e) { + System.out.println("Only 1 or 2 allow"); + } + scan.close(); + } + + private static void getSeconds(int seconds) { + int sec = seconds % 60; + if (sec >= 0 && sec < 35) { + System.out.println(pickColor("green")); + } else if ((sec >= 35 && sec < 40) || sec >= 55) { + System.out.println(pickColor("yellow")); + } else { + System.out.println(pickColor("red")); + } + } + + private static void selectMode(int mode) { + if (mode == 1) { + firstMode(); + } else if (mode == 2) { + secondMode(); + } else { + System.out.println("Wrong mode"); + } + } + + private static void firstMode() { + System.out.println("Provide time in seconds:"); + try { + int seconds = scan.nextInt(); + if (seconds < 0) { + System.out.println("Only positive numbers is allow, enter valid value"); + firstMode(); + } else if (seconds >= 86400) { + System.out.println("Day is over, enter valid value"); + firstMode(); + } else { + getSeconds(seconds); + } + } catch (InputMismatchException e) { + System.out.println("Only numbers is allow."); + } + } + + private static void secondMode() { + System.out.println("Provide time in \"hh:mm:ss\" format: "); + try { + String nextLine = scan.next(); + String[] input = nextLine.split(":"); + int hours = Integer.parseInt(input[0]); + int minutes = Integer.parseInt(input[1]); + int seconds = Integer.parseInt(input[2]); + + validateMode2(hours, minutes, seconds, input.length); + + int globalseconds = seconds + minutes * 60 + hours * 3600; + + getSeconds(globalseconds); + + } catch (InputMismatchException e) { + System.out.println("You are input incorrect date, try again"); + secondMode(); + } catch (NumberFormatException e) { + System.out.println("Only numbers is allow, try again"); + secondMode(); + } catch (ArrayIndexOutOfBoundsException e) { + System.out.println("Incorrect input, try again"); + secondMode(); + } + } + + private static void validateMode2(int hours, int minutes, int seconds, int length) { + if (hours < 0 || hours >= 24) { + System.out.println("You are input incorrect hours field."); + System.exit(0); + } + if (minutes < 0 || minutes >= 60) { + System.out.println("You are input incorrect minutes field."); + System.exit(0); + } + if (seconds < 0 || seconds >= 60) { + System.out.println("You are input incorrect seconds field."); + System.exit(0); + } + if (length > 3) { + System.out.println("There is an extra field"); + System.exit(0); + } + } + + private static String pickColor(String color) { + String message = "The traffic light is"; + if (color.equals("green")) { + return message + ANSI_GREEN + " Green" + ANSI_RESET + " now"; + } else if (color.equals("yellow")) { + return message + ANSI_YELLOW + " Yellow" + ANSI_RESET + " now"; + } else + return message + ANSI_RED + " Red" + ANSI_RESET + " now"; + } +} \ No newline at end of file From e29f38b4312e63d3b9cdf17c7b0375c10200f47b Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Wed, 14 Jul 2021 20:59:04 +0300 Subject: [PATCH 26/69] Edit README.md --- README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 5d2c93f0..79843172 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,9 @@ ## *Prokofev Ilia* | Index | Solution | Short description -| --- | --- | --- | +| :---: | --- | --- | | HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_1) | The app that reads input arguments and prints them, until "error" argument | - +| | [Traffic Light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_2/traffic_light) | The app that reads console and calculate current traffic light's color | +| HW2 | [Pyramid Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_2/pyramid_printer) | The app that reads console and prints a pyramid based on this | +| | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_2/random_chars_table) | The app that reads console for length, width and strategy and prints table based on this| From 73b485ce6629abb19f1042727e6445814191c24a Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Wed, 14 Jul 2021 21:03:00 +0300 Subject: [PATCH 27/69] Delete unnecessary import --- .../java/homework_2/random_chars_table/RandomCharsTable.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java index 49fb1a0c..34720bde 100644 --- a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -1,6 +1,5 @@ package homework_2.random_chars_table; -import java.lang.reflect.Array; import java.util.InputMismatchException; import java.util.Random; import java.util.Scanner; From 0d89e98780903e1c1a1150557fdee1c8225e5f0a Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Fri, 16 Jul 2021 12:55:56 +0300 Subject: [PATCH 28/69] Change output for PyramidPrinter --- src/main/java/homework_2/pyramid_printer/PyramidPrinter.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java index 67aaab69..53236e3c 100644 --- a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -10,7 +10,7 @@ public static void main(String[] args) { for (int i = 1; i <= x; ++i) { for (int j = 1; j <= i; ++j) { - System.out.print(x); + System.out.print("x"); } System.out.println(); } From 7d43fbcba0fd1f95ae5ca035113bc9dadce52799 Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Sat, 17 Jul 2021 13:41:12 +0300 Subject: [PATCH 29/69] Change program exit style --- src/main/java/homework_2/traffic_light/TrafficLight.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/homework_2/traffic_light/TrafficLight.java b/src/main/java/homework_2/traffic_light/TrafficLight.java index f0132055..f8322ce1 100644 --- a/src/main/java/homework_2/traffic_light/TrafficLight.java +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -89,19 +89,19 @@ private static void secondMode() { private static void validateMode2(int hours, int minutes, int seconds, int length) { if (hours < 0 || hours >= 24) { System.out.println("You are input incorrect hours field."); - System.exit(0); + secondMode(); } if (minutes < 0 || minutes >= 60) { System.out.println("You are input incorrect minutes field."); - System.exit(0); + secondMode(); } if (seconds < 0 || seconds >= 60) { System.out.println("You are input incorrect seconds field."); - System.exit(0); + secondMode(); } if (length > 3) { System.out.println("There is an extra field"); - System.exit(0); + secondMode(); } } From 94cb687d6dd4b1e0872dc1320f4425c56c9e3498 Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Sun, 18 Jul 2021 14:19:25 +0300 Subject: [PATCH 30/69] Fix minor problems, close Scanner in RandomCharsTable.java, fix English spelling. --- .../random_chars_table/RandomCharsTable.java | 14 ++++++++++---- .../java/homework_2/traffic_light/ColorTable.java | 10 +++++----- .../homework_2/traffic_light/TrafficLight.java | 11 +++++------ 3 files changed, 20 insertions(+), 15 deletions(-) diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java index 34720bde..bcc07c72 100644 --- a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -5,16 +5,23 @@ import java.util.Scanner; public class RandomCharsTable { - public static Scanner scanner = new Scanner(System.in); + private static Scanner scanner = new Scanner(System.in); private static int length; private static int width; public static void main(String[] args) { System.out.println("Enter valid length, width and strategy in format \"length width strategy\" "); - printRandomCharsTable(); + try { + printRandomCharsTable(); + } catch (NegativeArraySizeException e) { + System.out.println("Array size cannot be negative, try again."); + System.out.println("Enter valid length, width and strategy in format \"length width strategy\" "); + printRandomCharsTable(); + } + scanner.close(); } - public static void printRandomCharsTable() { + public static void printRandomCharsTable() throws NegativeArraySizeException { try { length = scanner.nextInt(); width = scanner.nextInt(); @@ -33,7 +40,6 @@ public static void printRandomCharsTable() { checkStratAndExecute(strategy, table); } catch (InputMismatchException e) { System.out.println("You entered invalid value, try again."); - System.exit(0); } } diff --git a/src/main/java/homework_2/traffic_light/ColorTable.java b/src/main/java/homework_2/traffic_light/ColorTable.java index c7e09799..9973f1a7 100644 --- a/src/main/java/homework_2/traffic_light/ColorTable.java +++ b/src/main/java/homework_2/traffic_light/ColorTable.java @@ -1,8 +1,8 @@ package homework_2.traffic_light; -public class ColorTable { - public static final String ANSI_RESET = "\u001B[0m"; - public static final String ANSI_RED = "\u001B[31m"; - public static final String ANSI_GREEN = "\u001B[32m"; - public static final String ANSI_YELLOW = "\u001B[33m"; +class ColorTable { + protected static final String ANSI_RESET = "\u001B[0m"; + protected static final String ANSI_RED = "\u001B[31m"; + protected static final String ANSI_GREEN = "\u001B[32m"; + protected static final String ANSI_YELLOW = "\u001B[33m"; } diff --git a/src/main/java/homework_2/traffic_light/TrafficLight.java b/src/main/java/homework_2/traffic_light/TrafficLight.java index f8322ce1..30af82a2 100644 --- a/src/main/java/homework_2/traffic_light/TrafficLight.java +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -1,6 +1,5 @@ package homework_2.traffic_light; -import java.util.Arrays; import java.util.InputMismatchException; import java.util.Scanner; @@ -75,7 +74,7 @@ private static void secondMode() { getSeconds(globalseconds); } catch (InputMismatchException e) { - System.out.println("You are input incorrect date, try again"); + System.out.println("You entered an invalid date, try again"); secondMode(); } catch (NumberFormatException e) { System.out.println("Only numbers is allow, try again"); @@ -88,19 +87,19 @@ private static void secondMode() { private static void validateMode2(int hours, int minutes, int seconds, int length) { if (hours < 0 || hours >= 24) { - System.out.println("You are input incorrect hours field."); + System.out.println("You entered an invalid hours field."); secondMode(); } if (minutes < 0 || minutes >= 60) { - System.out.println("You are input incorrect minutes field."); + System.out.println("You entered an invalid minutes field."); secondMode(); } if (seconds < 0 || seconds >= 60) { - System.out.println("You are input incorrect seconds field."); + System.out.println("You entered an invalid seconds field."); secondMode(); } if (length > 3) { - System.out.println("There is an extra field"); + System.out.println("You entered an extra field."); secondMode(); } } From a2d4b50ae878f9fc18eabe483f39a2687e16d6e8 Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Wed, 21 Jul 2021 02:57:23 +0300 Subject: [PATCH 31/69] Changed the entry point to applications, major refactoring --- README.md | 2 + .../java/homework_2/pyramid_printer/Main.java | 15 +++++ .../pyramid_printer/PyramidPrinter.java | 43 ++++++++++--- .../homework_2/random_chars_table/Main.java | 7 +++ .../random_chars_table/RandomCharsTable.java | 63 +++++++++++-------- .../java/homework_2/traffic_light/Main.java | 18 ++++++ .../traffic_light/TrafficLight.java | 44 +++++-------- 7 files changed, 130 insertions(+), 62 deletions(-) create mode 100644 src/main/java/homework_2/pyramid_printer/Main.java create mode 100644 src/main/java/homework_2/random_chars_table/Main.java create mode 100644 src/main/java/homework_2/traffic_light/Main.java diff --git a/README.md b/README.md index 79843172..d300d0b9 100644 --- a/README.md +++ b/README.md @@ -9,3 +9,5 @@ | HW2 | [Pyramid Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_2/pyramid_printer) | The app that reads console and prints a pyramid based on this | | | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_2/random_chars_table) | The app that reads console for length, width and strategy and prints table based on this| + +[CodingBat link](https://codingbat.com/done?user=slowly@live.ru&tag=8165639202) diff --git a/src/main/java/homework_2/pyramid_printer/Main.java b/src/main/java/homework_2/pyramid_printer/Main.java new file mode 100644 index 00000000..cc160f7a --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/Main.java @@ -0,0 +1,15 @@ +package homework_2.pyramid_printer; + +public class Main { + public static void main(String[] args) { + if (args.length > 1) { + System.out.println("Only 1 parameter is allowed"); + } else if (args.length == 0) { + System.out.println("Mode: x Representation"); + PyramidPrinter.xRepresentation(); + } else if (args[0].equals("dRepresentation")) { + System.out.println("Mode: Digital Representation"); + PyramidPrinter.dRepresentation(); + } + } +} diff --git a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java index 53236e3c..cf5f8487 100644 --- a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -1,18 +1,47 @@ package homework_2.pyramid_printer; +import java.util.InputMismatchException; import java.util.Scanner; public class PyramidPrinter { - public static void main(String[] args) { - Scanner scanner = new Scanner(System.in); + static final String INPUT_MISMATCH = "Only 1 non-negative integer is allowed."; + + protected static void xRepresentation() { System.out.println("Enter a valid INT value for create a pyramid:"); - int x = scanner.nextInt(); + try (Scanner scanner = new Scanner(System.in)) { + int x = scanner.nextInt(); + if (x >= 0) { + for (int i = 1; i <= x; ++i) { + for (int j = 1; j <= i; ++j) { + System.out.print("x"); + } + System.out.println(); + } + } else { + System.out.println(INPUT_MISMATCH); + } + } catch (InputMismatchException e) { + System.out.println(INPUT_MISMATCH); + } + } - for (int i = 1; i <= x; ++i) { - for (int j = 1; j <= i; ++j) { - System.out.print("x"); + protected static void dRepresentation() { + System.out.println("Enter a valid INT value for create a pyramid:"); + try (Scanner scanner = new Scanner(System.in)) { + int x = scanner.nextInt(); + if (x >= 0) { + for (int i = 1; i <= x; ++i) { + for (int j = 1; j <= i; ++j) { + System.out.print(x); + } + System.out.println(); + } + } else { + System.out.println(INPUT_MISMATCH); } - System.out.println(); + } catch (InputMismatchException e) { + System.out.println(INPUT_MISMATCH); } } } + diff --git a/src/main/java/homework_2/random_chars_table/Main.java b/src/main/java/homework_2/random_chars_table/Main.java new file mode 100644 index 00000000..a341a9fa --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/Main.java @@ -0,0 +1,7 @@ +package homework_2.random_chars_table; + +public class Main { + public static void main(String[] args) { + RandomCharsTable.greeting(); + } +} diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java index bcc07c72..cc1dd06c 100644 --- a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -5,46 +5,57 @@ import java.util.Scanner; public class RandomCharsTable { - private static Scanner scanner = new Scanner(System.in); private static int length; private static int width; - public static void main(String[] args) { - System.out.println("Enter valid length, width and strategy in format \"length width strategy\" "); - try { - printRandomCharsTable(); - } catch (NegativeArraySizeException e) { - System.out.println("Array size cannot be negative, try again."); - System.out.println("Enter valid length, width and strategy in format \"length width strategy\" "); - printRandomCharsTable(); - } - scanner.close(); + protected static void greeting() { + System.out.println("Enter valid table length, width and strategy(even or odd) in format \"length width strategy\" "); + getParameters(); } - public static void printRandomCharsTable() throws NegativeArraySizeException { - try { + private static void getParameters() { + try (Scanner scanner = new Scanner(System.in)) { length = scanner.nextInt(); width = scanner.nextInt(); String strategy = scanner.next(); + checkLengthAndWidth(length, width); + checkStrategyValid(strategy); char[][] table = new char[length][width]; + fillAndPrintTable(strategy, table); + } catch (NegativeArraySizeException e) { + System.out.println("Array size cannot be negative."); + } catch (InputMismatchException e) { + System.out.println("Input parameters must be in the format [positive integer(>0)] [positive integer(>0)] [even|odd]"); + } + } + + private static void checkLengthAndWidth(int length, int width) { + if (length == 0 || width == 0){ + throw new InputMismatchException(); + } + } - Random random = new Random(); + private static void fillAndPrintTable(String strategy, char[][] table) { + Random random = new Random(); - for (int i = 0; i < length; i++) { - for (int j = 0; j < width; j++) { - table[i][j] = (char) (random.nextInt((90 - 65) + 1) + 65); - System.out.print("|" + table[i][j] + "|"); - } - System.out.println(); + for (int i = 0; i < length; i++) { + for (int j = 0; j < width; j++) { + table[i][j] = (char) (random.nextInt((90 - 65) + 1) + 65); + System.out.print("|" + table[i][j] + "|"); } - checkStratAndExecute(strategy, table); - } catch (InputMismatchException e) { - System.out.println("You entered invalid value, try again."); + System.out.println(); + } + checkStratAndExecute(strategy, table); + } + + private static void checkStrategyValid(String strategy) { + if (!strategy.equals("even") && !strategy.equals("odd")) { + throw new InputMismatchException(); } } - private static void checkStratAndExecute(String strat, char[][] table) { - if (strat.equals("even")) { + private static void checkStratAndExecute(String strategy, char[][] table) { + if (strategy.equals("even")) { System.out.print("Even letters - "); for (int i = 0; i < length; i++) { for (int j = 0; j < width; j++) { @@ -53,7 +64,7 @@ private static void checkStratAndExecute(String strat, char[][] table) { } } } - } else if (strat.equals("odd")) { + } else if (strategy.equals("odd")) { System.out.print("Odd letters - "); for (int i = 0; i < length; i++) { for (int j = 0; j < width; j++) { diff --git a/src/main/java/homework_2/traffic_light/Main.java b/src/main/java/homework_2/traffic_light/Main.java new file mode 100644 index 00000000..0fb1ff93 --- /dev/null +++ b/src/main/java/homework_2/traffic_light/Main.java @@ -0,0 +1,18 @@ +package homework_2.traffic_light; + +public class Main { + public static void main(String[] args) { + if (args.length > 1){ + System.out.println("Only 1 parameter is allowed"); + } + else if (args.length == 0){ + TrafficLight.greeting(); + } + else if (args[0].equals("1")){ + TrafficLight.firstMode(); + } + else if (args[0].equals("2")){ + TrafficLight.secondMode(); + } + } +} diff --git a/src/main/java/homework_2/traffic_light/TrafficLight.java b/src/main/java/homework_2/traffic_light/TrafficLight.java index 30af82a2..dc552af8 100644 --- a/src/main/java/homework_2/traffic_light/TrafficLight.java +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -6,17 +6,15 @@ import static homework_2.traffic_light.ColorTable.*; public class TrafficLight { - private static Scanner scan = new Scanner(System.in); - public static void main(String[] args) { + public static void greeting() { System.out.println("Pick mode: 1 - provide seconds, 2 - provide time in format \"hh:mm:ss\": "); - try { + try (Scanner scan = new Scanner(System.in)) { int mode = scan.nextInt(); selectMode(mode); } catch (InputMismatchException e) { System.out.println("Only 1 or 2 allow"); } - scan.close(); } private static void getSeconds(int seconds) { @@ -36,20 +34,18 @@ private static void selectMode(int mode) { } else if (mode == 2) { secondMode(); } else { - System.out.println("Wrong mode"); + System.out.println("You entered wrong mode number."); } } - private static void firstMode() { + protected static void firstMode() { System.out.println("Provide time in seconds:"); - try { + try (Scanner scan = new Scanner(System.in)) { int seconds = scan.nextInt(); if (seconds < 0) { - System.out.println("Only positive numbers is allow, enter valid value"); - firstMode(); + System.out.println("Only non-negative numbers is allow."); } else if (seconds >= 86400) { - System.out.println("Day is over, enter valid value"); - firstMode(); + System.out.println("Day is over."); } else { getSeconds(seconds); } @@ -58,50 +54,40 @@ private static void firstMode() { } } - private static void secondMode() { + protected static void secondMode() { System.out.println("Provide time in \"hh:mm:ss\" format: "); - try { + try (Scanner scan = new Scanner(System.in)) { String nextLine = scan.next(); String[] input = nextLine.split(":"); int hours = Integer.parseInt(input[0]); int minutes = Integer.parseInt(input[1]); int seconds = Integer.parseInt(input[2]); - - validateMode2(hours, minutes, seconds, input.length); - + validateSecondMode(hours, minutes, seconds, input.length); int globalseconds = seconds + minutes * 60 + hours * 3600; - getSeconds(globalseconds); - } catch (InputMismatchException e) { - System.out.println("You entered an invalid date, try again"); - secondMode(); + System.out.println("You entered an invalid date."); } catch (NumberFormatException e) { - System.out.println("Only numbers is allow, try again"); - secondMode(); + System.out.println("Only numbers is allow."); } catch (ArrayIndexOutOfBoundsException e) { - System.out.println("Incorrect input, try again"); - secondMode(); + System.out.println("Incorrect input."); } } - private static void validateMode2(int hours, int minutes, int seconds, int length) { + private static void validateSecondMode(int hours, int minutes, int seconds, int length) { if (hours < 0 || hours >= 24) { System.out.println("You entered an invalid hours field."); - secondMode(); } if (minutes < 0 || minutes >= 60) { System.out.println("You entered an invalid minutes field."); - secondMode(); } if (seconds < 0 || seconds >= 60) { System.out.println("You entered an invalid seconds field."); - secondMode(); } if (length > 3) { System.out.println("You entered an extra field."); - secondMode(); } + throw new InputMismatchException(); } private static String pickColor(String color) { From a6ebdae706def68a9a356e150bf4bb0b869b1617 Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Thu, 22 Jul 2021 22:55:50 +0300 Subject: [PATCH 32/69] Global refactoring: --Extract frequently used methods and constants into separate modules --Create tests for PyramidPrinter and RandomCharsTable --Major and minor bug fixes --- .../java/homework_2/pyramid_printer/Main.java | 6 +- .../pyramid_printer/PyramidPrinter.java | 47 -------- .../pyramid_printer/PyramidPrinterD.java | 27 +++++ .../pyramid_printer/PyramidPrinterX.java | 30 ++++++ .../homework_2/pyramid_printer/Utils.java | 6 ++ .../homework_2/random_chars_table/Main.java | 2 +- .../random_chars_table/RandomCharsTable.java | 2 +- .../traffic_light/ColorSelector.java | 18 ++++ .../homework_2/traffic_light/ColorTable.java | 8 -- .../java/homework_2/traffic_light/Main.java | 17 ++- .../traffic_light/TrafficLight.java | 102 ------------------ .../traffic_light/TrafficLightDateTime.java | 55 ++++++++++ .../traffic_light/TrafficLightSeconds.java | 56 ++++++++++ .../pyramid_printer/PyramidPrinterDTest.java | 61 +++++++++++ .../pyramid_printer/PyramidPrinterXTest.java | 62 +++++++++++ .../RandomCharsTableTest.java | 43 ++++++++ .../TrafficLightDateTimeTest.java | 9 ++ .../TrafficLightSecondsTest.java | 9 ++ 18 files changed, 386 insertions(+), 174 deletions(-) delete mode 100644 src/main/java/homework_2/pyramid_printer/PyramidPrinter.java create mode 100644 src/main/java/homework_2/pyramid_printer/PyramidPrinterD.java create mode 100644 src/main/java/homework_2/pyramid_printer/PyramidPrinterX.java create mode 100644 src/main/java/homework_2/pyramid_printer/Utils.java create mode 100644 src/main/java/homework_2/traffic_light/ColorSelector.java delete mode 100644 src/main/java/homework_2/traffic_light/ColorTable.java delete mode 100644 src/main/java/homework_2/traffic_light/TrafficLight.java create mode 100644 src/main/java/homework_2/traffic_light/TrafficLightDateTime.java create mode 100644 src/main/java/homework_2/traffic_light/TrafficLightSeconds.java create mode 100644 src/test/java/homework_2/pyramid_printer/PyramidPrinterDTest.java create mode 100644 src/test/java/homework_2/pyramid_printer/PyramidPrinterXTest.java create mode 100644 src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java create mode 100644 src/test/java/homework_2/traffic_light/TrafficLightDateTimeTest.java create mode 100644 src/test/java/homework_2/traffic_light/TrafficLightSecondsTest.java diff --git a/src/main/java/homework_2/pyramid_printer/Main.java b/src/main/java/homework_2/pyramid_printer/Main.java index cc160f7a..38d68310 100644 --- a/src/main/java/homework_2/pyramid_printer/Main.java +++ b/src/main/java/homework_2/pyramid_printer/Main.java @@ -5,11 +5,9 @@ public static void main(String[] args) { if (args.length > 1) { System.out.println("Only 1 parameter is allowed"); } else if (args.length == 0) { - System.out.println("Mode: x Representation"); - PyramidPrinter.xRepresentation(); + PyramidPrinterX.run(); } else if (args[0].equals("dRepresentation")) { - System.out.println("Mode: Digital Representation"); - PyramidPrinter.dRepresentation(); + PyramidPrinterD.run(); } } } diff --git a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java deleted file mode 100644 index cf5f8487..00000000 --- a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java +++ /dev/null @@ -1,47 +0,0 @@ -package homework_2.pyramid_printer; - -import java.util.InputMismatchException; -import java.util.Scanner; - -public class PyramidPrinter { - static final String INPUT_MISMATCH = "Only 1 non-negative integer is allowed."; - - protected static void xRepresentation() { - System.out.println("Enter a valid INT value for create a pyramid:"); - try (Scanner scanner = new Scanner(System.in)) { - int x = scanner.nextInt(); - if (x >= 0) { - for (int i = 1; i <= x; ++i) { - for (int j = 1; j <= i; ++j) { - System.out.print("x"); - } - System.out.println(); - } - } else { - System.out.println(INPUT_MISMATCH); - } - } catch (InputMismatchException e) { - System.out.println(INPUT_MISMATCH); - } - } - - protected static void dRepresentation() { - System.out.println("Enter a valid INT value for create a pyramid:"); - try (Scanner scanner = new Scanner(System.in)) { - int x = scanner.nextInt(); - if (x >= 0) { - for (int i = 1; i <= x; ++i) { - for (int j = 1; j <= i; ++j) { - System.out.print(x); - } - System.out.println(); - } - } else { - System.out.println(INPUT_MISMATCH); - } - } catch (InputMismatchException e) { - System.out.println(INPUT_MISMATCH); - } - } -} - diff --git a/src/main/java/homework_2/pyramid_printer/PyramidPrinterD.java b/src/main/java/homework_2/pyramid_printer/PyramidPrinterD.java new file mode 100644 index 00000000..fb4ae69b --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinterD.java @@ -0,0 +1,27 @@ +package homework_2.pyramid_printer; + +import java.util.InputMismatchException; +import java.util.Scanner; + +import static homework_2.pyramid_printer.Utils.*; + +public class PyramidPrinterD { + protected static void run() { + System.out.println(INPUT); + try (Scanner scanner = new Scanner(System.in)) { + int x = scanner.nextInt(); + if (x >= 0) { + for (int i = 1; i <= x; ++i) { + for (int j = 1; j <= i; ++j) { + System.out.print(x); + } + System.out.println(); + } + } else { + System.out.println(INPUT_MISMATCH); + } + } catch (InputMismatchException e) { + System.out.println(INPUT_MISMATCH); + } + } +} diff --git a/src/main/java/homework_2/pyramid_printer/PyramidPrinterX.java b/src/main/java/homework_2/pyramid_printer/PyramidPrinterX.java new file mode 100644 index 00000000..dce55603 --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinterX.java @@ -0,0 +1,30 @@ +package homework_2.pyramid_printer; + +import java.util.InputMismatchException; +import java.util.Scanner; + +import static homework_2.pyramid_printer.Utils.*; + +public class PyramidPrinterX { + protected static void run() { + System.out.println(INPUT); + try (Scanner scanner = new Scanner(System.in)) { + int x = scanner.nextInt(); + if (x >= 0) { + for (int i = 1; i <= x; ++i) { + for (int j = 1; j <= i; ++j) { + System.out.print("x"); + } + System.out.println(); + } + } else { + System.out.println(INPUT_MISMATCH); + } + } catch (InputMismatchException e) { + System.out.println(INPUT_MISMATCH); + } + } + + +} + diff --git a/src/main/java/homework_2/pyramid_printer/Utils.java b/src/main/java/homework_2/pyramid_printer/Utils.java new file mode 100644 index 00000000..480f83d6 --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/Utils.java @@ -0,0 +1,6 @@ +package homework_2.pyramid_printer; + +class Utils { + static final String INPUT_MISMATCH = "Only 1 non-negative integer is allowed."; + static final String INPUT = "Enter a valid INT value for create a pyramid:"; +} diff --git a/src/main/java/homework_2/random_chars_table/Main.java b/src/main/java/homework_2/random_chars_table/Main.java index a341a9fa..2eb9b88f 100644 --- a/src/main/java/homework_2/random_chars_table/Main.java +++ b/src/main/java/homework_2/random_chars_table/Main.java @@ -2,6 +2,6 @@ public class Main { public static void main(String[] args) { - RandomCharsTable.greeting(); + RandomCharsTable.run(); } } diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java index cc1dd06c..6bc21a93 100644 --- a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -8,7 +8,7 @@ public class RandomCharsTable { private static int length; private static int width; - protected static void greeting() { + protected static void run() { System.out.println("Enter valid table length, width and strategy(even or odd) in format \"length width strategy\" "); getParameters(); } diff --git a/src/main/java/homework_2/traffic_light/ColorSelector.java b/src/main/java/homework_2/traffic_light/ColorSelector.java new file mode 100644 index 00000000..5664723d --- /dev/null +++ b/src/main/java/homework_2/traffic_light/ColorSelector.java @@ -0,0 +1,18 @@ +package homework_2.traffic_light; + +class ColorSelector { + protected static final String ANSI_RESET = "\u001B[0m"; + protected static final String ANSI_RED = "\u001B[31m"; + protected static final String ANSI_GREEN = "\u001B[32m"; + protected static final String ANSI_YELLOW = "\u001B[33m"; + protected static final String MESSAGE = "The traffic light is"; + + protected static String pickColor(String color) { + if (color.equals("green")) { + return MESSAGE + ANSI_GREEN + " Green" + ANSI_RESET + " now"; + } else if (color.equals("yellow")) { + return MESSAGE + ANSI_YELLOW + " Yellow" + ANSI_RESET + " now"; + } else + return MESSAGE + ANSI_RED + " Red" + ANSI_RESET + " now"; + } +} diff --git a/src/main/java/homework_2/traffic_light/ColorTable.java b/src/main/java/homework_2/traffic_light/ColorTable.java deleted file mode 100644 index 9973f1a7..00000000 --- a/src/main/java/homework_2/traffic_light/ColorTable.java +++ /dev/null @@ -1,8 +0,0 @@ -package homework_2.traffic_light; - -class ColorTable { - protected static final String ANSI_RESET = "\u001B[0m"; - protected static final String ANSI_RED = "\u001B[31m"; - protected static final String ANSI_GREEN = "\u001B[32m"; - protected static final String ANSI_YELLOW = "\u001B[33m"; -} diff --git a/src/main/java/homework_2/traffic_light/Main.java b/src/main/java/homework_2/traffic_light/Main.java index 0fb1ff93..f694b631 100644 --- a/src/main/java/homework_2/traffic_light/Main.java +++ b/src/main/java/homework_2/traffic_light/Main.java @@ -2,17 +2,12 @@ public class Main { public static void main(String[] args) { - if (args.length > 1){ + if (args.length > 1) { System.out.println("Only 1 parameter is allowed"); - } - else if (args.length == 0){ - TrafficLight.greeting(); - } - else if (args[0].equals("1")){ - TrafficLight.firstMode(); - } - else if (args[0].equals("2")){ - TrafficLight.secondMode(); + } else if (args.length == 0) { + TrafficLightSeconds.seconds(); + } else if (args[0].equals("LocalDateTime")) { + TrafficLightDateTime.dateTime(); } } -} +} \ No newline at end of file diff --git a/src/main/java/homework_2/traffic_light/TrafficLight.java b/src/main/java/homework_2/traffic_light/TrafficLight.java deleted file mode 100644 index dc552af8..00000000 --- a/src/main/java/homework_2/traffic_light/TrafficLight.java +++ /dev/null @@ -1,102 +0,0 @@ -package homework_2.traffic_light; - -import java.util.InputMismatchException; -import java.util.Scanner; - -import static homework_2.traffic_light.ColorTable.*; - -public class TrafficLight { - - public static void greeting() { - System.out.println("Pick mode: 1 - provide seconds, 2 - provide time in format \"hh:mm:ss\": "); - try (Scanner scan = new Scanner(System.in)) { - int mode = scan.nextInt(); - selectMode(mode); - } catch (InputMismatchException e) { - System.out.println("Only 1 or 2 allow"); - } - } - - private static void getSeconds(int seconds) { - int sec = seconds % 60; - if (sec >= 0 && sec < 35) { - System.out.println(pickColor("green")); - } else if ((sec >= 35 && sec < 40) || sec >= 55) { - System.out.println(pickColor("yellow")); - } else { - System.out.println(pickColor("red")); - } - } - - private static void selectMode(int mode) { - if (mode == 1) { - firstMode(); - } else if (mode == 2) { - secondMode(); - } else { - System.out.println("You entered wrong mode number."); - } - } - - protected static void firstMode() { - System.out.println("Provide time in seconds:"); - try (Scanner scan = new Scanner(System.in)) { - int seconds = scan.nextInt(); - if (seconds < 0) { - System.out.println("Only non-negative numbers is allow."); - } else if (seconds >= 86400) { - System.out.println("Day is over."); - } else { - getSeconds(seconds); - } - } catch (InputMismatchException e) { - System.out.println("Only numbers is allow."); - } - } - - protected static void secondMode() { - System.out.println("Provide time in \"hh:mm:ss\" format: "); - try (Scanner scan = new Scanner(System.in)) { - String nextLine = scan.next(); - String[] input = nextLine.split(":"); - int hours = Integer.parseInt(input[0]); - int minutes = Integer.parseInt(input[1]); - int seconds = Integer.parseInt(input[2]); - validateSecondMode(hours, minutes, seconds, input.length); - int globalseconds = seconds + minutes * 60 + hours * 3600; - getSeconds(globalseconds); - } catch (InputMismatchException e) { - System.out.println("You entered an invalid date."); - } catch (NumberFormatException e) { - System.out.println("Only numbers is allow."); - } catch (ArrayIndexOutOfBoundsException e) { - System.out.println("Incorrect input."); - } - } - - private static void validateSecondMode(int hours, int minutes, int seconds, int length) { - if (hours < 0 || hours >= 24) { - System.out.println("You entered an invalid hours field."); - } - if (minutes < 0 || minutes >= 60) { - System.out.println("You entered an invalid minutes field."); - } - if (seconds < 0 || seconds >= 60) { - System.out.println("You entered an invalid seconds field."); - } - if (length > 3) { - System.out.println("You entered an extra field."); - } - throw new InputMismatchException(); - } - - private static String pickColor(String color) { - String message = "The traffic light is"; - if (color.equals("green")) { - return message + ANSI_GREEN + " Green" + ANSI_RESET + " now"; - } else if (color.equals("yellow")) { - return message + ANSI_YELLOW + " Yellow" + ANSI_RESET + " now"; - } else - return message + ANSI_RED + " Red" + ANSI_RESET + " now"; - } -} \ No newline at end of file diff --git a/src/main/java/homework_2/traffic_light/TrafficLightDateTime.java b/src/main/java/homework_2/traffic_light/TrafficLightDateTime.java new file mode 100644 index 00000000..100fa11d --- /dev/null +++ b/src/main/java/homework_2/traffic_light/TrafficLightDateTime.java @@ -0,0 +1,55 @@ +package homework_2.traffic_light; + +import java.util.InputMismatchException; +import java.util.Scanner; + +import static homework_2.traffic_light.ColorSelector.*; + + +public class TrafficLightDateTime { + protected static void dateTime() { + System.out.println("Provide time in \"hh:mm:ss\" format: "); + try (Scanner scan = new Scanner(System.in)) { + String nextLine = scan.next(); + String[] input = nextLine.split(":"); + int hours = Integer.parseInt(input[0]); + int minutes = Integer.parseInt(input[1]); + int seconds = Integer.parseInt(input[2]); + validateSecondMode(hours, minutes, seconds, input.length); + int globalseconds = seconds + minutes * 60 + hours * 3600; + getSeconds(globalseconds); + } catch (InputMismatchException e) { + System.out.println("You entered an invalid date."); + } catch (NumberFormatException e) { + System.out.println("Only numbers is allow."); + } catch (ArrayIndexOutOfBoundsException e) { + System.out.println("Incorrect input."); + } + } + + private static void validateSecondMode(int hours, int minutes, int seconds, int length) { + if ((hours < 0 || hours >= 24)) { + throw new InputMismatchException(); + } + if (minutes < 0 || minutes >= 60) { + throw new InputMismatchException(); + } + if (seconds < 0 || seconds >= 60) { + throw new InputMismatchException(); + } + if (length > 3) { + throw new InputMismatchException(); + } + } + + private static void getSeconds(int seconds) { + int sec = seconds % 60; + if (sec >= 0 && sec < 35) { + System.out.println(pickColor("green")); + } else if ((sec >= 35 && sec < 40) || sec >= 55) { + System.out.println(pickColor("yellow")); + } else { + System.out.println(pickColor("red")); + } + } +} \ No newline at end of file diff --git a/src/main/java/homework_2/traffic_light/TrafficLightSeconds.java b/src/main/java/homework_2/traffic_light/TrafficLightSeconds.java new file mode 100644 index 00000000..7e71cbbb --- /dev/null +++ b/src/main/java/homework_2/traffic_light/TrafficLightSeconds.java @@ -0,0 +1,56 @@ +package homework_2.traffic_light; + +import java.util.InputMismatchException; +import java.util.Scanner; + +import static homework_2.traffic_light.ColorSelector.*; + +class TrafficLightSeconds { + protected static void seconds() { + System.out.println("Provide time in seconds:"); + try (Scanner scan = new Scanner(System.in)) { + int seconds = scan.nextInt(); + if (seconds < 0) { + System.out.println("Only non-negative numbers is allow."); + } else if (seconds >= 86400) { + System.out.println("Day is over."); + } else { + getSeconds(seconds); + } + } catch (InputMismatchException e) { + System.out.println("Only numbers is allow."); + } + } + + private static void getSeconds(int seconds) { + int sec = seconds % 60; + if (sec >= 0 && sec < 35) { + System.out.println(pickColor("green")); + } else if ((sec >= 35 && sec < 40) || sec >= 55) { + System.out.println(pickColor("yellow")); + } else { + System.out.println(pickColor("red")); + } + } +} + +// private static void selectMode(int mode) { +// if (mode == 1) { +// firstMode(); +// } else if (mode == 2) { +// secondMode(); +// } else { +// System.out.println("You entered wrong mode number."); +// } +// } + + +// public static void greeting() { +// System.out.println("Pick mode: 1 - provide seconds, 2 - provide time in format \"hh:mm:ss\": "); +// try (Scanner scan = new Scanner(System.in)) { +// int mode = scan.nextInt(); +// selectMode(mode); +// } catch (InputMismatchException e) { +// System.out.println("Only 1 or 2 allow"); +// } +// } \ No newline at end of file diff --git a/src/test/java/homework_2/pyramid_printer/PyramidPrinterDTest.java b/src/test/java/homework_2/pyramid_printer/PyramidPrinterDTest.java new file mode 100644 index 00000000..1a0d0e6f --- /dev/null +++ b/src/test/java/homework_2/pyramid_printer/PyramidPrinterDTest.java @@ -0,0 +1,61 @@ +package homework_2.pyramid_printer; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class PyramidPrinterDTest extends UnitBase { + private void run() { + new PyramidPrinterD().run(); + removeFromOutput("Enter a valid INT value for create a pyramid:"); + printOut(); + } + + @Test + void runWithOneArgument() { + setInput("1"); + + run(); + + assertEquals("1", getOutput()); + } + + @Test + void runWithThreeArguments() { + setInput("3"); + + run(); + + assertEquals("3", getOutputLines()[0]); + assertEquals("33", getOutputLines()[1]); + assertEquals("333", getOutputLines()[2]); + } + + @Test + void runWithZeroArguments() { + setInput("0"); + + run(); + + assertEquals("",getOutput()); + } + + @Test + void runWithNegativeArgument() { + setInput("-5"); + + run(); + + assertEquals("Only 1 non-negative integer is allowed.",getOutput()); + } + + @Test + void runWithNotNumberArgument() { + setInput("asd"); + + run(); + + assertEquals("Only 1 non-negative integer is allowed.",getOutput()); + } +} \ No newline at end of file diff --git a/src/test/java/homework_2/pyramid_printer/PyramidPrinterXTest.java b/src/test/java/homework_2/pyramid_printer/PyramidPrinterXTest.java new file mode 100644 index 00000000..2e88e490 --- /dev/null +++ b/src/test/java/homework_2/pyramid_printer/PyramidPrinterXTest.java @@ -0,0 +1,62 @@ +package homework_2.pyramid_printer; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class PyramidPrinterXTest extends UnitBase { + + private void run() { + new PyramidPrinterX().run(); + removeFromOutput("Enter a valid INT value for create a pyramid:"); + printOut(); + } + + @Test + void runWithOneArgument() { + setInput("1"); + + run(); + + assertEquals("x", getOutput()); + } + + @Test + void runWithThreeArguments() { + setInput("3"); + + run(); + + assertEquals("x", getOutputLines()[0]); + assertEquals("xx", getOutputLines()[1]); + assertEquals("xxx", getOutputLines()[2]); + } + + @Test + void runWithZeroArguments() { + setInput("0"); + + run(); + + assertEquals("",getOutput()); + } + + @Test + void runWithNegativeArgument() { + setInput("-5"); + + run(); + + assertEquals("Only 1 non-negative integer is allowed.",getOutput()); + } + + @Test + void runWithNotNumberArgument() { + setInput("asd"); + + run(); + + assertEquals("Only 1 non-negative integer is allowed.",getOutput()); + } +} \ No newline at end of file diff --git a/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java b/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java new file mode 100644 index 00000000..3e7c7514 --- /dev/null +++ b/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java @@ -0,0 +1,43 @@ +package homework_2.random_chars_table; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class RandomCharsTableTest extends UnitBase { + + private void run() { + new RandomCharsTable().run(); + removeFromOutput("Enter valid table length, width and strategy(even or odd) in format \"length width strategy\""); + printOut(); + } + + @Test + void runWithNegativeArgument() { + setInput("-1 5 even"); + + run(); + + assertEquals("Array size cannot be negative.", getOutput()); + } + + @Test + void runWithMismatchArguments() { + setInput("error 5 even"); + + run(); + + assertEquals("Input parameters must be in the format [positive integer(>0)] [positive integer(>0)] [even|odd]", getOutput()); + } + + @Test + void runWithMismatchStrategy() { + setInput("4 5 error"); + + run(); + + assertEquals("Input parameters must be in the format [positive integer(>0)] [positive integer(>0)] [even|odd]", getOutput()); + } + +} \ No newline at end of file diff --git a/src/test/java/homework_2/traffic_light/TrafficLightDateTimeTest.java b/src/test/java/homework_2/traffic_light/TrafficLightDateTimeTest.java new file mode 100644 index 00000000..9ab91e74 --- /dev/null +++ b/src/test/java/homework_2/traffic_light/TrafficLightDateTimeTest.java @@ -0,0 +1,9 @@ +package homework_2.traffic_light; + +import base.UnitBase; + +import static org.junit.jupiter.api.Assertions.*; + +class TrafficLightDateTimeTest extends UnitBase { + +} \ No newline at end of file diff --git a/src/test/java/homework_2/traffic_light/TrafficLightSecondsTest.java b/src/test/java/homework_2/traffic_light/TrafficLightSecondsTest.java new file mode 100644 index 00000000..19b4dd81 --- /dev/null +++ b/src/test/java/homework_2/traffic_light/TrafficLightSecondsTest.java @@ -0,0 +1,9 @@ +package homework_2.traffic_light; + +import base.UnitBase; + +import static org.junit.jupiter.api.Assertions.*; + +class TrafficLightSecondsTest extends UnitBase { + +} \ No newline at end of file From cc1ee4ae4e754da1764cbbf961c2d99f6023bb6b Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Sat, 24 Jul 2021 00:33:27 +0300 Subject: [PATCH 33/69] Complete all tests for homework, create Immutable Class, minor improvements and bug fixes. --- build.gradle | 6 ++ src/main/java/homework_1/CharCount.java | 2 +- src/main/java/homework_1/Main.java | 7 ++ .../random_chars_table/RandomCharsTable.java | 2 + src/main/java/homework_3/ImmutableClass.java | 62 +++++++++++++ .../homework_1/char_count/CharCountTest.java | 46 ++++++++++ .../TrafficLightDateTimeTest.java | 90 +++++++++++++++++++ .../TrafficLightSecondsTest.java | 52 +++++++++++ 8 files changed, 266 insertions(+), 1 deletion(-) create mode 100644 src/main/java/homework_1/Main.java create mode 100644 src/main/java/homework_3/ImmutableClass.java create mode 100644 src/test/java/homework_1/char_count/CharCountTest.java diff --git a/build.gradle b/build.gradle index b91dc843..67b7f675 100644 --- a/build.gradle +++ b/build.gradle @@ -12,6 +12,12 @@ repositories { dependencies { testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0' testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0' + + compileOnly 'org.projectlombok:lombok:1.18.20' + annotationProcessor 'org.projectlombok:lombok:1.18.20' + + testCompileOnly 'org.projectlombok:lombok:1.18.20' + testAnnotationProcessor 'org.projectlombok:lombok:1.18.20' } test { diff --git a/src/main/java/homework_1/CharCount.java b/src/main/java/homework_1/CharCount.java index a930c463..b0aa7eb7 100644 --- a/src/main/java/homework_1/CharCount.java +++ b/src/main/java/homework_1/CharCount.java @@ -4,7 +4,7 @@ public class CharCount { public static final String ANSI_RED = "\u001B[31m"; public static final String ANSI_RESET = "\u001B[0m"; - public static void main(String[] args) { + public static void run(String[] args) { for (String arg : args) { if (arg.equals("error")) { System.out.println(ANSI_RED + "Alarm!" + ANSI_RESET); diff --git a/src/main/java/homework_1/Main.java b/src/main/java/homework_1/Main.java new file mode 100644 index 00000000..3c466a0c --- /dev/null +++ b/src/main/java/homework_1/Main.java @@ -0,0 +1,7 @@ +package homework_1; + +public class Main { + public static void main(String[] args) { + CharCount.run(args); + } +} diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java index 6bc21a93..a69bb3e7 100644 --- a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -1,5 +1,7 @@ package homework_2.random_chars_table; +import lombok.Data; + import java.util.InputMismatchException; import java.util.Random; import java.util.Scanner; diff --git a/src/main/java/homework_3/ImmutableClass.java b/src/main/java/homework_3/ImmutableClass.java new file mode 100644 index 00000000..692107bc --- /dev/null +++ b/src/main/java/homework_3/ImmutableClass.java @@ -0,0 +1,62 @@ +package homework_3; +/* + Rules for Creating an Immutable Class in Java +1. The class must be declared as final (So that child classes can’t be created). +2. Don't provide "setter" methods — methods that modify fields or objects referred to by fields. +3. Make all fields final and private. +4. Don't allow subclasses to override methods. The simplest way to do this is to declare the class as final. +5. If the instance fields include references to mutable objects, don't allow those objects to be changed: + * Don't provide methods that modify the mutable objects. + * Don't share references to the mutable objects. Never store references to external, mutable objects passed to the constructor, + !if necessary, create copies, and store references to the copies. + !Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods. +6. A parameterized constructor should initialize all the fields performing a deep copy (So that data members can’t be modified with object reference). + */ + +public final class ImmutableClass { + private final int integer; + private final String string; + private final Integer integer1; + + public ImmutableClass(int integer, String string, Integer integer1) { + this.integer = integer; + this.string = string; + this.integer1 = new Integer(integer1); + } + + public ImmutableClass(int integer, String string) { + this.integer = integer; + this.string = string; + this.integer1 = new Integer(null); + } + + public ImmutableClass(int integer) { + this.integer = integer; + this.string = ""; + this.integer1 = new Integer(null); + } + + public ImmutableClass() { + this.integer = 6; + this.string = "field"; + this.integer1 = new Integer(5); + } + + + public int getInteger() { + return integer; + } + + public String getString() { + return string; + } + + public Integer getInteger1() { + return integer1; + } + + public ImmutableClass returnModifyObject() { + ImmutableClass immutableClass = new ImmutableClass(6, "field", 5); + return immutableClass; + } +} diff --git a/src/test/java/homework_1/char_count/CharCountTest.java b/src/test/java/homework_1/char_count/CharCountTest.java new file mode 100644 index 00000000..18f287a4 --- /dev/null +++ b/src/test/java/homework_1/char_count/CharCountTest.java @@ -0,0 +1,46 @@ +package homework_1.char_count; + +import base.UnitBase; +import homework_1.CharCount; +import homework_1.Main; +import homework_2.pyramid_printer.PyramidPrinterX; +import org.junit.jupiter.api.Test; + +import static homework_1.CharCount.ANSI_RED; +import static homework_1.CharCount.ANSI_RESET; +import static org.junit.jupiter.api.Assertions.*; + +class CharCountTest extends UnitBase { + @Test + void runWithError() { + String[] args = {"some", "new", "word", "and", "error"}; + Main.main(args); + printOut(); + assertEquals("some: 4 letters", getOutputLines()[0]); + assertEquals("new: 3 letters", getOutputLines()[1]); + assertEquals("word: 4 letters", getOutputLines()[2]); + assertEquals("and: 3 letters", getOutputLines()[3]); + assertEquals(ANSI_RED + "Alarm!" + ANSI_RESET, getOutputLines()[4]); + } + + @Test + void runWithoutError() { + String[] args = {"some", "new", "word", "and", "no error"}; + Main.main(args); + printOut(); + assertEquals("some: 4 letters", getOutputLines()[0]); + assertEquals("new: 3 letters", getOutputLines()[1]); + assertEquals("word: 4 letters", getOutputLines()[2]); + assertEquals("and: 3 letters", getOutputLines()[3]); + assertEquals("no error: 8 letters", getOutputLines()[4]); + } + + @Test + void runWithZeroArguments() { + String[] args = {}; + Main.main(args); + printOut(); + assertEquals("", getOutputLines()[0]); + + } +} \ No newline at end of file diff --git a/src/test/java/homework_2/traffic_light/TrafficLightDateTimeTest.java b/src/test/java/homework_2/traffic_light/TrafficLightDateTimeTest.java index 9ab91e74..00c0c4f2 100644 --- a/src/test/java/homework_2/traffic_light/TrafficLightDateTimeTest.java +++ b/src/test/java/homework_2/traffic_light/TrafficLightDateTimeTest.java @@ -1,9 +1,99 @@ package homework_2.traffic_light; import base.UnitBase; +import org.junit.jupiter.api.Test; +import static homework_2.traffic_light.ColorSelector.ANSI_RESET; +import static homework_2.traffic_light.ColorSelector.ANSI_YELLOW; import static org.junit.jupiter.api.Assertions.*; class TrafficLightDateTimeTest extends UnitBase { + final static TrafficLightDateTime trafficLightDateTime = new TrafficLightDateTime(); + private void run() { + trafficLightDateTime.dateTime(); + removeFromOutput("Provide time in \"hh:mm:ss\" format: "); + printOut(); + } + + @Test + void runGood() { + setInput("23:59:59"); + + run(); + + assertEquals("The traffic light is" + ANSI_YELLOW + " Yellow" + ANSI_RESET + " now", getOutput()); + } + + @Test + void runWithOneInputMissmatch() { + setInput("25:45:45"); + + run(); + + assertEquals("You entered an invalid date.", getOutput()); + } + + @Test + void runWithTwoInputMissmatch() { + setInput("25:65:45"); + + run(); + + assertEquals("You entered an invalid date.", getOutput()); + } + + @Test + void runWithThreeInputMissmatch() { + setInput("25:65:67"); + + run(); + + assertEquals("You entered an invalid date.", getOutput()); + } + + @Test + void runWithExtraField() { + setInput("25:65:67:67"); + + run(); + + assertEquals("You entered an invalid date.", getOutput()); + } + + @Test + void runWithNumberFormatException() { + setInput("error"); + + run(); + + assertEquals("Only numbers is allow.", getOutput()); + } + + @Test + void runWithZero() { + setInput("0"); + + run(); + + assertEquals("Incorrect input.", getOutput()); + } + + @Test + void runWithNegative() { + setInput("-5:23:45"); + + run(); + + assertEquals("You entered an invalid date.", getOutput()); + } + + @Test + void runWithOutOfBounds() { + setInput("5 5 5 5 5"); + + run(); + + assertEquals("Incorrect input.", getOutput()); + } } \ No newline at end of file diff --git a/src/test/java/homework_2/traffic_light/TrafficLightSecondsTest.java b/src/test/java/homework_2/traffic_light/TrafficLightSecondsTest.java index 19b4dd81..1e25e196 100644 --- a/src/test/java/homework_2/traffic_light/TrafficLightSecondsTest.java +++ b/src/test/java/homework_2/traffic_light/TrafficLightSecondsTest.java @@ -1,9 +1,61 @@ package homework_2.traffic_light; import base.UnitBase; +import org.junit.jupiter.api.Test; +import static homework_2.traffic_light.ColorSelector.*; import static org.junit.jupiter.api.Assertions.*; class TrafficLightSecondsTest extends UnitBase { + final static TrafficLightSeconds trafficLightSeconds = new TrafficLightSeconds(); + private void run() { + trafficLightSeconds.seconds(); + removeFromOutput("Provide time in seconds:"); + printOut(); + } + @Test + void runGood55(){ + setInput("55"); + + run(); + + assertEquals("The traffic light is" + ANSI_YELLOW + " Yellow" + ANSI_RESET + " now", getOutput()); + } + + @Test + void runGood7506(){ + setInput("7506"); + + run(); + + assertEquals("The traffic light is" + ANSI_GREEN + " Green" + ANSI_RESET + " now", getOutput()); + } + + @Test + void runWithNegative(){ + setInput("-5"); + + run(); + + assertEquals("Only non-negative numbers is allow.", getOutput()); + } + + @Test + void runWithInputMismatch(){ + setInput("error"); + + run(); + + assertEquals("Only numbers is allow.", getOutput()); + } + + @Test + void runWithOverload(){ + setInput("86401"); + + run(); + + assertEquals("Day is over.", getOutput()); + } } \ No newline at end of file From 86d5f3cd2e602e13fb526a113e619eee3d5015ec Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Sat, 24 Jul 2021 17:49:36 +0300 Subject: [PATCH 34/69] Update Readme.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d300d0b9..cd0e92e1 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,6 @@ | | [Traffic Light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_2/traffic_light) | The app that reads console and calculate current traffic light's color | | HW2 | [Pyramid Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_2/pyramid_printer) | The app that reads console and prints a pyramid based on this | | | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_2/random_chars_table) | The app that reads console for length, width and strategy and prints table based on this| - +| HW3 | [Immutable Class](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_3) | The class that give opportunity for create Immutable class| [CodingBat link](https://codingbat.com/done?user=slowly@live.ru&tag=8165639202) From 26f642c9a6767f4a8789f32edd8a9f4290d8d415 Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Sat, 24 Jul 2021 18:10:35 +0300 Subject: [PATCH 35/69] Edit ImmutableClass and add test --- src/main/java/homework_3/ImmutableClass.java | 23 ++++++++--------- .../java/homework_3/ImmutableClassTest.java | 25 +++++++++++++++++++ 2 files changed, 36 insertions(+), 12 deletions(-) create mode 100644 src/test/java/homework_3/ImmutableClassTest.java diff --git a/src/main/java/homework_3/ImmutableClass.java b/src/main/java/homework_3/ImmutableClass.java index 692107bc..baa23d22 100644 --- a/src/main/java/homework_3/ImmutableClass.java +++ b/src/main/java/homework_3/ImmutableClass.java @@ -16,47 +16,46 @@ public final class ImmutableClass { private final int integer; private final String string; - private final Integer integer1; + private final Integer bigInteger; public ImmutableClass(int integer, String string, Integer integer1) { this.integer = integer; this.string = string; - this.integer1 = new Integer(integer1); + this.bigInteger = new Integer(integer1); } public ImmutableClass(int integer, String string) { this.integer = integer; this.string = string; - this.integer1 = new Integer(null); + this.bigInteger = new Integer(null); } public ImmutableClass(int integer) { this.integer = integer; this.string = ""; - this.integer1 = new Integer(null); + this.bigInteger = new Integer(null); } public ImmutableClass() { this.integer = 6; this.string = "field"; - this.integer1 = new Integer(5); + this.bigInteger = new Integer(5); } public int getInteger() { - return integer; + return this.integer; } public String getString() { - return string; + return this.string; } - public Integer getInteger1() { - return integer1; + public Integer getBigInteger() { + return this.bigInteger; } - public ImmutableClass returnModifyObject() { - ImmutableClass immutableClass = new ImmutableClass(6, "field", 5); - return immutableClass; + public ImmutableClass returnModifyObject(Integer integer1) { + return new ImmutableClass(integer, string, integer1); } } diff --git a/src/test/java/homework_3/ImmutableClassTest.java b/src/test/java/homework_3/ImmutableClassTest.java new file mode 100644 index 00000000..acf7391e --- /dev/null +++ b/src/test/java/homework_3/ImmutableClassTest.java @@ -0,0 +1,25 @@ +package homework_3; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class ImmutableClassTest { + ImmutableClass immutableClass = new ImmutableClass(34, "String", 45); + ImmutableClass immutableClass1 = immutableClass.returnModifyObject(45); + + @Test + void testNotEquals() { + assertNotEquals(immutableClass, immutableClass1); + } + + @Test + void testMutableField() { + assertEquals(45, immutableClass1.getBigInteger()); + } + + @Test + void testBothMutableField() { + assertEquals(immutableClass1.getBigInteger(), immutableClass.getBigInteger()); + } +} \ No newline at end of file From 5ccef571bfbbc946799e18182845b60905bc111c Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Mon, 26 Jul 2021 01:36:08 +0300 Subject: [PATCH 36/69] --Changed the class names as specified in the condition --Made all run() methods public --- ...amidPrinterD.java => ExtraPyramidPrinter.java} | 4 ++-- .../java/homework_2/pyramid_printer/Main.java | 4 ++-- .../{PyramidPrinterX.java => PyramidPrinter.java} | 6 ++---- .../java/homework_2/random_chars_table/Main.java | 2 +- .../random_chars_table/RandomCharsTable.java | 4 +--- ...cLightDateTime.java => ExtraTrafficLight.java} | 4 ++-- src/main/java/homework_2/traffic_light/Main.java | 6 +++--- ...TrafficLightSeconds.java => TrafficLight.java} | 4 ++-- .../java/homework_1/char_count/CharCountTest.java | 2 -- ...terDTest.java => ExtraPyramidPrinterTest.java} | 4 ++-- ...dPrinterXTest.java => PyramidPrinterTest.java} | 13 ++++++------- ...teTimeTest.java => ExtraTrafficLightTest.java} | 9 +++------ ...ightSecondsTest.java => TrafficLightTest.java} | 15 +++++++-------- 13 files changed, 33 insertions(+), 44 deletions(-) rename src/main/java/homework_2/pyramid_printer/{PyramidPrinterD.java => ExtraPyramidPrinter.java} (91%) rename src/main/java/homework_2/pyramid_printer/{PyramidPrinterX.java => PyramidPrinter.java} (91%) rename src/main/java/homework_2/traffic_light/{TrafficLightDateTime.java => ExtraTrafficLight.java} (96%) rename src/main/java/homework_2/traffic_light/{TrafficLightSeconds.java => TrafficLight.java} (96%) rename src/test/java/homework_2/pyramid_printer/{PyramidPrinterDTest.java => ExtraPyramidPrinterTest.java} (92%) rename src/test/java/homework_2/pyramid_printer/{PyramidPrinterXTest.java => PyramidPrinterTest.java} (72%) rename src/test/java/homework_2/traffic_light/{TrafficLightDateTimeTest.java => ExtraTrafficLightTest.java} (84%) rename src/test/java/homework_2/traffic_light/{TrafficLightSecondsTest.java => TrafficLightTest.java} (76%) diff --git a/src/main/java/homework_2/pyramid_printer/PyramidPrinterD.java b/src/main/java/homework_2/pyramid_printer/ExtraPyramidPrinter.java similarity index 91% rename from src/main/java/homework_2/pyramid_printer/PyramidPrinterD.java rename to src/main/java/homework_2/pyramid_printer/ExtraPyramidPrinter.java index fb4ae69b..853034c2 100644 --- a/src/main/java/homework_2/pyramid_printer/PyramidPrinterD.java +++ b/src/main/java/homework_2/pyramid_printer/ExtraPyramidPrinter.java @@ -5,8 +5,8 @@ import static homework_2.pyramid_printer.Utils.*; -public class PyramidPrinterD { - protected static void run() { +public class ExtraPyramidPrinter { + public void run() { System.out.println(INPUT); try (Scanner scanner = new Scanner(System.in)) { int x = scanner.nextInt(); diff --git a/src/main/java/homework_2/pyramid_printer/Main.java b/src/main/java/homework_2/pyramid_printer/Main.java index 38d68310..3648b568 100644 --- a/src/main/java/homework_2/pyramid_printer/Main.java +++ b/src/main/java/homework_2/pyramid_printer/Main.java @@ -5,9 +5,9 @@ public static void main(String[] args) { if (args.length > 1) { System.out.println("Only 1 parameter is allowed"); } else if (args.length == 0) { - PyramidPrinterX.run(); + new PyramidPrinter().run(); } else if (args[0].equals("dRepresentation")) { - PyramidPrinterD.run(); + new ExtraPyramidPrinter().run(); } } } diff --git a/src/main/java/homework_2/pyramid_printer/PyramidPrinterX.java b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java similarity index 91% rename from src/main/java/homework_2/pyramid_printer/PyramidPrinterX.java rename to src/main/java/homework_2/pyramid_printer/PyramidPrinter.java index dce55603..ab2bc326 100644 --- a/src/main/java/homework_2/pyramid_printer/PyramidPrinterX.java +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -5,8 +5,8 @@ import static homework_2.pyramid_printer.Utils.*; -public class PyramidPrinterX { - protected static void run() { +public class PyramidPrinter { + public void run() { System.out.println(INPUT); try (Scanner scanner = new Scanner(System.in)) { int x = scanner.nextInt(); @@ -24,7 +24,5 @@ protected static void run() { System.out.println(INPUT_MISMATCH); } } - - } diff --git a/src/main/java/homework_2/random_chars_table/Main.java b/src/main/java/homework_2/random_chars_table/Main.java index 2eb9b88f..682fe366 100644 --- a/src/main/java/homework_2/random_chars_table/Main.java +++ b/src/main/java/homework_2/random_chars_table/Main.java @@ -2,6 +2,6 @@ public class Main { public static void main(String[] args) { - RandomCharsTable.run(); + new RandomCharsTable().run(); } } diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java index a69bb3e7..9938d983 100644 --- a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -1,7 +1,5 @@ package homework_2.random_chars_table; -import lombok.Data; - import java.util.InputMismatchException; import java.util.Random; import java.util.Scanner; @@ -10,7 +8,7 @@ public class RandomCharsTable { private static int length; private static int width; - protected static void run() { + public static void run() { System.out.println("Enter valid table length, width and strategy(even or odd) in format \"length width strategy\" "); getParameters(); } diff --git a/src/main/java/homework_2/traffic_light/TrafficLightDateTime.java b/src/main/java/homework_2/traffic_light/ExtraTrafficLight.java similarity index 96% rename from src/main/java/homework_2/traffic_light/TrafficLightDateTime.java rename to src/main/java/homework_2/traffic_light/ExtraTrafficLight.java index 100fa11d..54ec6cec 100644 --- a/src/main/java/homework_2/traffic_light/TrafficLightDateTime.java +++ b/src/main/java/homework_2/traffic_light/ExtraTrafficLight.java @@ -6,8 +6,8 @@ import static homework_2.traffic_light.ColorSelector.*; -public class TrafficLightDateTime { - protected static void dateTime() { +public class ExtraTrafficLight { + public static void run() { System.out.println("Provide time in \"hh:mm:ss\" format: "); try (Scanner scan = new Scanner(System.in)) { String nextLine = scan.next(); diff --git a/src/main/java/homework_2/traffic_light/Main.java b/src/main/java/homework_2/traffic_light/Main.java index f694b631..abb29a0a 100644 --- a/src/main/java/homework_2/traffic_light/Main.java +++ b/src/main/java/homework_2/traffic_light/Main.java @@ -5,9 +5,9 @@ public static void main(String[] args) { if (args.length > 1) { System.out.println("Only 1 parameter is allowed"); } else if (args.length == 0) { - TrafficLightSeconds.seconds(); - } else if (args[0].equals("LocalDateTime")) { - TrafficLightDateTime.dateTime(); + new TrafficLight().run(); + } else if (args[0].equals("ExtraMode")) { + new ExtraTrafficLight().run(); } } } \ No newline at end of file diff --git a/src/main/java/homework_2/traffic_light/TrafficLightSeconds.java b/src/main/java/homework_2/traffic_light/TrafficLight.java similarity index 96% rename from src/main/java/homework_2/traffic_light/TrafficLightSeconds.java rename to src/main/java/homework_2/traffic_light/TrafficLight.java index 7e71cbbb..d854053e 100644 --- a/src/main/java/homework_2/traffic_light/TrafficLightSeconds.java +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -5,8 +5,8 @@ import static homework_2.traffic_light.ColorSelector.*; -class TrafficLightSeconds { - protected static void seconds() { +class TrafficLight { + public static void run() { System.out.println("Provide time in seconds:"); try (Scanner scan = new Scanner(System.in)) { int seconds = scan.nextInt(); diff --git a/src/test/java/homework_1/char_count/CharCountTest.java b/src/test/java/homework_1/char_count/CharCountTest.java index 18f287a4..d1444343 100644 --- a/src/test/java/homework_1/char_count/CharCountTest.java +++ b/src/test/java/homework_1/char_count/CharCountTest.java @@ -1,9 +1,7 @@ package homework_1.char_count; import base.UnitBase; -import homework_1.CharCount; import homework_1.Main; -import homework_2.pyramid_printer.PyramidPrinterX; import org.junit.jupiter.api.Test; import static homework_1.CharCount.ANSI_RED; diff --git a/src/test/java/homework_2/pyramid_printer/PyramidPrinterDTest.java b/src/test/java/homework_2/pyramid_printer/ExtraPyramidPrinterTest.java similarity index 92% rename from src/test/java/homework_2/pyramid_printer/PyramidPrinterDTest.java rename to src/test/java/homework_2/pyramid_printer/ExtraPyramidPrinterTest.java index 1a0d0e6f..64e22314 100644 --- a/src/test/java/homework_2/pyramid_printer/PyramidPrinterDTest.java +++ b/src/test/java/homework_2/pyramid_printer/ExtraPyramidPrinterTest.java @@ -5,9 +5,9 @@ import static org.junit.jupiter.api.Assertions.*; -class PyramidPrinterDTest extends UnitBase { +class ExtraPyramidPrinterTest extends UnitBase { private void run() { - new PyramidPrinterD().run(); + new ExtraPyramidPrinter().run(); removeFromOutput("Enter a valid INT value for create a pyramid:"); printOut(); } diff --git a/src/test/java/homework_2/pyramid_printer/PyramidPrinterXTest.java b/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java similarity index 72% rename from src/test/java/homework_2/pyramid_printer/PyramidPrinterXTest.java rename to src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java index 2e88e490..1f3f76fe 100644 --- a/src/test/java/homework_2/pyramid_printer/PyramidPrinterXTest.java +++ b/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java @@ -3,12 +3,11 @@ import base.UnitBase; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; - -class PyramidPrinterXTest extends UnitBase { +import static org.junit.jupiter.api.Assertions.assertEquals; +class PyramidPrinterTest extends UnitBase { private void run() { - new PyramidPrinterX().run(); + new PyramidPrinter().run(); removeFromOutput("Enter a valid INT value for create a pyramid:"); printOut(); } @@ -39,7 +38,7 @@ void runWithZeroArguments() { run(); - assertEquals("",getOutput()); + assertEquals("", getOutput()); } @Test @@ -48,7 +47,7 @@ void runWithNegativeArgument() { run(); - assertEquals("Only 1 non-negative integer is allowed.",getOutput()); + assertEquals("Only 1 non-negative integer is allowed.", getOutput()); } @Test @@ -57,6 +56,6 @@ void runWithNotNumberArgument() { run(); - assertEquals("Only 1 non-negative integer is allowed.",getOutput()); + assertEquals("Only 1 non-negative integer is allowed.", getOutput()); } } \ No newline at end of file diff --git a/src/test/java/homework_2/traffic_light/TrafficLightDateTimeTest.java b/src/test/java/homework_2/traffic_light/ExtraTrafficLightTest.java similarity index 84% rename from src/test/java/homework_2/traffic_light/TrafficLightDateTimeTest.java rename to src/test/java/homework_2/traffic_light/ExtraTrafficLightTest.java index 00c0c4f2..28b12025 100644 --- a/src/test/java/homework_2/traffic_light/TrafficLightDateTimeTest.java +++ b/src/test/java/homework_2/traffic_light/ExtraTrafficLightTest.java @@ -3,15 +3,12 @@ import base.UnitBase; import org.junit.jupiter.api.Test; -import static homework_2.traffic_light.ColorSelector.ANSI_RESET; -import static homework_2.traffic_light.ColorSelector.ANSI_YELLOW; +import static homework_2.traffic_light.ColorSelector.*; import static org.junit.jupiter.api.Assertions.*; -class TrafficLightDateTimeTest extends UnitBase { - final static TrafficLightDateTime trafficLightDateTime = new TrafficLightDateTime(); - +class ExtraTrafficLightTest extends UnitBase { private void run() { - trafficLightDateTime.dateTime(); + new ExtraTrafficLight().run(); removeFromOutput("Provide time in \"hh:mm:ss\" format: "); printOut(); } diff --git a/src/test/java/homework_2/traffic_light/TrafficLightSecondsTest.java b/src/test/java/homework_2/traffic_light/TrafficLightTest.java similarity index 76% rename from src/test/java/homework_2/traffic_light/TrafficLightSecondsTest.java rename to src/test/java/homework_2/traffic_light/TrafficLightTest.java index 1e25e196..6db0d60d 100644 --- a/src/test/java/homework_2/traffic_light/TrafficLightSecondsTest.java +++ b/src/test/java/homework_2/traffic_light/TrafficLightTest.java @@ -6,16 +6,15 @@ import static homework_2.traffic_light.ColorSelector.*; import static org.junit.jupiter.api.Assertions.*; -class TrafficLightSecondsTest extends UnitBase { - final static TrafficLightSeconds trafficLightSeconds = new TrafficLightSeconds(); +class TrafficLightTest extends UnitBase { private void run() { - trafficLightSeconds.seconds(); + new TrafficLight().run(); removeFromOutput("Provide time in seconds:"); printOut(); } @Test - void runGood55(){ + void runGood55() { setInput("55"); run(); @@ -24,7 +23,7 @@ void runGood55(){ } @Test - void runGood7506(){ + void runGood7506() { setInput("7506"); run(); @@ -33,7 +32,7 @@ void runGood7506(){ } @Test - void runWithNegative(){ + void runWithNegative() { setInput("-5"); run(); @@ -42,7 +41,7 @@ void runWithNegative(){ } @Test - void runWithInputMismatch(){ + void runWithInputMismatch() { setInput("error"); run(); @@ -51,7 +50,7 @@ void runWithInputMismatch(){ } @Test - void runWithOverload(){ + void runWithOverload() { setInput("86401"); run(); From a2b062fddf4d1aec064c97173177013c0cf9af2a Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Mon, 26 Jul 2021 01:42:14 +0300 Subject: [PATCH 37/69] Fixed typo in README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index cd0e92e1..bc1fbd2e 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,6 @@ | | [Traffic Light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_2/traffic_light) | The app that reads console and calculate current traffic light's color | | HW2 | [Pyramid Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_2/pyramid_printer) | The app that reads console and prints a pyramid based on this | | | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_2/random_chars_table) | The app that reads console for length, width and strategy and prints table based on this| -| HW3 | [Immutable Class](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_3) | The class that give opportunity for create Immutable class| +| HW3 | [Immutable Class](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_3) | The class that give opportunity for create Immutable object| [CodingBat link](https://codingbat.com/done?user=slowly@live.ru&tag=8165639202) From 375015010cd5781cb2d8ad027cbd9df6d3de600a Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Tue, 27 Jul 2021 01:40:40 +0300 Subject: [PATCH 38/69] Change the type of abstraction --- ...tableClass.java => ImmutableClassMan.java} | 56 +++++++++---------- .../homework_3/ImmutableClassManTest.java | 25 +++++++++ .../java/homework_3/ImmutableClassTest.java | 25 --------- 3 files changed, 53 insertions(+), 53 deletions(-) rename src/main/java/homework_3/{ImmutableClass.java => ImmutableClassMan.java} (51%) create mode 100644 src/test/java/homework_3/ImmutableClassManTest.java delete mode 100644 src/test/java/homework_3/ImmutableClassTest.java diff --git a/src/main/java/homework_3/ImmutableClass.java b/src/main/java/homework_3/ImmutableClassMan.java similarity index 51% rename from src/main/java/homework_3/ImmutableClass.java rename to src/main/java/homework_3/ImmutableClassMan.java index baa23d22..f916a018 100644 --- a/src/main/java/homework_3/ImmutableClass.java +++ b/src/main/java/homework_3/ImmutableClassMan.java @@ -13,49 +13,49 @@ 6. A parameterized constructor should initialize all the fields performing a deep copy (So that data members can’t be modified with object reference). */ -public final class ImmutableClass { - private final int integer; - private final String string; - private final Integer bigInteger; +public final class ImmutableClassMan { + private final int age; + private final String name; + private final Integer iq; - public ImmutableClass(int integer, String string, Integer integer1) { - this.integer = integer; - this.string = string; - this.bigInteger = new Integer(integer1); + public ImmutableClassMan(int age, String name, Integer iq) { + this.age = age; + this.name = name; + this.iq = new Integer(iq); } - public ImmutableClass(int integer, String string) { - this.integer = integer; - this.string = string; - this.bigInteger = new Integer(null); + public ImmutableClassMan(int age, String name) { + this.age = age; + this.name = name; + this.iq = new Integer(null); } - public ImmutableClass(int integer) { - this.integer = integer; - this.string = ""; - this.bigInteger = new Integer(null); + public ImmutableClassMan(int age) { + this.age = age; + this.name = ""; + this.iq = new Integer(null); } - public ImmutableClass() { - this.integer = 6; - this.string = "field"; - this.bigInteger = new Integer(5); + public ImmutableClassMan() { + this.age = 6; + this.name = "Ivan"; + this.iq = new Integer(128); } - public int getInteger() { - return this.integer; + public int getAge() { + return this.age; } - public String getString() { - return this.string; + public String getName() { + return this.name; } - public Integer getBigInteger() { - return this.bigInteger; + public Integer getIq() { + return this.iq; } - public ImmutableClass returnModifyObject(Integer integer1) { - return new ImmutableClass(integer, string, integer1); + public ImmutableClassMan returnModifyMan(Integer iq) { + return new ImmutableClassMan(age, name, iq); } } diff --git a/src/test/java/homework_3/ImmutableClassManTest.java b/src/test/java/homework_3/ImmutableClassManTest.java new file mode 100644 index 00000000..13075b76 --- /dev/null +++ b/src/test/java/homework_3/ImmutableClassManTest.java @@ -0,0 +1,25 @@ +package homework_3; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class ImmutableClassManTest { + ImmutableClassMan immutableClassMan = new ImmutableClassMan(34, "String", 143); + ImmutableClassMan immutableClassMan1 = immutableClassMan.returnModifyMan(143); + + @Test + void testNotEquals() { + assertNotEquals(immutableClassMan, immutableClassMan1); + } + + @Test + void testMutableField() { + assertEquals(143, immutableClassMan1.getIq()); + } + + @Test + void testBothMutableField() { + assertEquals(immutableClassMan1.getIq(), immutableClassMan.getIq()); + } +} \ No newline at end of file diff --git a/src/test/java/homework_3/ImmutableClassTest.java b/src/test/java/homework_3/ImmutableClassTest.java deleted file mode 100644 index acf7391e..00000000 --- a/src/test/java/homework_3/ImmutableClassTest.java +++ /dev/null @@ -1,25 +0,0 @@ -package homework_3; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.*; - -class ImmutableClassTest { - ImmutableClass immutableClass = new ImmutableClass(34, "String", 45); - ImmutableClass immutableClass1 = immutableClass.returnModifyObject(45); - - @Test - void testNotEquals() { - assertNotEquals(immutableClass, immutableClass1); - } - - @Test - void testMutableField() { - assertEquals(45, immutableClass1.getBigInteger()); - } - - @Test - void testBothMutableField() { - assertEquals(immutableClass1.getBigInteger(), immutableClass.getBigInteger()); - } -} \ No newline at end of file From 35754932069029e0229223d73cbb52339c7b0faa Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Sun, 8 Aug 2021 17:10:35 +0300 Subject: [PATCH 39/69] Changed the names of the tests, added some blank lines, deleted tests for Immutable Class --- src/main/java/homework_1/CharCount.java | 1 + src/main/java/homework_1/Main.java | 1 + .../pyramid_printer/ExtraPyramidPrinter.java | 1 + .../java/homework_2/pyramid_printer/Main.java | 1 + .../pyramid_printer/PyramidPrinter.java | 1 + .../homework_2/pyramid_printer/Utils.java | 2 +- .../homework_2/random_chars_table/Main.java | 1 + .../random_chars_table/RandomCharsTable.java | 7 +-- .../traffic_light/ExtraTrafficLight.java | 1 + .../java/homework_2/traffic_light/Main.java | 1 + .../traffic_light/TrafficLight.java | 5 +- .../java/homework_3/ImmutableClassMan.java | 3 +- .../custom_annotation/CustomAnnotation.java | 9 ++++ .../custom_annotation/HelloGenerator.java | 35 ++++++++++++++ .../custom_file_reader/CustomFileReader.java | 47 +++++++++++++++++++ .../homework_4/custom_file_reader/Main.java | 8 ++++ .../java/homework_4/singleton/Singleton.java | 20 ++++++++ .../custom_file_reader/custom.file.reader.txt | 1 + .../homework_1/char_count/CharCountTest.java | 7 ++- .../ExtraPyramidPrinterTest.java | 10 ++-- .../pyramid_printer/PyramidPrinterTest.java | 11 +++-- .../RandomCharsTableTest.java | 12 ++--- .../traffic_light/ExtraTrafficLightTest.java | 19 ++++---- .../traffic_light/TrafficLightTest.java | 15 +++--- .../homework_3/ImmutableClassManTest.java | 25 ---------- .../CustomFileReaderTest.java | 43 +++++++++++++++++ .../homework_4/singleton/SingletonTest.java | 15 ++++++ 27 files changed, 234 insertions(+), 68 deletions(-) create mode 100644 src/main/java/homework_4/custom_annotation/CustomAnnotation.java create mode 100644 src/main/java/homework_4/custom_annotation/HelloGenerator.java create mode 100644 src/main/java/homework_4/custom_file_reader/CustomFileReader.java create mode 100644 src/main/java/homework_4/custom_file_reader/Main.java create mode 100644 src/main/java/homework_4/singleton/Singleton.java create mode 100644 src/main/resources/custom_file_reader/custom.file.reader.txt delete mode 100644 src/test/java/homework_3/ImmutableClassManTest.java create mode 100644 src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java create mode 100644 src/test/java/homework_4/singleton/SingletonTest.java diff --git a/src/main/java/homework_1/CharCount.java b/src/main/java/homework_1/CharCount.java index b0aa7eb7..6d4d0b1c 100644 --- a/src/main/java/homework_1/CharCount.java +++ b/src/main/java/homework_1/CharCount.java @@ -1,6 +1,7 @@ package homework_1; public class CharCount { + public static final String ANSI_RED = "\u001B[31m"; public static final String ANSI_RESET = "\u001B[0m"; diff --git a/src/main/java/homework_1/Main.java b/src/main/java/homework_1/Main.java index 3c466a0c..0994a298 100644 --- a/src/main/java/homework_1/Main.java +++ b/src/main/java/homework_1/Main.java @@ -1,6 +1,7 @@ package homework_1; public class Main { + public static void main(String[] args) { CharCount.run(args); } diff --git a/src/main/java/homework_2/pyramid_printer/ExtraPyramidPrinter.java b/src/main/java/homework_2/pyramid_printer/ExtraPyramidPrinter.java index 853034c2..c331d160 100644 --- a/src/main/java/homework_2/pyramid_printer/ExtraPyramidPrinter.java +++ b/src/main/java/homework_2/pyramid_printer/ExtraPyramidPrinter.java @@ -6,6 +6,7 @@ import static homework_2.pyramid_printer.Utils.*; public class ExtraPyramidPrinter { + public void run() { System.out.println(INPUT); try (Scanner scanner = new Scanner(System.in)) { diff --git a/src/main/java/homework_2/pyramid_printer/Main.java b/src/main/java/homework_2/pyramid_printer/Main.java index 3648b568..df73a866 100644 --- a/src/main/java/homework_2/pyramid_printer/Main.java +++ b/src/main/java/homework_2/pyramid_printer/Main.java @@ -1,6 +1,7 @@ package homework_2.pyramid_printer; public class Main { + public static void main(String[] args) { if (args.length > 1) { System.out.println("Only 1 parameter is allowed"); diff --git a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java index ab2bc326..34d5fef3 100644 --- a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -6,6 +6,7 @@ import static homework_2.pyramid_printer.Utils.*; public class PyramidPrinter { + public void run() { System.out.println(INPUT); try (Scanner scanner = new Scanner(System.in)) { diff --git a/src/main/java/homework_2/pyramid_printer/Utils.java b/src/main/java/homework_2/pyramid_printer/Utils.java index 480f83d6..12b877ec 100644 --- a/src/main/java/homework_2/pyramid_printer/Utils.java +++ b/src/main/java/homework_2/pyramid_printer/Utils.java @@ -1,6 +1,6 @@ package homework_2.pyramid_printer; -class Utils { +final class Utils { static final String INPUT_MISMATCH = "Only 1 non-negative integer is allowed."; static final String INPUT = "Enter a valid INT value for create a pyramid:"; } diff --git a/src/main/java/homework_2/random_chars_table/Main.java b/src/main/java/homework_2/random_chars_table/Main.java index 682fe366..be586c4b 100644 --- a/src/main/java/homework_2/random_chars_table/Main.java +++ b/src/main/java/homework_2/random_chars_table/Main.java @@ -1,6 +1,7 @@ package homework_2.random_chars_table; public class Main { + public static void main(String[] args) { new RandomCharsTable().run(); } diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java index 9938d983..f48e0e64 100644 --- a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -5,6 +5,7 @@ import java.util.Scanner; public class RandomCharsTable { + private static int length; private static int width; @@ -23,9 +24,9 @@ private static void getParameters() { char[][] table = new char[length][width]; fillAndPrintTable(strategy, table); } catch (NegativeArraySizeException e) { - System.out.println("Array size cannot be negative."); + System.out.println("Passed parameters should match the format [positive integer] [positive integer] [even|odd]"); } catch (InputMismatchException e) { - System.out.println("Input parameters must be in the format [positive integer(>0)] [positive integer(>0)] [even|odd]"); + System.out.println("Passed parameters should match the format [positive integer] [positive integer] [even|odd]"); } } @@ -40,7 +41,7 @@ private static void fillAndPrintTable(String strategy, char[][] table) { for (int i = 0; i < length; i++) { for (int j = 0; j < width; j++) { - table[i][j] = (char) (random.nextInt((90 - 65) + 1) + 65); + table[i][j] = (char) (random.nextInt((26) + 1) + 65); System.out.print("|" + table[i][j] + "|"); } System.out.println(); diff --git a/src/main/java/homework_2/traffic_light/ExtraTrafficLight.java b/src/main/java/homework_2/traffic_light/ExtraTrafficLight.java index 54ec6cec..02811eb4 100644 --- a/src/main/java/homework_2/traffic_light/ExtraTrafficLight.java +++ b/src/main/java/homework_2/traffic_light/ExtraTrafficLight.java @@ -7,6 +7,7 @@ public class ExtraTrafficLight { + public static void run() { System.out.println("Provide time in \"hh:mm:ss\" format: "); try (Scanner scan = new Scanner(System.in)) { diff --git a/src/main/java/homework_2/traffic_light/Main.java b/src/main/java/homework_2/traffic_light/Main.java index abb29a0a..6d66c93c 100644 --- a/src/main/java/homework_2/traffic_light/Main.java +++ b/src/main/java/homework_2/traffic_light/Main.java @@ -1,6 +1,7 @@ package homework_2.traffic_light; public class Main { + public static void main(String[] args) { if (args.length > 1) { System.out.println("Only 1 parameter is allowed"); diff --git a/src/main/java/homework_2/traffic_light/TrafficLight.java b/src/main/java/homework_2/traffic_light/TrafficLight.java index d854053e..935012e1 100644 --- a/src/main/java/homework_2/traffic_light/TrafficLight.java +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -6,19 +6,20 @@ import static homework_2.traffic_light.ColorSelector.*; class TrafficLight { + public static void run() { System.out.println("Provide time in seconds:"); try (Scanner scan = new Scanner(System.in)) { int seconds = scan.nextInt(); if (seconds < 0) { - System.out.println("Only non-negative numbers is allow."); + System.out.println("Only 1 non-negative integer is allowed as passed parameter"); } else if (seconds >= 86400) { System.out.println("Day is over."); } else { getSeconds(seconds); } } catch (InputMismatchException e) { - System.out.println("Only numbers is allow."); + System.out.println("Only 1 non-negative integer is allowed as passed parameter"); } } diff --git a/src/main/java/homework_3/ImmutableClassMan.java b/src/main/java/homework_3/ImmutableClassMan.java index f916a018..18a3a731 100644 --- a/src/main/java/homework_3/ImmutableClassMan.java +++ b/src/main/java/homework_3/ImmutableClassMan.java @@ -14,6 +14,7 @@ */ public final class ImmutableClassMan { + private final int age; private final String name; private final Integer iq; @@ -33,7 +34,7 @@ public ImmutableClassMan(int age, String name) { public ImmutableClassMan(int age) { this.age = age; this.name = ""; - this.iq = new Integer(null); + this.iq = null; } public ImmutableClassMan() { diff --git a/src/main/java/homework_4/custom_annotation/CustomAnnotation.java b/src/main/java/homework_4/custom_annotation/CustomAnnotation.java new file mode 100644 index 00000000..881c3ebd --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/CustomAnnotation.java @@ -0,0 +1,9 @@ +package homework_4.custom_annotation; + +import java.lang.annotation.*; + +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +public @interface CustomAnnotation { + String name() default "Ilia"; +} diff --git a/src/main/java/homework_4/custom_annotation/HelloGenerator.java b/src/main/java/homework_4/custom_annotation/HelloGenerator.java new file mode 100644 index 00000000..2b1dd16e --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/HelloGenerator.java @@ -0,0 +1,35 @@ +package homework_4.custom_annotation; + +@CustomAnnotation +public class HelloGenerator { + private String name; + private int age; + + public HelloGenerator(String name, int age) { + if (name == null || name.isEmpty()) { + CustomAnnotation customAnnotation = (CustomAnnotation) this.getClass().getDeclaredAnnotations()[0]; + this.name = customAnnotation.name(); + } else { + this.name = name; + } + this.age = age; + } + + public String getName() { + return name; + } + + public int getAge() { + return age; + } + + public static void main(String[] args) { + HelloGenerator helloGenerator = new HelloGenerator("", 16); + System.out.println(helloGenerator); + } + + @Override + public String toString() { + return "Hello " + name + "!" + " You are " + age + " year old!"; + } +} diff --git a/src/main/java/homework_4/custom_file_reader/CustomFileReader.java b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java new file mode 100644 index 00000000..f9ab0f3a --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java @@ -0,0 +1,47 @@ +package homework_4.custom_file_reader; + +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.Scanner; + +public class CustomFileReader { + + static final String GLOBAL_PATH = "src/main/resources/custom_file_reader/custom.file.reader.txt"; + + public void run1() { + try (Scanner input = new Scanner(new File(GLOBAL_PATH))) { + String line = input.nextLine().replace(",", ""); + String output = line.replace(".", ""); + System.out.println(output); + } catch (FileNotFoundException e) { + System.out.println("File not found."); + } + } + + public void run2() { + StringBuilder contents = new StringBuilder(); + try (BufferedReader reader = new BufferedReader(new FileReader(GLOBAL_PATH))) { + String file = ""; + while ((file = reader.readLine()) != null) { + System.out.println(contents.append(file.replaceAll("[,.]", ""))); + } + } catch (IOException e) { + System.out.println("File not found."); + } + } + + public void run3() { + Path path = Paths.get(GLOBAL_PATH); + try { + List text = Files.readAllLines(path); + for (String line : text) { + System.out.println(line.replaceAll("[,.]", "")); + } + } catch (IOException e) { + System.out.println("File not found"); + } + } +} diff --git a/src/main/java/homework_4/custom_file_reader/Main.java b/src/main/java/homework_4/custom_file_reader/Main.java new file mode 100644 index 00000000..fba1bc7d --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/Main.java @@ -0,0 +1,8 @@ +package homework_4.custom_file_reader; + +public class Main { + + public static void main(String[] args) { + new CustomFileReader().run2(); + } +} diff --git a/src/main/java/homework_4/singleton/Singleton.java b/src/main/java/homework_4/singleton/Singleton.java new file mode 100644 index 00000000..dbfec216 --- /dev/null +++ b/src/main/java/homework_4/singleton/Singleton.java @@ -0,0 +1,20 @@ +package homework_4.singleton; + +public class Singleton { + + private static Singleton instance; + + private Singleton() { + } + + public static Singleton getInstance() { + if (instance == null) { + synchronized (Singleton.class){ + if (instance == null){ + instance = new Singleton(); + } + } + } + return instance; + } +} diff --git a/src/main/resources/custom_file_reader/custom.file.reader.txt b/src/main/resources/custom_file_reader/custom.file.reader.txt new file mode 100644 index 00000000..c520610e --- /dev/null +++ b/src/main/resources/custom_file_reader/custom.file.reader.txt @@ -0,0 +1 @@ +Мы часто повторяем, что о человеке судят по его делам, но забываем иногда, что слово тоже поступок. Речь человека — зеркало его самого. Всё фальшивое , лживое или вульгарное, как бы человек ни пытался скрыть это от других, вся пустота, черствость или грубость прорываются в его речи с такой же силой и очевидностью, с какой проявляются искренность и благородство, глубина и тонкость мыслей и чувств. То, о чём говорит человек, отражает его внутренний мир. \ No newline at end of file diff --git a/src/test/java/homework_1/char_count/CharCountTest.java b/src/test/java/homework_1/char_count/CharCountTest.java index d1444343..4768b3a8 100644 --- a/src/test/java/homework_1/char_count/CharCountTest.java +++ b/src/test/java/homework_1/char_count/CharCountTest.java @@ -10,7 +10,7 @@ class CharCountTest extends UnitBase { @Test - void runWithError() { + void givenError_whenRun_thenExpected() { String[] args = {"some", "new", "word", "and", "error"}; Main.main(args); printOut(); @@ -22,7 +22,7 @@ void runWithError() { } @Test - void runWithoutError() { + void givenNoError_whenRun_thenExpected() { String[] args = {"some", "new", "word", "and", "no error"}; Main.main(args); printOut(); @@ -34,11 +34,10 @@ void runWithoutError() { } @Test - void runWithZeroArguments() { + void givenZeroArguments_whenRun_thenExpected() { String[] args = {}; Main.main(args); printOut(); assertEquals("", getOutputLines()[0]); - } } \ No newline at end of file diff --git a/src/test/java/homework_2/pyramid_printer/ExtraPyramidPrinterTest.java b/src/test/java/homework_2/pyramid_printer/ExtraPyramidPrinterTest.java index 64e22314..232de1e1 100644 --- a/src/test/java/homework_2/pyramid_printer/ExtraPyramidPrinterTest.java +++ b/src/test/java/homework_2/pyramid_printer/ExtraPyramidPrinterTest.java @@ -13,7 +13,7 @@ private void run() { } @Test - void runWithOneArgument() { + void givenPositive1_whenRun_thenExpected() { setInput("1"); run(); @@ -22,7 +22,7 @@ void runWithOneArgument() { } @Test - void runWithThreeArguments() { + void givenPositive3_whenRun_thenExpected() { setInput("3"); run(); @@ -33,7 +33,7 @@ void runWithThreeArguments() { } @Test - void runWithZeroArguments() { + void given0_whenRun_thenExpected() { setInput("0"); run(); @@ -42,7 +42,7 @@ void runWithZeroArguments() { } @Test - void runWithNegativeArgument() { + void givenNegative_whenRun_thenExpectedError() { setInput("-5"); run(); @@ -51,7 +51,7 @@ void runWithNegativeArgument() { } @Test - void runWithNotNumberArgument() { + void givenNaN_whenRun_thenExpectedError() { setInput("asd"); run(); diff --git a/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java b/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java index 1f3f76fe..25a4a85b 100644 --- a/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java +++ b/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java @@ -6,6 +6,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; class PyramidPrinterTest extends UnitBase { + private void run() { new PyramidPrinter().run(); removeFromOutput("Enter a valid INT value for create a pyramid:"); @@ -13,7 +14,7 @@ private void run() { } @Test - void runWithOneArgument() { + void givenPositive1_whenRun_thenExpected() { setInput("1"); run(); @@ -22,7 +23,7 @@ void runWithOneArgument() { } @Test - void runWithThreeArguments() { + void givenPositive3_whenRun_thenExpected() { setInput("3"); run(); @@ -33,7 +34,7 @@ void runWithThreeArguments() { } @Test - void runWithZeroArguments() { + void givenZero_whenRun_thenExpected() { setInput("0"); run(); @@ -42,7 +43,7 @@ void runWithZeroArguments() { } @Test - void runWithNegativeArgument() { + void givenNegative_whenRun_thenExpectedError() { setInput("-5"); run(); @@ -51,7 +52,7 @@ void runWithNegativeArgument() { } @Test - void runWithNotNumberArgument() { + void givenNaN_whenRun_thenExpectedError() { setInput("asd"); run(); diff --git a/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java b/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java index 3e7c7514..7543d541 100644 --- a/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java +++ b/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java @@ -14,30 +14,30 @@ private void run() { } @Test - void runWithNegativeArgument() { + void givenNegative_whenRun_thenArraySizeError() { setInput("-1 5 even"); run(); - assertEquals("Array size cannot be negative.", getOutput()); + assertEquals("Passed parameters should match the format [positive integer] [positive integer] [even|odd]", getOutput()); } @Test - void runWithMismatchArguments() { + void givenWrongArgument_whenRun_thenInputError() { setInput("error 5 even"); run(); - assertEquals("Input parameters must be in the format [positive integer(>0)] [positive integer(>0)] [even|odd]", getOutput()); + assertEquals("Passed parameters should match the format [positive integer] [positive integer] [even|odd]", getOutput()); } @Test - void runWithMismatchStrategy() { + void givenWrongStrategyName_whenRun_thenInputError() { setInput("4 5 error"); run(); - assertEquals("Input parameters must be in the format [positive integer(>0)] [positive integer(>0)] [even|odd]", getOutput()); + assertEquals("Passed parameters should match the format [positive integer] [positive integer] [even|odd]", getOutput()); } } \ No newline at end of file diff --git a/src/test/java/homework_2/traffic_light/ExtraTrafficLightTest.java b/src/test/java/homework_2/traffic_light/ExtraTrafficLightTest.java index 28b12025..67d4702a 100644 --- a/src/test/java/homework_2/traffic_light/ExtraTrafficLightTest.java +++ b/src/test/java/homework_2/traffic_light/ExtraTrafficLightTest.java @@ -14,16 +14,17 @@ private void run() { } @Test - void runGood() { + void givenValidArguments_whenRun_thenYellowOutput() { setInput("23:59:59"); run(); assertEquals("The traffic light is" + ANSI_YELLOW + " Yellow" + ANSI_RESET + " now", getOutput()); + } @Test - void runWithOneInputMissmatch() { + void givenOneWrongArgument_whenRun_thenInputError() { setInput("25:45:45"); run(); @@ -32,7 +33,7 @@ void runWithOneInputMissmatch() { } @Test - void runWithTwoInputMissmatch() { + void givenTwoWrongArguments_whenRun_thenInputError() { setInput("25:65:45"); run(); @@ -41,7 +42,7 @@ void runWithTwoInputMissmatch() { } @Test - void runWithThreeInputMissmatch() { + void givenThreeWrongArguments_whenRun_thenInputError() { setInput("25:65:67"); run(); @@ -50,7 +51,7 @@ void runWithThreeInputMissmatch() { } @Test - void runWithExtraField() { + void givenAdditionalField_whenRun_thenInputError() { setInput("25:65:67:67"); run(); @@ -59,7 +60,7 @@ void runWithExtraField() { } @Test - void runWithNumberFormatException() { + void givenNaN_whenRun_thenNumberFormatError() { setInput("error"); run(); @@ -68,7 +69,7 @@ void runWithNumberFormatException() { } @Test - void runWithZero() { + void givenZero_whenRun_thenInputError() { setInput("0"); run(); @@ -77,7 +78,7 @@ void runWithZero() { } @Test - void runWithNegative() { + void givenNegativeArgument_whenRun_thenInputError() { setInput("-5:23:45"); run(); @@ -86,7 +87,7 @@ void runWithNegative() { } @Test - void runWithOutOfBounds() { + void givenOutOfBoundsArguments_whenRun_thenInputError() { setInput("5 5 5 5 5"); run(); diff --git a/src/test/java/homework_2/traffic_light/TrafficLightTest.java b/src/test/java/homework_2/traffic_light/TrafficLightTest.java index 6db0d60d..b1d46433 100644 --- a/src/test/java/homework_2/traffic_light/TrafficLightTest.java +++ b/src/test/java/homework_2/traffic_light/TrafficLightTest.java @@ -7,6 +7,7 @@ import static org.junit.jupiter.api.Assertions.*; class TrafficLightTest extends UnitBase { + private void run() { new TrafficLight().run(); removeFromOutput("Provide time in seconds:"); @@ -14,7 +15,7 @@ private void run() { } @Test - void runGood55() { + void given55_whenRun_thenYellowOutput() { setInput("55"); run(); @@ -23,7 +24,7 @@ void runGood55() { } @Test - void runGood7506() { + void given7506_whenRun_thenGreenOutput() { setInput("7506"); run(); @@ -32,25 +33,25 @@ void runGood7506() { } @Test - void runWithNegative() { + void givenNegative_whenRun_thenInputError() { setInput("-5"); run(); - assertEquals("Only non-negative numbers is allow.", getOutput()); + assertEquals("Only 1 non-negative integer is allowed as passed parameter", getOutput()); } @Test - void runWithInputMismatch() { + void givenNan_whenRun_thenInputError() { setInput("error"); run(); - assertEquals("Only numbers is allow.", getOutput()); + assertEquals("Only 1 non-negative integer is allowed as passed parameter", getOutput()); } @Test - void runWithOverload() { + void givenMoreThanDay_whenRun_thenDayOverError() { setInput("86401"); run(); diff --git a/src/test/java/homework_3/ImmutableClassManTest.java b/src/test/java/homework_3/ImmutableClassManTest.java deleted file mode 100644 index 13075b76..00000000 --- a/src/test/java/homework_3/ImmutableClassManTest.java +++ /dev/null @@ -1,25 +0,0 @@ -package homework_3; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.*; - -class ImmutableClassManTest { - ImmutableClassMan immutableClassMan = new ImmutableClassMan(34, "String", 143); - ImmutableClassMan immutableClassMan1 = immutableClassMan.returnModifyMan(143); - - @Test - void testNotEquals() { - assertNotEquals(immutableClassMan, immutableClassMan1); - } - - @Test - void testMutableField() { - assertEquals(143, immutableClassMan1.getIq()); - } - - @Test - void testBothMutableField() { - assertEquals(immutableClassMan1.getIq(), immutableClassMan.getIq()); - } -} \ No newline at end of file diff --git a/src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java b/src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java new file mode 100644 index 00000000..a2707f0d --- /dev/null +++ b/src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java @@ -0,0 +1,43 @@ +package homework_4.custom_file_reader; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import java.io.FileNotFoundException; +import java.io.IOException; + +import static org.junit.jupiter.api.Assertions.*; + +class CustomFileReaderTest extends UnitBase { + CustomFileReader customFileReader = new CustomFileReader(); + + @Test + void testRun1() { + customFileReader.run1(); + String expected = getOutput(); + if (expected.contains(",") || expected.contains(".")) { + throw new IllegalArgumentException("Text contains symbol ',' or symbol '.'"); + } + assertEquals(expected, getOutput()); + } + + @Test + void testRun2() { + customFileReader.run2(); + String expected = getOutput(); + if (expected.contains(",") || expected.contains(".")) { + throw new IllegalArgumentException("Text contains symbol ',' or symbol '.'"); + } + assertEquals(expected, getOutput()); + } + + @Test + void testRun3() { + customFileReader.run3(); + String expected = getOutput(); + if (expected.contains(",") || expected.contains(".")) { + throw new IllegalArgumentException("Text contains symbol ',' or symbol '.'"); + } + assertEquals(expected, getOutput()); + } +} \ No newline at end of file diff --git a/src/test/java/homework_4/singleton/SingletonTest.java b/src/test/java/homework_4/singleton/SingletonTest.java new file mode 100644 index 00000000..a6ec4ebf --- /dev/null +++ b/src/test/java/homework_4/singleton/SingletonTest.java @@ -0,0 +1,15 @@ +package homework_4.singleton; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class SingletonTest { + + @Test + void assertSingletons() { + Singleton expected = Singleton.getInstance(); + Singleton actual = Singleton.getInstance(); + assertSame(expected, actual); + } +} \ No newline at end of file From e81d405b69688ecc579b013fbc945f837c5f9529 Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Sun, 8 Aug 2021 22:10:48 +0300 Subject: [PATCH 40/69] Refactoring + README edit --- README.md | 3 +++ src/main/java/homework_1/Main.java | 2 +- .../java/homework_2/pyramid_printer/ExtraPyramidPrinter.java | 3 ++- src/main/java/homework_2/pyramid_printer/PyramidPrinter.java | 3 ++- .../java/homework_2/random_chars_table/RandomCharsTable.java | 2 +- .../java/homework_2/traffic_light/ExtraTrafficLight.java | 2 +- src/main/java/homework_2/traffic_light/TrafficLight.java | 2 +- .../java/homework_4/custom_annotation/CustomAnnotation.java | 5 ++++- src/main/java/homework_4/singleton/Singleton.java | 4 ++-- .../java/homework_2/traffic_light/ExtraTrafficLightTest.java | 1 - 10 files changed, 17 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index bc1fbd2e..f001b4c2 100644 --- a/README.md +++ b/README.md @@ -9,5 +9,8 @@ | HW2 | [Pyramid Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_2/pyramid_printer) | The app that reads console and prints a pyramid based on this | | | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_2/random_chars_table) | The app that reads console for length, width and strategy and prints table based on this| | HW3 | [Immutable Class](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_3) | The class that give opportunity for create Immutable object| +| | [Custom Annotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_4/custom_annotation) | A form of syntactic metadata that can be added to Java source code| +| HW4 | [Custom File Reader](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_4/custom_file_reader) | An app that provides 3 ways to read and edit a file| +| | [Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_4/singleton) | Creational design pattern, which ensures that only one object of its kind exists | [CodingBat link](https://codingbat.com/done?user=slowly@live.ru&tag=8165639202) diff --git a/src/main/java/homework_1/Main.java b/src/main/java/homework_1/Main.java index 0994a298..d22a36b1 100644 --- a/src/main/java/homework_1/Main.java +++ b/src/main/java/homework_1/Main.java @@ -1,7 +1,7 @@ package homework_1; public class Main { - + public static void main(String[] args) { CharCount.run(args); } diff --git a/src/main/java/homework_2/pyramid_printer/ExtraPyramidPrinter.java b/src/main/java/homework_2/pyramid_printer/ExtraPyramidPrinter.java index c331d160..3f6bfa0e 100644 --- a/src/main/java/homework_2/pyramid_printer/ExtraPyramidPrinter.java +++ b/src/main/java/homework_2/pyramid_printer/ExtraPyramidPrinter.java @@ -3,7 +3,8 @@ import java.util.InputMismatchException; import java.util.Scanner; -import static homework_2.pyramid_printer.Utils.*; +import static homework_2.pyramid_printer.Utils.INPUT; +import static homework_2.pyramid_printer.Utils.INPUT_MISMATCH; public class ExtraPyramidPrinter { diff --git a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java index 34d5fef3..117ce5e2 100644 --- a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -3,7 +3,8 @@ import java.util.InputMismatchException; import java.util.Scanner; -import static homework_2.pyramid_printer.Utils.*; +import static homework_2.pyramid_printer.Utils.INPUT; +import static homework_2.pyramid_printer.Utils.INPUT_MISMATCH; public class PyramidPrinter { diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java index f48e0e64..482b6e77 100644 --- a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -31,7 +31,7 @@ private static void getParameters() { } private static void checkLengthAndWidth(int length, int width) { - if (length == 0 || width == 0){ + if (length == 0 || width == 0) { throw new InputMismatchException(); } } diff --git a/src/main/java/homework_2/traffic_light/ExtraTrafficLight.java b/src/main/java/homework_2/traffic_light/ExtraTrafficLight.java index 02811eb4..f4e1f35d 100644 --- a/src/main/java/homework_2/traffic_light/ExtraTrafficLight.java +++ b/src/main/java/homework_2/traffic_light/ExtraTrafficLight.java @@ -3,7 +3,7 @@ import java.util.InputMismatchException; import java.util.Scanner; -import static homework_2.traffic_light.ColorSelector.*; +import static homework_2.traffic_light.ColorSelector.pickColor; public class ExtraTrafficLight { diff --git a/src/main/java/homework_2/traffic_light/TrafficLight.java b/src/main/java/homework_2/traffic_light/TrafficLight.java index 935012e1..c57c5423 100644 --- a/src/main/java/homework_2/traffic_light/TrafficLight.java +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -3,7 +3,7 @@ import java.util.InputMismatchException; import java.util.Scanner; -import static homework_2.traffic_light.ColorSelector.*; +import static homework_2.traffic_light.ColorSelector.pickColor; class TrafficLight { diff --git a/src/main/java/homework_4/custom_annotation/CustomAnnotation.java b/src/main/java/homework_4/custom_annotation/CustomAnnotation.java index 881c3ebd..8a8d1274 100644 --- a/src/main/java/homework_4/custom_annotation/CustomAnnotation.java +++ b/src/main/java/homework_4/custom_annotation/CustomAnnotation.java @@ -1,6 +1,9 @@ package homework_4.custom_annotation; -import java.lang.annotation.*; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) diff --git a/src/main/java/homework_4/singleton/Singleton.java b/src/main/java/homework_4/singleton/Singleton.java index dbfec216..ca7c33d1 100644 --- a/src/main/java/homework_4/singleton/Singleton.java +++ b/src/main/java/homework_4/singleton/Singleton.java @@ -9,8 +9,8 @@ private Singleton() { public static Singleton getInstance() { if (instance == null) { - synchronized (Singleton.class){ - if (instance == null){ + synchronized (Singleton.class) { + if (instance == null) { instance = new Singleton(); } } diff --git a/src/test/java/homework_2/traffic_light/ExtraTrafficLightTest.java b/src/test/java/homework_2/traffic_light/ExtraTrafficLightTest.java index 67d4702a..79926029 100644 --- a/src/test/java/homework_2/traffic_light/ExtraTrafficLightTest.java +++ b/src/test/java/homework_2/traffic_light/ExtraTrafficLightTest.java @@ -20,7 +20,6 @@ void givenValidArguments_whenRun_thenYellowOutput() { run(); assertEquals("The traffic light is" + ANSI_YELLOW + " Yellow" + ANSI_RESET + " now", getOutput()); - } @Test From 61b1bfa32f2c9dc44e77519a78d922f0208bd652 Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Sun, 8 Aug 2021 22:18:48 +0300 Subject: [PATCH 41/69] README edit --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index f001b4c2..a1b7864c 100644 --- a/README.md +++ b/README.md @@ -5,12 +5,12 @@ | Index | Solution | Short description | :---: | --- | --- | | HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_1) | The app that reads input arguments and prints them, until "error" argument | -| | [Traffic Light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_2/traffic_light) | The app that reads console and calculate current traffic light's color | +|-----| [Traffic Light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_2/traffic_light) | The app that reads console and calculate current traffic light's color | | HW2 | [Pyramid Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_2/pyramid_printer) | The app that reads console and prints a pyramid based on this | -| | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_2/random_chars_table) | The app that reads console for length, width and strategy and prints table based on this| +|-----| [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_2/random_chars_table) | The app that reads console for length, width and strategy and prints table based on this| | HW3 | [Immutable Class](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_3) | The class that give opportunity for create Immutable object| -| | [Custom Annotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_4/custom_annotation) | A form of syntactic metadata that can be added to Java source code| +|-----| [Custom Annotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_4/custom_annotation) | A form of syntactic metadata that can be added to Java source code| | HW4 | [Custom File Reader](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_4/custom_file_reader) | An app that provides 3 ways to read and edit a file| -| | [Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_4/singleton) | Creational design pattern, which ensures that only one object of its kind exists | +|-----| [Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_4/singleton) | Creational design pattern, which ensures that only one object of its kind exists | [CodingBat link](https://codingbat.com/done?user=slowly@live.ru&tag=8165639202) From 7da109c9a8ed6dd0887c39aac33187f84f59dc5f Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Thu, 12 Aug 2021 12:03:52 +0300 Subject: [PATCH 42/69] Change .txt input --- .../resources/custom_file_reader/custom.file.reader.txt | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/main/resources/custom_file_reader/custom.file.reader.txt b/src/main/resources/custom_file_reader/custom.file.reader.txt index c520610e..39206e66 100644 --- a/src/main/resources/custom_file_reader/custom.file.reader.txt +++ b/src/main/resources/custom_file_reader/custom.file.reader.txt @@ -1 +1,6 @@ -Мы часто повторяем, что о человеке судят по его делам, но забываем иногда, что слово тоже поступок. Речь человека — зеркало его самого. Всё фальшивое , лживое или вульгарное, как бы человек ни пытался скрыть это от других, вся пустота, черствость или грубость прорываются в его речи с такой же силой и очевидностью, с какой проявляются искренность и благородство, глубина и тонкость мыслей и чувств. То, о чём говорит человек, отражает его внутренний мир. \ No newline at end of file +Мы часто повторяем, что о человеке судят по его делам, но забываем иногда, что слово тоже поступок. +Речь человека — зеркало его самого. +Всё фальшивое , лживое или вульгарное, как бы человек ни пытался скрыть это от других, вся пустота, +черствость или грубость прорываются в его речи с такой же силой и очевидностью, +с какой проявляются искренность и благородство, глубина и тонкость мыслей и чувств. +То, о чём говорит человек, отражает его внутренний мир. \ No newline at end of file From f850b76e69d6b5e30cc1f02c04af3730883ac72f Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Fri, 13 Aug 2021 17:01:30 +0300 Subject: [PATCH 43/69] Refactoring --- .../custom_annotation/CustomAnnotation.java | 2 +- .../custom_annotation/HelloGenerator.java | 18 ++++++++++++------ .../custom_file_reader/CustomFileReader.java | 17 ++++++++++++----- 3 files changed, 25 insertions(+), 12 deletions(-) diff --git a/src/main/java/homework_4/custom_annotation/CustomAnnotation.java b/src/main/java/homework_4/custom_annotation/CustomAnnotation.java index 8a8d1274..34556edf 100644 --- a/src/main/java/homework_4/custom_annotation/CustomAnnotation.java +++ b/src/main/java/homework_4/custom_annotation/CustomAnnotation.java @@ -5,7 +5,7 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -@Target(ElementType.TYPE) +@Target({ElementType.LOCAL_VARIABLE, ElementType.FIELD, ElementType.CONSTRUCTOR}) @Retention(RetentionPolicy.RUNTIME) public @interface CustomAnnotation { String name() default "Ilia"; diff --git a/src/main/java/homework_4/custom_annotation/HelloGenerator.java b/src/main/java/homework_4/custom_annotation/HelloGenerator.java index 2b1dd16e..4b8df528 100644 --- a/src/main/java/homework_4/custom_annotation/HelloGenerator.java +++ b/src/main/java/homework_4/custom_annotation/HelloGenerator.java @@ -1,16 +1,22 @@ package homework_4.custom_annotation; -@CustomAnnotation + public class HelloGenerator { private String name; private int age; + @CustomAnnotation public HelloGenerator(String name, int age) { if (name == null || name.isEmpty()) { - CustomAnnotation customAnnotation = (CustomAnnotation) this.getClass().getDeclaredAnnotations()[0]; - this.name = customAnnotation.name(); - } else { - this.name = name; + String temp; + try { + CustomAnnotation customAnnotation = (CustomAnnotation) this.getClass().getConstructor().getDeclaredAnnotations()[0]; + // this.name = customAnnotation.name(); + temp = customAnnotation.name(); + } catch (NoSuchMethodException e) { + temp = "Aristarch"; + } + this.name = temp; } this.age = age; } @@ -24,7 +30,7 @@ public int getAge() { } public static void main(String[] args) { - HelloGenerator helloGenerator = new HelloGenerator("", 16); + HelloGenerator helloGenerator = new HelloGenerator(null, 16); System.out.println(helloGenerator); } diff --git a/src/main/java/homework_4/custom_file_reader/CustomFileReader.java b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java index f9ab0f3a..34adc794 100644 --- a/src/main/java/homework_4/custom_file_reader/CustomFileReader.java +++ b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java @@ -13,8 +13,11 @@ public class CustomFileReader { public void run1() { try (Scanner input = new Scanner(new File(GLOBAL_PATH))) { - String line = input.nextLine().replace(",", ""); - String output = line.replace(".", ""); + String output = ""; + while (input.hasNext()) { + output = output.concat(input.nextLine().replace(",", "") + "\n"); + } + output = output.replace(".", "").trim(); System.out.println(output); } catch (FileNotFoundException e) { System.out.println("File not found."); @@ -24,10 +27,14 @@ public void run1() { public void run2() { StringBuilder contents = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new FileReader(GLOBAL_PATH))) { - String file = ""; - while ((file = reader.readLine()) != null) { - System.out.println(contents.append(file.replaceAll("[,.]", ""))); + String check; + String space = ""; + while ((check = reader.readLine()) != null) { + contents.append(space); + contents.append(check.replaceAll("[,.]", "")); + space = "\n"; } + System.out.println(contents); } catch (IOException e) { System.out.println("File not found."); } From 795027aff926935a661950dca9412b08e1fe6d2e Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Fri, 13 Aug 2021 18:20:58 +0300 Subject: [PATCH 44/69] Add CustomAnnotation, edit README.md --- README.md | 12 +++--- .../custom_annotation/CustomAnnotation.java | 7 +--- .../custom_annotation/HelloGenerator.java | 40 +++++++++++++------ 3 files changed, 36 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index a1b7864c..1d2a146b 100644 --- a/README.md +++ b/README.md @@ -4,13 +4,13 @@ | Index | Solution | Short description | :---: | --- | --- | -| HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_1) | The app that reads input arguments and prints them, until "error" argument | -|-----| [Traffic Light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_2/traffic_light) | The app that reads console and calculate current traffic light's color | -| HW2 | [Pyramid Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_2/pyramid_printer) | The app that reads console and prints a pyramid based on this | -|-----| [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_2/random_chars_table) | The app that reads console for length, width and strategy and prints table based on this| +| HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_1)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_1/char_count) | The app that reads input arguments and prints them, until "error" argument | +|-----| [Traffic Light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_2/traffic_light)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_2/traffic_light) | The app that reads console and calculate current traffic light's color | +| HW2 | [Pyramid Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_2/pyramid_printer)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_2/pyramid_printer) | The app that reads console and prints a pyramid based on this | +|-----| [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_2/random_chars_table)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_2/random_chars_table) | The app that reads console for length, width and strategy and prints table based on this| | HW3 | [Immutable Class](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_3) | The class that give opportunity for create Immutable object| |-----| [Custom Annotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_4/custom_annotation) | A form of syntactic metadata that can be added to Java source code| -| HW4 | [Custom File Reader](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_4/custom_file_reader) | An app that provides 3 ways to read and edit a file| -|-----| [Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_4/singleton) | Creational design pattern, which ensures that only one object of its kind exists | +| HW4 | [Custom File Reader](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_4/custom_file_reader)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_4/custom_file_reader) | An app that provides 3 ways to read and edit a file| +|-----| [Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_4/singleton)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_4/singleton) | Creational design pattern, which ensures that only one object of its kind exists | [CodingBat link](https://codingbat.com/done?user=slowly@live.ru&tag=8165639202) diff --git a/src/main/java/homework_4/custom_annotation/CustomAnnotation.java b/src/main/java/homework_4/custom_annotation/CustomAnnotation.java index 34556edf..4ff3fcac 100644 --- a/src/main/java/homework_4/custom_annotation/CustomAnnotation.java +++ b/src/main/java/homework_4/custom_annotation/CustomAnnotation.java @@ -1,12 +1,9 @@ package homework_4.custom_annotation; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; +import java.lang.annotation.*; @Target({ElementType.LOCAL_VARIABLE, ElementType.FIELD, ElementType.CONSTRUCTOR}) @Retention(RetentionPolicy.RUNTIME) public @interface CustomAnnotation { - String name() default "Ilia"; + String name() default "Egor"; } diff --git a/src/main/java/homework_4/custom_annotation/HelloGenerator.java b/src/main/java/homework_4/custom_annotation/HelloGenerator.java index 4b8df528..1bc8d608 100644 --- a/src/main/java/homework_4/custom_annotation/HelloGenerator.java +++ b/src/main/java/homework_4/custom_annotation/HelloGenerator.java @@ -1,24 +1,38 @@ package homework_4.custom_annotation; - public class HelloGenerator { private String name; private int age; + @CustomAnnotation + public HelloGenerator() { + String temp; + try { + CustomAnnotation customAnnotation = (CustomAnnotation) this.getClass().getConstructor().getDeclaredAnnotations()[0]; + temp = customAnnotation.name(); + } catch (NoSuchMethodException e) { + temp = "Aristarch"; + this.age = 50; + } + this.name = temp; + this.age = 15; + } + @CustomAnnotation public HelloGenerator(String name, int age) { - if (name == null || name.isEmpty()) { - String temp; - try { - CustomAnnotation customAnnotation = (CustomAnnotation) this.getClass().getConstructor().getDeclaredAnnotations()[0]; - // this.name = customAnnotation.name(); - temp = customAnnotation.name(); - } catch (NoSuchMethodException e) { - temp = "Aristarch"; + try { + CustomAnnotation customAnnotation = (CustomAnnotation) this.getClass().getConstructor().getDeclaredAnnotations()[0]; + if (name == null) { + this.name = customAnnotation.name(); + } else { + this.name = name; } - this.name = temp; + //this.name = name; + this.age = age; + } catch (NoSuchMethodException e) { + name = "Aristarch"; + this.age = 5090; } - this.age = age; } public String getName() { @@ -30,8 +44,10 @@ public int getAge() { } public static void main(String[] args) { - HelloGenerator helloGenerator = new HelloGenerator(null, 16); + HelloGenerator helloGenerator = new HelloGenerator(); + HelloGenerator helloGenerator1 = new HelloGenerator(null, 5); System.out.println(helloGenerator); + System.out.println(helloGenerator1); } @Override From 7f805edda4b43d282eaa888e0a608a951348078a Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Mon, 16 Aug 2021 14:19:22 +0300 Subject: [PATCH 45/69] Added test for CustomAnnotation --- .../custom_annotation/HelloGenerator.java | 13 +++---- .../CustomAnnotationTest.java | 35 +++++++++++++++++++ .../CustomFileReaderTest.java | 3 ++ 3 files changed, 45 insertions(+), 6 deletions(-) create mode 100644 src/test/java/homework_4/custom_annotation/CustomAnnotationTest.java diff --git a/src/main/java/homework_4/custom_annotation/HelloGenerator.java b/src/main/java/homework_4/custom_annotation/HelloGenerator.java index 1bc8d608..c6e1ca9a 100644 --- a/src/main/java/homework_4/custom_annotation/HelloGenerator.java +++ b/src/main/java/homework_4/custom_annotation/HelloGenerator.java @@ -4,6 +4,13 @@ public class HelloGenerator { private String name; private int age; + public static void main(String args[]) { + HelloGenerator helloGenerator = new HelloGenerator(); + HelloGenerator helloGenerator1 = new HelloGenerator(null, 5); + System.out.println(helloGenerator); + System.out.println(helloGenerator1); + } + @CustomAnnotation public HelloGenerator() { String temp; @@ -43,12 +50,6 @@ public int getAge() { return age; } - public static void main(String[] args) { - HelloGenerator helloGenerator = new HelloGenerator(); - HelloGenerator helloGenerator1 = new HelloGenerator(null, 5); - System.out.println(helloGenerator); - System.out.println(helloGenerator1); - } @Override public String toString() { diff --git a/src/test/java/homework_4/custom_annotation/CustomAnnotationTest.java b/src/test/java/homework_4/custom_annotation/CustomAnnotationTest.java new file mode 100644 index 00000000..327d4ddb --- /dev/null +++ b/src/test/java/homework_4/custom_annotation/CustomAnnotationTest.java @@ -0,0 +1,35 @@ +package homework_4.custom_annotation; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class CustomAnnotationTest extends UnitBase { + HelloGenerator helloGenerator = new HelloGenerator(); + HelloGenerator helloGenerator1 = new HelloGenerator(null, 5); + + @Test + void givenEmptyNameField_whenCreateObject_thenTakeFromAnnotation(){ + String expected = "Egor"; + assertEquals(expected, helloGenerator.getName()); + } + + @Test + void givenEmptyAgeField_whenCreateObject_thenTakeFromAnnotation(){ + int expected = 15; + assertEquals(expected, helloGenerator.getAge()); + } + + @Test + void run3(){ + String expected = "Egor"; + assertEquals(expected, helloGenerator1.getName()); + } + + @Test + void run4(){ + int expected = 5; + assertEquals(expected, helloGenerator1.getAge()); + } +} diff --git a/src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java b/src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java index a2707f0d..d4896b29 100644 --- a/src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java +++ b/src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java @@ -19,6 +19,7 @@ void testRun1() { throw new IllegalArgumentException("Text contains symbol ',' or symbol '.'"); } assertEquals(expected, getOutput()); + printOut(); } @Test @@ -29,6 +30,7 @@ void testRun2() { throw new IllegalArgumentException("Text contains symbol ',' or symbol '.'"); } assertEquals(expected, getOutput()); + printOut(); } @Test @@ -39,5 +41,6 @@ void testRun3() { throw new IllegalArgumentException("Text contains symbol ',' or symbol '.'"); } assertEquals(expected, getOutput()); + printOut(); } } \ No newline at end of file From 6e7d1e519f9ff25beb92ea49db6e36cedf27c7b3 Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Mon, 16 Aug 2021 14:20:27 +0300 Subject: [PATCH 46/69] Edit README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1d2a146b..3379a1fb 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ | HW2 | [Pyramid Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_2/pyramid_printer)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_2/pyramid_printer) | The app that reads console and prints a pyramid based on this | |-----| [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_2/random_chars_table)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_2/random_chars_table) | The app that reads console for length, width and strategy and prints table based on this| | HW3 | [Immutable Class](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_3) | The class that give opportunity for create Immutable object| -|-----| [Custom Annotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_4/custom_annotation) | A form of syntactic metadata that can be added to Java source code| +|-----| [Custom Annotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_4/custom_annotation)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_4/custom_annotation) | A form of syntactic metadata that can be added to Java source code| | HW4 | [Custom File Reader](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_4/custom_file_reader)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_4/custom_file_reader) | An app that provides 3 ways to read and edit a file| |-----| [Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_4/singleton)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_4/singleton) | Creational design pattern, which ensures that only one object of its kind exists | From f0833d6b407a207c465bc9ee13946620277322fc Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Mon, 16 Aug 2021 14:22:00 +0300 Subject: [PATCH 47/69] Add couple of tests for CustomAnnotation --- .../custom_annotation/CustomAnnotationTest.java | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/test/java/homework_4/custom_annotation/CustomAnnotationTest.java b/src/test/java/homework_4/custom_annotation/CustomAnnotationTest.java index 327d4ddb..111024a9 100644 --- a/src/test/java/homework_4/custom_annotation/CustomAnnotationTest.java +++ b/src/test/java/homework_4/custom_annotation/CustomAnnotationTest.java @@ -8,6 +8,7 @@ public class CustomAnnotationTest extends UnitBase { HelloGenerator helloGenerator = new HelloGenerator(); HelloGenerator helloGenerator1 = new HelloGenerator(null, 5); + HelloGenerator helloGenerator2 = new HelloGenerator("Aleksei", 35); @Test void givenEmptyNameField_whenCreateObject_thenTakeFromAnnotation(){ @@ -32,4 +33,16 @@ void run4(){ int expected = 5; assertEquals(expected, helloGenerator1.getAge()); } + + @Test + void run5(){ + String expected = "Aleksei"; + assertEquals(expected, helloGenerator2.getName()); + } + + @Test + void run6(){ + int expected = 35; + assertEquals(expected, helloGenerator2.getAge()); + } } From d2a9b336ec6cd0fa94597ae38753c058c5cd3e5a Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Mon, 16 Aug 2021 22:31:40 +0300 Subject: [PATCH 48/69] Complete homework 5 --- .../custom_annotation/HelloGenerator.java | 21 +++++++++++++++++++ .../ExponentiationViaRecursion.java | 13 ++++++++++++ .../exponentiation_via_recursion/Main.java | 7 +++++++ 3 files changed, 41 insertions(+) create mode 100644 src/main/java/homework_5/exponentiation_via_recursion/ExponentiationViaRecursion.java create mode 100644 src/main/java/homework_5/exponentiation_via_recursion/Main.java diff --git a/src/main/java/homework_4/custom_annotation/HelloGenerator.java b/src/main/java/homework_4/custom_annotation/HelloGenerator.java index c6e1ca9a..5acf0db5 100644 --- a/src/main/java/homework_4/custom_annotation/HelloGenerator.java +++ b/src/main/java/homework_4/custom_annotation/HelloGenerator.java @@ -1,5 +1,8 @@ package homework_4.custom_annotation; +import java.util.ArrayList; +import java.util.Arrays; + public class HelloGenerator { private String name; private int age; @@ -9,8 +12,23 @@ public static void main(String args[]) { HelloGenerator helloGenerator1 = new HelloGenerator(null, 5); System.out.println(helloGenerator); System.out.println(helloGenerator1); + seriesUp(3); } + public static int[] seriesUp(int n) { + int[] res = new int[n * (n + 1) / 2]; + int index = 0; + + for(int i = 1; i <= n; i++) { + for(int j = 0; j < i; j++) { + res[index + j] = j + 1; + } + index += i; + } + + System.out.println(Arrays.toString(res)); + return res; + } @CustomAnnotation public HelloGenerator() { String temp; @@ -51,8 +69,11 @@ public int getAge() { } + + @Override public String toString() { return "Hello " + name + "!" + " You are " + age + " year old!"; } + } diff --git a/src/main/java/homework_5/exponentiation_via_recursion/ExponentiationViaRecursion.java b/src/main/java/homework_5/exponentiation_via_recursion/ExponentiationViaRecursion.java new file mode 100644 index 00000000..89bff7bb --- /dev/null +++ b/src/main/java/homework_5/exponentiation_via_recursion/ExponentiationViaRecursion.java @@ -0,0 +1,13 @@ +package homework_5.exponentiation_via_recursion; + +public class ExponentiationViaRecursion { + public long run(int number, int degree) { + if (degree == 0) { + return 1; + } else if (number == 0) { + return 0; + } else { + return number * run(number, degree - 1); + } + } +} \ No newline at end of file diff --git a/src/main/java/homework_5/exponentiation_via_recursion/Main.java b/src/main/java/homework_5/exponentiation_via_recursion/Main.java new file mode 100644 index 00000000..ae09ab9f --- /dev/null +++ b/src/main/java/homework_5/exponentiation_via_recursion/Main.java @@ -0,0 +1,7 @@ +package homework_5.exponentiation_via_recursion; + +public class Main { + public static void main(String[] args) { + System.out.println(new ExponentiationViaRecursion().run(5, 5)); + } +} From 631db282788ebea87283a40dabb8aa3747c7cef8 Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Mon, 16 Aug 2021 22:58:23 +0300 Subject: [PATCH 49/69] HW5 refactoring and add tests --- .../ExponentiationViaRecursion.java | 9 ++--- .../exponentiation_via_recursion/Main.java | 2 +- .../ExponentiationViaRecursionTest.java | 34 +++++++++++++++++++ 3 files changed, 38 insertions(+), 7 deletions(-) create mode 100644 src/test/java/homework_5/exponentiation_via_recursion/ExponentiationViaRecursionTest.java diff --git a/src/main/java/homework_5/exponentiation_via_recursion/ExponentiationViaRecursion.java b/src/main/java/homework_5/exponentiation_via_recursion/ExponentiationViaRecursion.java index 89bff7bb..21f3224f 100644 --- a/src/main/java/homework_5/exponentiation_via_recursion/ExponentiationViaRecursion.java +++ b/src/main/java/homework_5/exponentiation_via_recursion/ExponentiationViaRecursion.java @@ -1,13 +1,10 @@ package homework_5.exponentiation_via_recursion; public class ExponentiationViaRecursion { - public long run(int number, int degree) { - if (degree == 0) { - return 1; - } else if (number == 0) { - return 0; - } else { + public static double run(double number, int degree) { + if (degree != 0){ return number * run(number, degree - 1); } + return 1; } } \ No newline at end of file diff --git a/src/main/java/homework_5/exponentiation_via_recursion/Main.java b/src/main/java/homework_5/exponentiation_via_recursion/Main.java index ae09ab9f..17536892 100644 --- a/src/main/java/homework_5/exponentiation_via_recursion/Main.java +++ b/src/main/java/homework_5/exponentiation_via_recursion/Main.java @@ -2,6 +2,6 @@ public class Main { public static void main(String[] args) { - System.out.println(new ExponentiationViaRecursion().run(5, 5)); + System.out.println(new ExponentiationViaRecursion().run(5.4, 5)); } } diff --git a/src/test/java/homework_5/exponentiation_via_recursion/ExponentiationViaRecursionTest.java b/src/test/java/homework_5/exponentiation_via_recursion/ExponentiationViaRecursionTest.java new file mode 100644 index 00000000..43bb410d --- /dev/null +++ b/src/test/java/homework_5/exponentiation_via_recursion/ExponentiationViaRecursionTest.java @@ -0,0 +1,34 @@ +package homework_5.exponentiation_via_recursion; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class ExponentiationViaRecursionTest { + + @Test + void given5and5_whenExponentiation_then3125() { + double expected = 3125; + assertEquals(expected, ExponentiationViaRecursion.run(5, 5)); + } + + @Test + void given0and5_whenExponentiation_then0() { + double expected = 0; + assertEquals(expected, ExponentiationViaRecursion.run(0, 5)); + } + + @Test + void given5and0_whenExponentiation_then3125() { + double expected = 1; + assertEquals(expected, ExponentiationViaRecursion.run(5, 0)); + } + + @Test + void given0and0_whenExponentiation_then1() { + double expected = 1; + assertEquals(expected, ExponentiationViaRecursion.run(0, 0)); + } + + +} \ No newline at end of file From 69e5170686b222b5a28cb7f68110dd0fce4c9099 Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Mon, 16 Aug 2021 23:01:44 +0300 Subject: [PATCH 50/69] Refactoring --- README.md | 1 + .../ExpWRec.java} | 4 ++-- src/main/java/homework_5/exp_w_rec/Main.java | 7 +++++++ .../exponentiation_via_recursion/Main.java | 7 ------- .../ExpWRecTest.java} | 12 ++++++------ 5 files changed, 16 insertions(+), 15 deletions(-) rename src/main/java/homework_5/{exponentiation_via_recursion/ExponentiationViaRecursion.java => exp_w_rec/ExpWRec.java} (65%) create mode 100644 src/main/java/homework_5/exp_w_rec/Main.java delete mode 100644 src/main/java/homework_5/exponentiation_via_recursion/Main.java rename src/test/java/homework_5/{exponentiation_via_recursion/ExponentiationViaRecursionTest.java => exp_w_rec/ExpWRecTest.java} (56%) diff --git a/README.md b/README.md index 3379a1fb..b107ec36 100644 --- a/README.md +++ b/README.md @@ -12,5 +12,6 @@ |-----| [Custom Annotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_4/custom_annotation)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_4/custom_annotation) | A form of syntactic metadata that can be added to Java source code| | HW4 | [Custom File Reader](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_4/custom_file_reader)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_4/custom_file_reader) | An app that provides 3 ways to read and edit a file| |-----| [Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_4/singleton)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_4/singleton) | Creational design pattern, which ensures that only one object of its kind exists | +| HW5 | [ExpWRec](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_4/custom_file_reader)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_4/custom_file_reader) | An app that provides 3 ways to read and edit a file| [CodingBat link](https://codingbat.com/done?user=slowly@live.ru&tag=8165639202) diff --git a/src/main/java/homework_5/exponentiation_via_recursion/ExponentiationViaRecursion.java b/src/main/java/homework_5/exp_w_rec/ExpWRec.java similarity index 65% rename from src/main/java/homework_5/exponentiation_via_recursion/ExponentiationViaRecursion.java rename to src/main/java/homework_5/exp_w_rec/ExpWRec.java index 21f3224f..4929b6aa 100644 --- a/src/main/java/homework_5/exponentiation_via_recursion/ExponentiationViaRecursion.java +++ b/src/main/java/homework_5/exp_w_rec/ExpWRec.java @@ -1,6 +1,6 @@ -package homework_5.exponentiation_via_recursion; +package homework_5.exp_w_rec; -public class ExponentiationViaRecursion { +public class ExpWRec { public static double run(double number, int degree) { if (degree != 0){ return number * run(number, degree - 1); diff --git a/src/main/java/homework_5/exp_w_rec/Main.java b/src/main/java/homework_5/exp_w_rec/Main.java new file mode 100644 index 00000000..dbc8c7f6 --- /dev/null +++ b/src/main/java/homework_5/exp_w_rec/Main.java @@ -0,0 +1,7 @@ +package homework_5.exp_w_rec; + +public class Main { + public static void main(String[] args) { + System.out.println(new ExpWRec().run(5.4, 5)); + } +} diff --git a/src/main/java/homework_5/exponentiation_via_recursion/Main.java b/src/main/java/homework_5/exponentiation_via_recursion/Main.java deleted file mode 100644 index 17536892..00000000 --- a/src/main/java/homework_5/exponentiation_via_recursion/Main.java +++ /dev/null @@ -1,7 +0,0 @@ -package homework_5.exponentiation_via_recursion; - -public class Main { - public static void main(String[] args) { - System.out.println(new ExponentiationViaRecursion().run(5.4, 5)); - } -} diff --git a/src/test/java/homework_5/exponentiation_via_recursion/ExponentiationViaRecursionTest.java b/src/test/java/homework_5/exp_w_rec/ExpWRecTest.java similarity index 56% rename from src/test/java/homework_5/exponentiation_via_recursion/ExponentiationViaRecursionTest.java rename to src/test/java/homework_5/exp_w_rec/ExpWRecTest.java index 43bb410d..82d48738 100644 --- a/src/test/java/homework_5/exponentiation_via_recursion/ExponentiationViaRecursionTest.java +++ b/src/test/java/homework_5/exp_w_rec/ExpWRecTest.java @@ -1,33 +1,33 @@ -package homework_5.exponentiation_via_recursion; +package homework_5.exp_w_rec; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; -class ExponentiationViaRecursionTest { +class ExpWRecTest { @Test void given5and5_whenExponentiation_then3125() { double expected = 3125; - assertEquals(expected, ExponentiationViaRecursion.run(5, 5)); + assertEquals(expected, ExpWRec.run(5, 5)); } @Test void given0and5_whenExponentiation_then0() { double expected = 0; - assertEquals(expected, ExponentiationViaRecursion.run(0, 5)); + assertEquals(expected, ExpWRec.run(0, 5)); } @Test void given5and0_whenExponentiation_then3125() { double expected = 1; - assertEquals(expected, ExponentiationViaRecursion.run(5, 0)); + assertEquals(expected, ExpWRec.run(5, 0)); } @Test void given0and0_whenExponentiation_then1() { double expected = 1; - assertEquals(expected, ExponentiationViaRecursion.run(0, 0)); + assertEquals(expected, ExpWRec.run(0, 0)); } From e7a84a0164c0df50ba42a5deab0e84f09f33e42b Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Mon, 16 Aug 2021 23:04:32 +0300 Subject: [PATCH 51/69] Edit README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index b107ec36..652ddc95 100644 --- a/README.md +++ b/README.md @@ -10,8 +10,8 @@ |-----| [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_2/random_chars_table)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_2/random_chars_table) | The app that reads console for length, width and strategy and prints table based on this| | HW3 | [Immutable Class](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_3) | The class that give opportunity for create Immutable object| |-----| [Custom Annotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_4/custom_annotation)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_4/custom_annotation) | A form of syntactic metadata that can be added to Java source code| -| HW4 | [Custom File Reader](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_4/custom_file_reader)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_4/custom_file_reader) | An app that provides 3 ways to read and edit a file| +| HW4 | [Custom File Reader](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_4/custom_file_reader)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_4/custom_file_reader) | The app that provides 3 ways to read and edit a file| |-----| [Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_4/singleton)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_4/singleton) | Creational design pattern, which ensures that only one object of its kind exists | -| HW5 | [ExpWRec](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_4/custom_file_reader)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_4/custom_file_reader) | An app that provides 3 ways to read and edit a file| +| HW5 | [ExpWRec](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_5/exp_w_rec)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_5/exp_w_rec) | The app that raises a number to a power | [CodingBat link](https://codingbat.com/done?user=slowly@live.ru&tag=8165639202) From 80ad1a2447e1b728f7d634d60704c665609b733d Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Thu, 19 Aug 2021 00:04:32 +0300 Subject: [PATCH 52/69] Add one case for unit-test --- src/test/java/homework_5/exp_w_rec/ExpWRecTest.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/test/java/homework_5/exp_w_rec/ExpWRecTest.java b/src/test/java/homework_5/exp_w_rec/ExpWRecTest.java index 82d48738..f7575692 100644 --- a/src/test/java/homework_5/exp_w_rec/ExpWRecTest.java +++ b/src/test/java/homework_5/exp_w_rec/ExpWRecTest.java @@ -30,5 +30,9 @@ void given0and0_whenExponentiation_then1() { assertEquals(expected, ExpWRec.run(0, 0)); } - + @Test + void given5divide4and4_whenExponentiation_then1() { + double expected = Math.pow(5.4, 4); + assertEquals(expected, ExpWRec.run(5.4, 4)); + } } \ No newline at end of file From 1d4b053f9806cdc8153303858838d14593aa1249 Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Mon, 23 Aug 2021 14:53:33 +0300 Subject: [PATCH 53/69] Major refactoring, add tests, complete CustomRegexMatcher --- .../CustomRegexMatcher.java | 29 ++++++++++ .../homework_5/custom_regex_matcher/Main.java | 7 +++ .../java/homework_5/exp_w_rec/ExpWRec.java | 10 ---- src/main/java/homework_5/exp_w_rec/Main.java | 7 --- .../java/homework_5/power_of_number/Main.java | 7 +++ .../power_of_number/PowerOfNumber.java | 49 +++++++++++++++++ .../CustomRegexMatcherTest.java | 40 ++++++++++++++ .../homework_5/exp_w_rec/ExpWRecTest.java | 38 ------------- .../power_of_number/PowerOfNumberTest.java | 54 +++++++++++++++++++ 9 files changed, 186 insertions(+), 55 deletions(-) create mode 100644 src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java create mode 100644 src/main/java/homework_5/custom_regex_matcher/Main.java delete mode 100644 src/main/java/homework_5/exp_w_rec/ExpWRec.java delete mode 100644 src/main/java/homework_5/exp_w_rec/Main.java create mode 100644 src/main/java/homework_5/power_of_number/Main.java create mode 100644 src/main/java/homework_5/power_of_number/PowerOfNumber.java create mode 100644 src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java delete mode 100644 src/test/java/homework_5/exp_w_rec/ExpWRecTest.java create mode 100644 src/test/java/homework_5/power_of_number/PowerOfNumberTest.java diff --git a/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java b/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java new file mode 100644 index 00000000..4bcdda82 --- /dev/null +++ b/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java @@ -0,0 +1,29 @@ +package homework_5.custom_regex_matcher; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class CustomRegexMatcher { + + private static final String CHECK_USERNAME = "^[a-z0-9.-]{5,10}$"; + + public static void run() { + System.out.println(checkRegex()); + } + + private static boolean checkRegex() { + return getInput().matches(CHECK_USERNAME); + } + + private static String getInput() { + String input = ""; + try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { + System.out.println("Enter your username, it must only contain letters, numbers and dot, minimum length 5, maximum length 10(inclusive):"); + input = reader.readLine(); + } catch (IOException e) { + e.printStackTrace(); + } + return input; + } +} \ No newline at end of file diff --git a/src/main/java/homework_5/custom_regex_matcher/Main.java b/src/main/java/homework_5/custom_regex_matcher/Main.java new file mode 100644 index 00000000..0b612ebf --- /dev/null +++ b/src/main/java/homework_5/custom_regex_matcher/Main.java @@ -0,0 +1,7 @@ +package homework_5.custom_regex_matcher; + +public class Main { + public static void main(String[] args) { + CustomRegexMatcher.run(); + } +} diff --git a/src/main/java/homework_5/exp_w_rec/ExpWRec.java b/src/main/java/homework_5/exp_w_rec/ExpWRec.java deleted file mode 100644 index 4929b6aa..00000000 --- a/src/main/java/homework_5/exp_w_rec/ExpWRec.java +++ /dev/null @@ -1,10 +0,0 @@ -package homework_5.exp_w_rec; - -public class ExpWRec { - public static double run(double number, int degree) { - if (degree != 0){ - return number * run(number, degree - 1); - } - return 1; - } -} \ No newline at end of file diff --git a/src/main/java/homework_5/exp_w_rec/Main.java b/src/main/java/homework_5/exp_w_rec/Main.java deleted file mode 100644 index dbc8c7f6..00000000 --- a/src/main/java/homework_5/exp_w_rec/Main.java +++ /dev/null @@ -1,7 +0,0 @@ -package homework_5.exp_w_rec; - -public class Main { - public static void main(String[] args) { - System.out.println(new ExpWRec().run(5.4, 5)); - } -} diff --git a/src/main/java/homework_5/power_of_number/Main.java b/src/main/java/homework_5/power_of_number/Main.java new file mode 100644 index 00000000..8f1c5b6d --- /dev/null +++ b/src/main/java/homework_5/power_of_number/Main.java @@ -0,0 +1,7 @@ +package homework_5.power_of_number; + +public class Main { + public static void main(String[] args) { + PowerOfNumber.run(); + } +} diff --git a/src/main/java/homework_5/power_of_number/PowerOfNumber.java b/src/main/java/homework_5/power_of_number/PowerOfNumber.java new file mode 100644 index 00000000..74cad4a0 --- /dev/null +++ b/src/main/java/homework_5/power_of_number/PowerOfNumber.java @@ -0,0 +1,49 @@ +package homework_5.power_of_number; + +import java.util.InputMismatchException; +import java.util.Scanner; + +public class PowerOfNumber { + + public static void run() { + int[] input = getInput(); + if (input.length != 2) { + System.out.println("Only 2 non-negative integers are allowed"); + } else { + System.out.println(power(input[0], input[1])); + } + } + + private static int[] getInput() { + try { + Scanner scanner = new Scanner(System.in); + int[] input = new int[2]; + String[] string = scanner.nextLine().split(" "); + input[0] = Integer.parseInt(string[0]); + input[1] = Integer.parseInt(string[1]); + + if (string.length != 2) { + throw new InputMismatchException(); + } + + if (isValid(input[0]) && isValid(input[1])) { + return input; + } else { + throw new InputMismatchException(); + } + } catch (NumberFormatException | InputMismatchException | ArrayIndexOutOfBoundsException e) { + return new int[0]; + } + } + + private static int power(int number, int divide) { + if (divide != 0) { + return number * power(number, divide - 1); + } + return 1; + } + + private static boolean isValid(int number) { + return number >= 0; + } +} diff --git a/src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java b/src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java new file mode 100644 index 00000000..82925da9 --- /dev/null +++ b/src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java @@ -0,0 +1,40 @@ +package homework_5.custom_regex_matcher; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class CustomRegexMatcherTest extends UnitBase { + + @Test + void givenCorrectUserName_whenCheckRegex_thenTrue() { + String expected = "true"; + setInput("nuker228"); + CustomRegexMatcher.run(); + removeFromOutput("Enter your username, it must only contain letters, numbers and dot, minimum length 5, maximum length 10(inclusive):"); + assertEquals(expected, getOutput()); + printOut(); + } + + @Test + void givenCorrectUserNameWithDot_whenCheckRegex_thenTrue() { + String expected = "true"; + setInput("nuker.228"); + CustomRegexMatcher.run(); + removeFromOutput("Enter your username, it must only contain letters, numbers and dot, minimum length 5, maximum length 10(inclusive):"); + assertEquals(expected, getOutput()); + printOut(); + } + + @Test + void givenIncorrectUserName_whenCheckRegex_thenFalse() { + String expected = "false"; + setInput("nuker@228"); + CustomRegexMatcher.run(); + removeFromOutput("Enter your username, it must only contain letters, numbers and dot, minimum length 5, maximum length 10(inclusive):"); + assertEquals(expected, getOutput()); + printOut(); + } + +} \ No newline at end of file diff --git a/src/test/java/homework_5/exp_w_rec/ExpWRecTest.java b/src/test/java/homework_5/exp_w_rec/ExpWRecTest.java deleted file mode 100644 index f7575692..00000000 --- a/src/test/java/homework_5/exp_w_rec/ExpWRecTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package homework_5.exp_w_rec; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.*; - -class ExpWRecTest { - - @Test - void given5and5_whenExponentiation_then3125() { - double expected = 3125; - assertEquals(expected, ExpWRec.run(5, 5)); - } - - @Test - void given0and5_whenExponentiation_then0() { - double expected = 0; - assertEquals(expected, ExpWRec.run(0, 5)); - } - - @Test - void given5and0_whenExponentiation_then3125() { - double expected = 1; - assertEquals(expected, ExpWRec.run(5, 0)); - } - - @Test - void given0and0_whenExponentiation_then1() { - double expected = 1; - assertEquals(expected, ExpWRec.run(0, 0)); - } - - @Test - void given5divide4and4_whenExponentiation_then1() { - double expected = Math.pow(5.4, 4); - assertEquals(expected, ExpWRec.run(5.4, 4)); - } -} \ No newline at end of file diff --git a/src/test/java/homework_5/power_of_number/PowerOfNumberTest.java b/src/test/java/homework_5/power_of_number/PowerOfNumberTest.java new file mode 100644 index 00000000..8ed81475 --- /dev/null +++ b/src/test/java/homework_5/power_of_number/PowerOfNumberTest.java @@ -0,0 +1,54 @@ +package homework_5.power_of_number; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class PowerOfNumberTest extends UnitBase { + + @Test + void given5and2_whenPoW_then25() { + String expected = String.valueOf((int) Math.pow(5, 2)); + setInput("5 2"); + PowerOfNumber.run(); + assertEquals(expected, getOutput()); + printOut(); + } + + @Test + void given0and5_whenPoW_then25() { + String expected = String.valueOf((int) Math.pow(0, 5)); + setInput("0 5"); + PowerOfNumber.run(); + assertEquals(expected, getOutput()); + printOut(); + } + + @Test + void given3and0_whenPoW_then1() { + String expected = String.valueOf((int) Math.pow(3, 0)); + setInput("3 0"); + PowerOfNumber.run(); + assertEquals(expected, getOutput()); + printOut(); + } + + @Test + void givenWrongInput_whenPoW_thenPrintError() { + String expected = "Only 2 non-negative integers are allowed"; + setInput("asd fdf"); + PowerOfNumber.run(); + assertEquals(expected, getOutput()); + printOut(); + } + + @Test + void givenOnlyOneArgument_whenPoW_thenPrintError() { + String expected = "Only 2 non-negative integers are allowed"; + setInput("5"); + PowerOfNumber.run(); + assertEquals(expected, getOutput()); + printOut(); + } +} \ No newline at end of file From 6a354d9860b85e7f8593c51be54af9605242508a Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Mon, 23 Aug 2021 15:01:01 +0300 Subject: [PATCH 54/69] Edit README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 652ddc95..12370bc1 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ |-----| [Custom Annotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_4/custom_annotation)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_4/custom_annotation) | A form of syntactic metadata that can be added to Java source code| | HW4 | [Custom File Reader](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_4/custom_file_reader)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_4/custom_file_reader) | The app that provides 3 ways to read and edit a file| |-----| [Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_4/singleton)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_4/singleton) | Creational design pattern, which ensures that only one object of its kind exists | -| HW5 | [ExpWRec](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_5/exp_w_rec)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_5/exp_w_rec) | The app that raises a number to a power | +| HW5 | [PowerOfNumber](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_5/power_of_number)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_5/power_of_number) | The app that raises a number to a power | +|-----| [CustomRegexMatcher](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_5/custom_regex_matcher)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_5/custom_regex_matcher) | The app that check input string by hardcoded regex and return boolean answer | [CodingBat link](https://codingbat.com/done?user=slowly@live.ru&tag=8165639202) From f15163d25b39874dd0a900cf13d9a50633564caf Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Mon, 30 Aug 2021 21:21:48 +0300 Subject: [PATCH 55/69] Complete Homework 6 --- .../map_problem_generator/Main.java | 8 +++++ .../MapProblemsCollisionGenerator.java | 26 ++++++++++++++ .../MapProblemsGenerator.java | 34 +++++++++++++++++++ .../MapProblemsMutableGenerator.java | 31 +++++++++++++++++ 4 files changed, 99 insertions(+) create mode 100644 src/main/java/homework_6/map_problem_generator/Main.java create mode 100644 src/main/java/homework_6/map_problem_generator/MapProblemsCollisionGenerator.java create mode 100644 src/main/java/homework_6/map_problem_generator/MapProblemsGenerator.java create mode 100644 src/main/java/homework_6/map_problem_generator/MapProblemsMutableGenerator.java diff --git a/src/main/java/homework_6/map_problem_generator/Main.java b/src/main/java/homework_6/map_problem_generator/Main.java new file mode 100644 index 00000000..a859f31e --- /dev/null +++ b/src/main/java/homework_6/map_problem_generator/Main.java @@ -0,0 +1,8 @@ +package homework_6.map_problem_generator; + +public class Main { + public static void main(String[] args) { + new MapProblemsGenerator().makeCollision(); + new MapProblemsGenerator().makeUnreachedObject(); + } +} diff --git a/src/main/java/homework_6/map_problem_generator/MapProblemsCollisionGenerator.java b/src/main/java/homework_6/map_problem_generator/MapProblemsCollisionGenerator.java new file mode 100644 index 00000000..ec43c8a6 --- /dev/null +++ b/src/main/java/homework_6/map_problem_generator/MapProblemsCollisionGenerator.java @@ -0,0 +1,26 @@ +package homework_6.map_problem_generator; + +import java.util.Objects; + +class MapProblemsCollisionGenerator { + + private final int age; + + MapProblemsCollisionGenerator(int age) { + this.age = age; + } + + @Override + public int hashCode() { + return Objects.hashCode(0); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) return true; + if (obj == null || getClass() != obj.getClass()) return false; + MapProblemsCollisionGenerator newObj = (MapProblemsCollisionGenerator) obj; + return age == newObj.age; + } + +} diff --git a/src/main/java/homework_6/map_problem_generator/MapProblemsGenerator.java b/src/main/java/homework_6/map_problem_generator/MapProblemsGenerator.java new file mode 100644 index 00000000..282d8fd5 --- /dev/null +++ b/src/main/java/homework_6/map_problem_generator/MapProblemsGenerator.java @@ -0,0 +1,34 @@ +package homework_6.map_problem_generator; + +import java.util.HashMap; + +public class MapProblemsGenerator { + + public void makeCollision() { + + HashMap mapForCollisions = new HashMap<>(); + + MapProblemsCollisionGenerator obj1 = new MapProblemsCollisionGenerator(10); + MapProblemsCollisionGenerator obj2 = new MapProblemsCollisionGenerator(15); + + mapForCollisions.put(obj1, "field"); + mapForCollisions.put(obj2, "anotherField"); + System.out.println("mapForCollisions = " + mapForCollisions); + System.out.println(obj1.hashCode() == obj2.hashCode()); + } + + public void makeUnreachedObject() { + + HashMap mapForUnreachableObjects = new HashMap<>(); + + MapProblemsMutableGenerator obj1 = new MapProblemsMutableGenerator(125); + MapProblemsMutableGenerator obj2 = new MapProblemsMutableGenerator(126); + + mapForUnreachableObjects.put(obj1, "field"); + mapForUnreachableObjects.put(obj2, "anotherField"); + System.out.println("mapForUnreachableObjects = " + mapForUnreachableObjects); + System.out.println("mapForUnreachableObjects.get(obj1) = " + mapForUnreachableObjects.get(obj1)); + + } +} + diff --git a/src/main/java/homework_6/map_problem_generator/MapProblemsMutableGenerator.java b/src/main/java/homework_6/map_problem_generator/MapProblemsMutableGenerator.java new file mode 100644 index 00000000..c0bbf288 --- /dev/null +++ b/src/main/java/homework_6/map_problem_generator/MapProblemsMutableGenerator.java @@ -0,0 +1,31 @@ +package homework_6.map_problem_generator; + +public class MapProblemsMutableGenerator { + + private int weight; + + public MapProblemsMutableGenerator(int weight) { + this.weight = weight; + } + + public int getWeight() { + return weight; + } + + public void setWeight(int weight) { + this.weight = weight; + } + + @Override + public int hashCode() { + return (int)(Math.random() * 50 + 1); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) return true; + if (obj == null || getClass() != obj.getClass()) return false; + MapProblemsMutableGenerator newObj = (MapProblemsMutableGenerator) obj; + return weight == newObj.weight; + } +} From bc43c5b9b2e34ec186fb5685d5b68193823cd820 Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Mon, 30 Aug 2021 21:27:15 +0300 Subject: [PATCH 56/69] Edit README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 12370bc1..7d610379 100644 --- a/README.md +++ b/README.md @@ -14,5 +14,6 @@ |-----| [Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_4/singleton)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_4/singleton) | Creational design pattern, which ensures that only one object of its kind exists | | HW5 | [PowerOfNumber](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_5/power_of_number)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_5/power_of_number) | The app that raises a number to a power | |-----| [CustomRegexMatcher](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_5/custom_regex_matcher)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_5/custom_regex_matcher) | The app that check input string by hardcoded regex and return boolean answer | +| HW6 | [MapProblemsGenerator](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_6/map_problem_generator)|Two classes that allow you to check the work of the collision and create a situation where it is impossible to get the object just put| [CodingBat link](https://codingbat.com/done?user=slowly@live.ru&tag=8165639202) From 1eac62d8112eb6b9cc0f1d97dfedd2d040d62f96 Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Thu, 2 Sep 2021 15:47:55 +0300 Subject: [PATCH 57/69] Major refactoring --- .../{Utils.java => Constants.java} | 2 +- .../pyramid_printer/ExtraPyramidPrinter.java | 4 +-- .../pyramid_printer/PyramidPrinter.java | 4 +-- .../random_chars_table/RandomCharsTable.java | 35 +++++++++++-------- .../traffic_light/ExtraTrafficLight.java | 2 +- .../traffic_light/TrafficLight.java | 31 +++------------- .../custom_annotation/HelloGenerator.java | 9 ++--- .../CustomRegexMatcher.java | 2 +- .../homework_5/custom_regex_matcher/Main.java | 2 +- .../java/homework_5/power_of_number/Main.java | 2 +- .../power_of_number/PowerOfNumber.java | 2 +- src/main/java/sea_battle/Main.java | 4 +++ .../CustomRegexMatcherTest.java | 6 ++-- .../power_of_number/PowerOfNumberTest.java | 10 +++--- 14 files changed, 50 insertions(+), 65 deletions(-) rename src/main/java/homework_2/pyramid_printer/{Utils.java => Constants.java} (89%) create mode 100644 src/main/java/sea_battle/Main.java diff --git a/src/main/java/homework_2/pyramid_printer/Utils.java b/src/main/java/homework_2/pyramid_printer/Constants.java similarity index 89% rename from src/main/java/homework_2/pyramid_printer/Utils.java rename to src/main/java/homework_2/pyramid_printer/Constants.java index 12b877ec..a6108434 100644 --- a/src/main/java/homework_2/pyramid_printer/Utils.java +++ b/src/main/java/homework_2/pyramid_printer/Constants.java @@ -1,6 +1,6 @@ package homework_2.pyramid_printer; -final class Utils { +final class Constants { static final String INPUT_MISMATCH = "Only 1 non-negative integer is allowed."; static final String INPUT = "Enter a valid INT value for create a pyramid:"; } diff --git a/src/main/java/homework_2/pyramid_printer/ExtraPyramidPrinter.java b/src/main/java/homework_2/pyramid_printer/ExtraPyramidPrinter.java index 3f6bfa0e..674ea910 100644 --- a/src/main/java/homework_2/pyramid_printer/ExtraPyramidPrinter.java +++ b/src/main/java/homework_2/pyramid_printer/ExtraPyramidPrinter.java @@ -3,8 +3,8 @@ import java.util.InputMismatchException; import java.util.Scanner; -import static homework_2.pyramid_printer.Utils.INPUT; -import static homework_2.pyramid_printer.Utils.INPUT_MISMATCH; +import static homework_2.pyramid_printer.Constants.INPUT; +import static homework_2.pyramid_printer.Constants.INPUT_MISMATCH; public class ExtraPyramidPrinter { diff --git a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java index 117ce5e2..fd249c8f 100644 --- a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -3,8 +3,8 @@ import java.util.InputMismatchException; import java.util.Scanner; -import static homework_2.pyramid_printer.Utils.INPUT; -import static homework_2.pyramid_printer.Utils.INPUT_MISMATCH; +import static homework_2.pyramid_printer.Constants.INPUT; +import static homework_2.pyramid_printer.Constants.INPUT_MISMATCH; public class PyramidPrinter { diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java index 482b6e77..925bc9c4 100644 --- a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -1,5 +1,7 @@ package homework_2.random_chars_table; +import lombok.experimental.SuperBuilder; + import java.util.InputMismatchException; import java.util.Random; import java.util.Scanner; @@ -9,23 +11,22 @@ public class RandomCharsTable { private static int length; private static int width; - public static void run() { + public void run() { System.out.println("Enter valid table length, width and strategy(even or odd) in format \"length width strategy\" "); - getParameters(); + getInput(); } - private static void getParameters() { + private static void getInput() { try (Scanner scanner = new Scanner(System.in)) { - length = scanner.nextInt(); - width = scanner.nextInt(); - String strategy = scanner.next(); + String[] input= scanner.nextLine().split(" "); + length = Integer.parseInt(input[0]); + width = Integer.parseInt(input[1]); + String strategy = input[2]; checkLengthAndWidth(length, width); checkStrategyValid(strategy); char[][] table = new char[length][width]; fillAndPrintTable(strategy, table); - } catch (NegativeArraySizeException e) { - System.out.println("Passed parameters should match the format [positive integer] [positive integer] [even|odd]"); - } catch (InputMismatchException e) { + } catch (NegativeArraySizeException | InputMismatchException | NumberFormatException e) { System.out.println("Passed parameters should match the format [positive integer] [positive integer] [even|odd]"); } } @@ -38,12 +39,12 @@ private static void checkLengthAndWidth(int length, int width) { private static void fillAndPrintTable(String strategy, char[][] table) { Random random = new Random(); - for (int i = 0; i < length; i++) { for (int j = 0; j < width; j++) { - table[i][j] = (char) (random.nextInt((26) + 1) + 65); - System.out.print("|" + table[i][j] + "|"); + table[i][j] = (char) (random.nextInt(((90 - 65) + 1)) + 65); + System.out.print("|" + table[i][j]); } + System.out.print("|"); System.out.println(); } checkStratAndExecute(strategy, table); @@ -56,24 +57,28 @@ private static void checkStrategyValid(String strategy) { } private static void checkStratAndExecute(String strategy, char[][] table) { + StringBuilder str = new StringBuilder(); if (strategy.equals("even")) { System.out.print("Even letters - "); for (int i = 0; i < length; i++) { for (int j = 0; j < width; j++) { if (table[i][j] % 2 == 0) { - System.out.print(table[i][j] + " "); + str.append(table[i][j]).append(", "); } } } - } else if (strategy.equals("odd")) { + } else { System.out.print("Odd letters - "); for (int i = 0; i < length; i++) { for (int j = 0; j < width; j++) { if (table[i][j] % 2 != 0) { - System.out.print(table[i][j] + " "); + str.append(table[i][j]).append(", "); } } } } + if (str.length() > 2) { + System.out.print(str.substring(0, str.length() - 2)); + } } } diff --git a/src/main/java/homework_2/traffic_light/ExtraTrafficLight.java b/src/main/java/homework_2/traffic_light/ExtraTrafficLight.java index f4e1f35d..ea8dd49a 100644 --- a/src/main/java/homework_2/traffic_light/ExtraTrafficLight.java +++ b/src/main/java/homework_2/traffic_light/ExtraTrafficLight.java @@ -8,7 +8,7 @@ public class ExtraTrafficLight { - public static void run() { + public void run() { System.out.println("Provide time in \"hh:mm:ss\" format: "); try (Scanner scan = new Scanner(System.in)) { String nextLine = scan.next(); diff --git a/src/main/java/homework_2/traffic_light/TrafficLight.java b/src/main/java/homework_2/traffic_light/TrafficLight.java index c57c5423..4fb569d1 100644 --- a/src/main/java/homework_2/traffic_light/TrafficLight.java +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -5,12 +5,12 @@ import static homework_2.traffic_light.ColorSelector.pickColor; -class TrafficLight { +public class TrafficLight { - public static void run() { + public void run() { System.out.println("Provide time in seconds:"); try (Scanner scan = new Scanner(System.in)) { - int seconds = scan.nextInt(); + int seconds = Integer.parseInt(scan.nextLine()); if (seconds < 0) { System.out.println("Only 1 non-negative integer is allowed as passed parameter"); } else if (seconds >= 86400) { @@ -18,7 +18,7 @@ public static void run() { } else { getSeconds(seconds); } - } catch (InputMismatchException e) { + } catch (InputMismatchException | NumberFormatException e) { System.out.println("Only 1 non-negative integer is allowed as passed parameter"); } } @@ -33,25 +33,4 @@ private static void getSeconds(int seconds) { System.out.println(pickColor("red")); } } -} - -// private static void selectMode(int mode) { -// if (mode == 1) { -// firstMode(); -// } else if (mode == 2) { -// secondMode(); -// } else { -// System.out.println("You entered wrong mode number."); -// } -// } - - -// public static void greeting() { -// System.out.println("Pick mode: 1 - provide seconds, 2 - provide time in format \"hh:mm:ss\": "); -// try (Scanner scan = new Scanner(System.in)) { -// int mode = scan.nextInt(); -// selectMode(mode); -// } catch (InputMismatchException e) { -// System.out.println("Only 1 or 2 allow"); -// } -// } \ No newline at end of file +} \ No newline at end of file diff --git a/src/main/java/homework_4/custom_annotation/HelloGenerator.java b/src/main/java/homework_4/custom_annotation/HelloGenerator.java index 5acf0db5..9eef10ae 100644 --- a/src/main/java/homework_4/custom_annotation/HelloGenerator.java +++ b/src/main/java/homework_4/custom_annotation/HelloGenerator.java @@ -1,6 +1,5 @@ package homework_4.custom_annotation; -import java.util.ArrayList; import java.util.Arrays; public class HelloGenerator { @@ -19,8 +18,8 @@ public static int[] seriesUp(int n) { int[] res = new int[n * (n + 1) / 2]; int index = 0; - for(int i = 1; i <= n; i++) { - for(int j = 0; j < i; j++) { + for (int i = 1; i <= n; i++) { + for (int j = 0; j < i; j++) { res[index + j] = j + 1; } index += i; @@ -29,6 +28,7 @@ public static int[] seriesUp(int n) { System.out.println(Arrays.toString(res)); return res; } + @CustomAnnotation public HelloGenerator() { String temp; @@ -68,9 +68,6 @@ public int getAge() { return age; } - - - @Override public String toString() { return "Hello " + name + "!" + " You are " + age + " year old!"; diff --git a/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java b/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java index 4bcdda82..fb799585 100644 --- a/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java +++ b/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java @@ -8,7 +8,7 @@ public class CustomRegexMatcher { private static final String CHECK_USERNAME = "^[a-z0-9.-]{5,10}$"; - public static void run() { + public void run() { System.out.println(checkRegex()); } diff --git a/src/main/java/homework_5/custom_regex_matcher/Main.java b/src/main/java/homework_5/custom_regex_matcher/Main.java index 0b612ebf..f8b52c06 100644 --- a/src/main/java/homework_5/custom_regex_matcher/Main.java +++ b/src/main/java/homework_5/custom_regex_matcher/Main.java @@ -2,6 +2,6 @@ public class Main { public static void main(String[] args) { - CustomRegexMatcher.run(); + new CustomRegexMatcher().run(); } } diff --git a/src/main/java/homework_5/power_of_number/Main.java b/src/main/java/homework_5/power_of_number/Main.java index 8f1c5b6d..64c1ff9c 100644 --- a/src/main/java/homework_5/power_of_number/Main.java +++ b/src/main/java/homework_5/power_of_number/Main.java @@ -2,6 +2,6 @@ public class Main { public static void main(String[] args) { - PowerOfNumber.run(); + new PowerOfNumber().run(); } } diff --git a/src/main/java/homework_5/power_of_number/PowerOfNumber.java b/src/main/java/homework_5/power_of_number/PowerOfNumber.java index 74cad4a0..025768b4 100644 --- a/src/main/java/homework_5/power_of_number/PowerOfNumber.java +++ b/src/main/java/homework_5/power_of_number/PowerOfNumber.java @@ -5,7 +5,7 @@ public class PowerOfNumber { - public static void run() { + public void run() { int[] input = getInput(); if (input.length != 2) { System.out.println("Only 2 non-negative integers are allowed"); diff --git a/src/main/java/sea_battle/Main.java b/src/main/java/sea_battle/Main.java new file mode 100644 index 00000000..5eb8f8a5 --- /dev/null +++ b/src/main/java/sea_battle/Main.java @@ -0,0 +1,4 @@ +package sea_battle; + +public class Main { +} diff --git a/src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java b/src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java index 82925da9..359e3b65 100644 --- a/src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java +++ b/src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java @@ -11,7 +11,7 @@ class CustomRegexMatcherTest extends UnitBase { void givenCorrectUserName_whenCheckRegex_thenTrue() { String expected = "true"; setInput("nuker228"); - CustomRegexMatcher.run(); + new CustomRegexMatcher().run(); removeFromOutput("Enter your username, it must only contain letters, numbers and dot, minimum length 5, maximum length 10(inclusive):"); assertEquals(expected, getOutput()); printOut(); @@ -21,7 +21,7 @@ void givenCorrectUserName_whenCheckRegex_thenTrue() { void givenCorrectUserNameWithDot_whenCheckRegex_thenTrue() { String expected = "true"; setInput("nuker.228"); - CustomRegexMatcher.run(); + new CustomRegexMatcher().run(); removeFromOutput("Enter your username, it must only contain letters, numbers and dot, minimum length 5, maximum length 10(inclusive):"); assertEquals(expected, getOutput()); printOut(); @@ -31,7 +31,7 @@ void givenCorrectUserNameWithDot_whenCheckRegex_thenTrue() { void givenIncorrectUserName_whenCheckRegex_thenFalse() { String expected = "false"; setInput("nuker@228"); - CustomRegexMatcher.run(); + new CustomRegexMatcher().run(); removeFromOutput("Enter your username, it must only contain letters, numbers and dot, minimum length 5, maximum length 10(inclusive):"); assertEquals(expected, getOutput()); printOut(); diff --git a/src/test/java/homework_5/power_of_number/PowerOfNumberTest.java b/src/test/java/homework_5/power_of_number/PowerOfNumberTest.java index 8ed81475..3158c09c 100644 --- a/src/test/java/homework_5/power_of_number/PowerOfNumberTest.java +++ b/src/test/java/homework_5/power_of_number/PowerOfNumberTest.java @@ -11,7 +11,7 @@ class PowerOfNumberTest extends UnitBase { void given5and2_whenPoW_then25() { String expected = String.valueOf((int) Math.pow(5, 2)); setInput("5 2"); - PowerOfNumber.run(); + new PowerOfNumber().run(); assertEquals(expected, getOutput()); printOut(); } @@ -20,7 +20,7 @@ void given5and2_whenPoW_then25() { void given0and5_whenPoW_then25() { String expected = String.valueOf((int) Math.pow(0, 5)); setInput("0 5"); - PowerOfNumber.run(); + new PowerOfNumber().run(); assertEquals(expected, getOutput()); printOut(); } @@ -29,7 +29,7 @@ void given0and5_whenPoW_then25() { void given3and0_whenPoW_then1() { String expected = String.valueOf((int) Math.pow(3, 0)); setInput("3 0"); - PowerOfNumber.run(); + new PowerOfNumber().run(); assertEquals(expected, getOutput()); printOut(); } @@ -38,7 +38,7 @@ void given3and0_whenPoW_then1() { void givenWrongInput_whenPoW_thenPrintError() { String expected = "Only 2 non-negative integers are allowed"; setInput("asd fdf"); - PowerOfNumber.run(); + new PowerOfNumber().run(); assertEquals(expected, getOutput()); printOut(); } @@ -47,7 +47,7 @@ void givenWrongInput_whenPoW_thenPrintError() { void givenOnlyOneArgument_whenPoW_thenPrintError() { String expected = "Only 2 non-negative integers are allowed"; setInput("5"); - PowerOfNumber.run(); + new PowerOfNumber().run(); assertEquals(expected, getOutput()); printOut(); } From 86ff8908cdcc0b1e8554678020cc989f3bedfd0f Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Fri, 3 Sep 2021 15:35:12 +0300 Subject: [PATCH 58/69] Edited method names --- .../random_chars_table/RandomCharsTable.java | 40 +++++++++++-------- 1 file changed, 23 insertions(+), 17 deletions(-) diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java index 925bc9c4..74d6f9a4 100644 --- a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -1,43 +1,49 @@ package homework_2.random_chars_table; -import lombok.experimental.SuperBuilder; - import java.util.InputMismatchException; import java.util.Random; import java.util.Scanner; public class RandomCharsTable { - private static int length; - private static int width; + private int length; + private int width; + private String strategy; public void run() { + createTableWithRandomCharacters(); + } + + private void createTableWithRandomCharacters() { System.out.println("Enter valid table length, width and strategy(even or odd) in format \"length width strategy\" "); - getInput(); + inputData(); + checkLengthAndWidth(length, width); + checkStrategyValid(strategy); + fillAndPrintTable(strategy, getTable()); + } + + private char[][] getTable() { + return new char[length][width]; } - private static void getInput() { + private void inputData() { try (Scanner scanner = new Scanner(System.in)) { - String[] input= scanner.nextLine().split(" "); + String[] input = scanner.nextLine().split(" "); length = Integer.parseInt(input[0]); width = Integer.parseInt(input[1]); - String strategy = input[2]; - checkLengthAndWidth(length, width); - checkStrategyValid(strategy); - char[][] table = new char[length][width]; - fillAndPrintTable(strategy, table); + strategy = input[2]; } catch (NegativeArraySizeException | InputMismatchException | NumberFormatException e) { System.out.println("Passed parameters should match the format [positive integer] [positive integer] [even|odd]"); } } - private static void checkLengthAndWidth(int length, int width) { + private void checkLengthAndWidth(int length, int width) { if (length == 0 || width == 0) { throw new InputMismatchException(); } } - private static void fillAndPrintTable(String strategy, char[][] table) { + private void fillAndPrintTable(String strategy, char[][] table) { Random random = new Random(); for (int i = 0; i < length; i++) { for (int j = 0; j < width; j++) { @@ -47,16 +53,16 @@ private static void fillAndPrintTable(String strategy, char[][] table) { System.out.print("|"); System.out.println(); } - checkStratAndExecute(strategy, table); + checkStrategyAndExecute(strategy, table); } - private static void checkStrategyValid(String strategy) { + private void checkStrategyValid(String strategy) { if (!strategy.equals("even") && !strategy.equals("odd")) { throw new InputMismatchException(); } } - private static void checkStratAndExecute(String strategy, char[][] table) { + private void checkStrategyAndExecute(String strategy, char[][] table) { StringBuilder str = new StringBuilder(); if (strategy.equals("even")) { System.out.print("Even letters - "); From 759f5ea444c1b8b54a901803689ff3d40bd912a2 Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Mon, 20 Sep 2021 22:46:27 +0300 Subject: [PATCH 59/69] Complete homework_7 --- src/main/java/homework_7/Main.java | 19 +++++++++++ .../kitten_to_cat_function/Cat.java | 25 +++++++++++++++ .../kitten_to_cat_function/Kitten.java | 32 +++++++++++++++++++ .../KittenToCatFunction.java | 6 ++++ 4 files changed, 82 insertions(+) create mode 100644 src/main/java/homework_7/Main.java create mode 100644 src/main/java/homework_7/kitten_to_cat_function/Cat.java create mode 100644 src/main/java/homework_7/kitten_to_cat_function/Kitten.java create mode 100644 src/main/java/homework_7/kitten_to_cat_function/KittenToCatFunction.java diff --git a/src/main/java/homework_7/Main.java b/src/main/java/homework_7/Main.java new file mode 100644 index 00000000..cbe096dd --- /dev/null +++ b/src/main/java/homework_7/Main.java @@ -0,0 +1,19 @@ +package homework_7; + +import homework_7.kitten_to_cat_function.Cat; +import homework_7.kitten_to_cat_function.Kitten; +import homework_7.kitten_to_cat_function.KittenToCatFunction; + +public class Main { + public static void main(String[] args) { + Kitten rudolf = new Kitten("Rudolf", 3, "Gottalot"); + Cat buchi = new Cat("Buchi", 12); + + KittenToCatFunction kittenToCat = kitten -> new Cat( kitten.getName(), kitten.getAge() + 10); + Cat grewRudolf = kittenToCat.grow(rudolf); + + System.out.println(buchi); + System.out.println(rudolf); + System.out.println(grewRudolf); + } +} \ No newline at end of file diff --git a/src/main/java/homework_7/kitten_to_cat_function/Cat.java b/src/main/java/homework_7/kitten_to_cat_function/Cat.java new file mode 100644 index 00000000..dc0bfdf6 --- /dev/null +++ b/src/main/java/homework_7/kitten_to_cat_function/Cat.java @@ -0,0 +1,25 @@ +package homework_7.kitten_to_cat_function; + +public class Cat { + private final String name; + private final int age; + + public Cat(String name, int age) { + this.name = name; + this.age = age; + } + + public String getName() { + return name; + } + + public int getAge() { + return age; + } + + @Override + public String toString() { + return "Cat's name: " + this.getName() + + ", Cat's age: " + this.getAge(); + } +} \ No newline at end of file diff --git a/src/main/java/homework_7/kitten_to_cat_function/Kitten.java b/src/main/java/homework_7/kitten_to_cat_function/Kitten.java new file mode 100644 index 00000000..a6ba36d1 --- /dev/null +++ b/src/main/java/homework_7/kitten_to_cat_function/Kitten.java @@ -0,0 +1,32 @@ +package homework_7.kitten_to_cat_function; + +public class Kitten { + private final String nameOfEnemy; + private final String name; + private final int age; + + public Kitten(String name, int age, String enemyName) { + this.name = name; + this.age = age; + this.nameOfEnemy = enemyName; + } + + public String getNameOfEnemy() { + return nameOfEnemy; + } + + public String getName() { + return name; + } + + public int getAge() { + return age; + } + + @Override + public String toString() { + return "Kitten's name: " + this.getName() + + ", Kitten's age: " + this.getAge() + + ", Kitten's enemy name: " + this.getNameOfEnemy() ; + } +} diff --git a/src/main/java/homework_7/kitten_to_cat_function/KittenToCatFunction.java b/src/main/java/homework_7/kitten_to_cat_function/KittenToCatFunction.java new file mode 100644 index 00000000..5c7b09d5 --- /dev/null +++ b/src/main/java/homework_7/kitten_to_cat_function/KittenToCatFunction.java @@ -0,0 +1,6 @@ +package homework_7.kitten_to_cat_function; + +@FunctionalInterface +public interface KittenToCatFunction { + Cat grow(Kitten kitten); +} From fb8ef30066eba5f2f968cae60f15b4e4fdff935b Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Mon, 20 Sep 2021 22:57:30 +0300 Subject: [PATCH 60/69] Edit README.md --- README.md | 1 + src/main/java/sea_battle/Main.java | 4 ---- 2 files changed, 1 insertion(+), 4 deletions(-) delete mode 100644 src/main/java/sea_battle/Main.java diff --git a/README.md b/README.md index 7d610379..51f74cf8 100644 --- a/README.md +++ b/README.md @@ -15,5 +15,6 @@ | HW5 | [PowerOfNumber](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_5/power_of_number)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_5/power_of_number) | The app that raises a number to a power | |-----| [CustomRegexMatcher](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_5/custom_regex_matcher)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_5/custom_regex_matcher) | The app that check input string by hardcoded regex and return boolean answer | | HW6 | [MapProblemsGenerator](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_6/map_problem_generator)|Two classes that allow you to check the work of the collision and create a situation where it is impossible to get the object just put| +| HW7 | [KittenToCatFunction](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_7)|Functional interface that allows you to transform a Kitten into a Cat| [CodingBat link](https://codingbat.com/done?user=slowly@live.ru&tag=8165639202) diff --git a/src/main/java/sea_battle/Main.java b/src/main/java/sea_battle/Main.java deleted file mode 100644 index 5eb8f8a5..00000000 --- a/src/main/java/sea_battle/Main.java +++ /dev/null @@ -1,4 +0,0 @@ -package sea_battle; - -public class Main { -} From f15468de7f00f2a5648c97f4bf5118cc56da3765 Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Mon, 20 Sep 2021 23:01:33 +0300 Subject: [PATCH 61/69] Fix wrong naming --- .../{map_problem_generator => map_problems_generator}/Main.java | 2 +- .../MapProblemsCollisionGenerator.java | 2 +- .../MapProblemsGenerator.java | 2 +- .../MapProblemsMutableGenerator.java | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) rename src/main/java/homework_6/{map_problem_generator => map_problems_generator}/Main.java (87%) rename src/main/java/homework_6/{map_problem_generator => map_problems_generator}/MapProblemsCollisionGenerator.java (92%) rename src/main/java/homework_6/{map_problem_generator => map_problems_generator}/MapProblemsGenerator.java (96%) rename src/main/java/homework_6/{map_problem_generator => map_problems_generator}/MapProblemsMutableGenerator.java (94%) diff --git a/src/main/java/homework_6/map_problem_generator/Main.java b/src/main/java/homework_6/map_problems_generator/Main.java similarity index 87% rename from src/main/java/homework_6/map_problem_generator/Main.java rename to src/main/java/homework_6/map_problems_generator/Main.java index a859f31e..235535d8 100644 --- a/src/main/java/homework_6/map_problem_generator/Main.java +++ b/src/main/java/homework_6/map_problems_generator/Main.java @@ -1,4 +1,4 @@ -package homework_6.map_problem_generator; +package homework_6.map_problems_generator; public class Main { public static void main(String[] args) { diff --git a/src/main/java/homework_6/map_problem_generator/MapProblemsCollisionGenerator.java b/src/main/java/homework_6/map_problems_generator/MapProblemsCollisionGenerator.java similarity index 92% rename from src/main/java/homework_6/map_problem_generator/MapProblemsCollisionGenerator.java rename to src/main/java/homework_6/map_problems_generator/MapProblemsCollisionGenerator.java index ec43c8a6..a5b8c8f9 100644 --- a/src/main/java/homework_6/map_problem_generator/MapProblemsCollisionGenerator.java +++ b/src/main/java/homework_6/map_problems_generator/MapProblemsCollisionGenerator.java @@ -1,4 +1,4 @@ -package homework_6.map_problem_generator; +package homework_6.map_problems_generator; import java.util.Objects; diff --git a/src/main/java/homework_6/map_problem_generator/MapProblemsGenerator.java b/src/main/java/homework_6/map_problems_generator/MapProblemsGenerator.java similarity index 96% rename from src/main/java/homework_6/map_problem_generator/MapProblemsGenerator.java rename to src/main/java/homework_6/map_problems_generator/MapProblemsGenerator.java index 282d8fd5..5d81da6b 100644 --- a/src/main/java/homework_6/map_problem_generator/MapProblemsGenerator.java +++ b/src/main/java/homework_6/map_problems_generator/MapProblemsGenerator.java @@ -1,4 +1,4 @@ -package homework_6.map_problem_generator; +package homework_6.map_problems_generator; import java.util.HashMap; diff --git a/src/main/java/homework_6/map_problem_generator/MapProblemsMutableGenerator.java b/src/main/java/homework_6/map_problems_generator/MapProblemsMutableGenerator.java similarity index 94% rename from src/main/java/homework_6/map_problem_generator/MapProblemsMutableGenerator.java rename to src/main/java/homework_6/map_problems_generator/MapProblemsMutableGenerator.java index c0bbf288..3956948d 100644 --- a/src/main/java/homework_6/map_problem_generator/MapProblemsMutableGenerator.java +++ b/src/main/java/homework_6/map_problems_generator/MapProblemsMutableGenerator.java @@ -1,4 +1,4 @@ -package homework_6.map_problem_generator; +package homework_6.map_problems_generator; public class MapProblemsMutableGenerator { From 01fb814441a6c4fe873b252972cfe78b9ac13019 Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Mon, 20 Sep 2021 23:02:23 +0300 Subject: [PATCH 62/69] Edit README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 51f74cf8..9f3cb03e 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ |-----| [Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_4/singleton)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_4/singleton) | Creational design pattern, which ensures that only one object of its kind exists | | HW5 | [PowerOfNumber](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_5/power_of_number)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_5/power_of_number) | The app that raises a number to a power | |-----| [CustomRegexMatcher](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_5/custom_regex_matcher)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_5/custom_regex_matcher) | The app that check input string by hardcoded regex and return boolean answer | -| HW6 | [MapProblemsGenerator](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_6/map_problem_generator)|Two classes that allow you to check the work of the collision and create a situation where it is impossible to get the object just put| +| HW6 | [MapProblemsGenerator](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_6/map_problems_generator)|Two classes that allow you to check the work of the collision and create a situation where it is impossible to get the object just put| | HW7 | [KittenToCatFunction](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_7)|Functional interface that allows you to transform a Kitten into a Cat| [CodingBat link](https://codingbat.com/done?user=slowly@live.ru&tag=8165639202) From 641ed85c681cd7c0d3757dd0e09c360fe2dd3bbd Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Tue, 21 Sep 2021 16:42:19 +0300 Subject: [PATCH 63/69] Course project complete --- src/main/java/course_project/Main.java | 8 + src/main/java/course_project/SeaBattle.java | 12 + .../course_project/board/Battlefield.java | 207 +++++++++++++++++ src/main/java/course_project/board/Board.java | 113 ++++++++++ src/main/java/course_project/board/Cell.java | 48 ++++ .../java/course_project/dialogue/Menu.java | 208 ++++++++++++++++++ .../java/course_project/logic/GameLogic.java | 120 ++++++++++ .../java/course_project/player/Player.java | 28 +++ .../java/course_project/ships/Battleship.java | 11 + .../java/course_project/ships/Cruiser.java | 11 + .../java/course_project/ships/Destroyer.java | 11 + .../java/course_project/ships/PatrolBoat.java | 11 + src/main/java/course_project/ships/Ship.java | 30 +++ .../java/course_project/utils/Colors.java | 10 + .../utils/RandomDirectionGenerator.java | 9 + .../utils/RandomPositionGenerator.java | 11 + 16 files changed, 848 insertions(+) create mode 100644 src/main/java/course_project/Main.java create mode 100644 src/main/java/course_project/SeaBattle.java create mode 100644 src/main/java/course_project/board/Battlefield.java create mode 100644 src/main/java/course_project/board/Board.java create mode 100644 src/main/java/course_project/board/Cell.java create mode 100644 src/main/java/course_project/dialogue/Menu.java create mode 100644 src/main/java/course_project/logic/GameLogic.java create mode 100644 src/main/java/course_project/player/Player.java create mode 100644 src/main/java/course_project/ships/Battleship.java create mode 100644 src/main/java/course_project/ships/Cruiser.java create mode 100644 src/main/java/course_project/ships/Destroyer.java create mode 100644 src/main/java/course_project/ships/PatrolBoat.java create mode 100644 src/main/java/course_project/ships/Ship.java create mode 100644 src/main/java/course_project/utils/Colors.java create mode 100644 src/main/java/course_project/utils/RandomDirectionGenerator.java create mode 100644 src/main/java/course_project/utils/RandomPositionGenerator.java diff --git a/src/main/java/course_project/Main.java b/src/main/java/course_project/Main.java new file mode 100644 index 00000000..59fb35f3 --- /dev/null +++ b/src/main/java/course_project/Main.java @@ -0,0 +1,8 @@ +package course_project; + +public class Main { + + public static void main(String[] args) { + SeaBattle.run(); + } +} diff --git a/src/main/java/course_project/SeaBattle.java b/src/main/java/course_project/SeaBattle.java new file mode 100644 index 00000000..42e4b4ae --- /dev/null +++ b/src/main/java/course_project/SeaBattle.java @@ -0,0 +1,12 @@ +package course_project; + +import course_project.dialogue.Menu; + +final class SeaBattle { + + public static void run() { + Menu.showLogo(); + Menu.showGreetings(); + Menu.showMainMenu(); + } +} diff --git a/src/main/java/course_project/board/Battlefield.java b/src/main/java/course_project/board/Battlefield.java new file mode 100644 index 00000000..9be5778a --- /dev/null +++ b/src/main/java/course_project/board/Battlefield.java @@ -0,0 +1,207 @@ +package course_project.board; + +import course_project.player.Player; +import course_project.ships.*; + +import java.util.*; + +import static course_project.dialogue.Menu.*; +import static course_project.utils.RandomPositionGenerator.generateRandomForCell; +import static course_project.utils.RandomDirectionGenerator.generateRandomDirection; + +public class Battlefield extends Board { + + private final List availableShips = new ArrayList<>(); + + public Battlefield() { + super.cells = new Cell[FIELD_SIZE][FIELD_SIZE]; + fillCells(); + addShipsToList(); + } + + public List getAvailableShips() { + return this.availableShips; + } + + public void addShipsToList() { + availableShips.add(new Battleship()); + availableShips.add(new Destroyer()); + availableShips.add(new Destroyer()); + availableShips.add(new Cruiser()); + availableShips.add(new Cruiser()); + availableShips.add(new Cruiser()); + availableShips.add(new PatrolBoat()); + availableShips.add(new PatrolBoat()); + availableShips.add(new PatrolBoat()); + availableShips.add(new PatrolBoat()); + } + + public boolean addShipOnBattlefield(Ship ship, Cell cell, boolean isHorizontal) { + if (checkSpaceForPlaceShip(cell, ship.getSize(), isHorizontal)) { + if (isHorizontal) { + return !addRowOfCells(cell, ship); + } else { + return !addColumnOfCells(cell, ship); + } + } + return true; + } + + public void availableShipsDecrease(Ship ship) { + this.availableShips.remove(ship); + } + + private boolean addColumnOfCells(Cell entryCell, Ship ship) { + if (checkPossibilityForAddColumn(entryCell, ship.getSize())) { + int y = entryCell.getY(); + for (int i = entryCell.getX(); i < entryCell.getX() + ship.getSize(); i++) { + getCellByPosition(i, y).setShipAtCell(ship); + } + return true; + } + return false; + } + + private boolean addRowOfCells(Cell entryCell, Ship ship) { + if (checkPossibilityForAddRow(entryCell, ship.getSize())) { + int x = entryCell.getX(); + for (int j = entryCell.getY(); j < entryCell.getY() + ship.getSize(); j++) { + getCellByPosition(x, j).setShipAtCell(ship); + } + return true; + } + return false; + } + + private boolean checkPossibilityForAddColumn(Cell entryCell, int shipSize) { + if (!(checkCellAbove(entryCell) && + checkCellAboveLeftDiagonal(entryCell) && + checkCellAboveRightDiagonal(entryCell))) { + return false; + } + int y = entryCell.getY(); + for (int i = entryCell.getX(); i < entryCell.getX() + shipSize; i++) { + Cell currentCell = cells[i][y]; + if (!(isCellEmpty(currentCell) && + checkCellBelow(currentCell) && + checkCellOnTheLeft(currentCell) && + checkCellOnTheRight(currentCell))) { + return false; + } + if (i == entryCell.getX() + shipSize - 1 && + !(checkCellBelowLeftDiagonal(currentCell) && + checkCellBelowRightDiagonal(currentCell)) + ) { + return false; + } + } + return true; + } + + private boolean checkPossibilityForAddRow(Cell entryCell, int shipSize) { + if (!(checkCellOnTheLeft(entryCell) && + checkCellAboveLeftDiagonal(entryCell) && + checkCellBelowLeftDiagonal(entryCell) && + checkCellAboveRightDiagonal(entryCell)) + ) { + return false; + } + int x = entryCell.getX(); + for (int j = entryCell.getY(); j < entryCell.getY() + shipSize; j++) { + Cell currentCell = cells[x][j]; + if (!(isCellEmpty(currentCell) && + checkCellOnTheRight(currentCell) && + checkCellAbove(currentCell) && + checkCellBelow(currentCell)) + ) { + System.out.println("Cannot set the ship to coordinates " + Character.toUpperCase((char) (entryCell.getY() + 97)) + "" + (entryCell.getX() + 1) + ", check if the ship is in contact with another.\n"); + return false; + } + if (j == entryCell.getY() + shipSize - 1 && + !(checkCellAboveRightDiagonal(currentCell) && + checkCellBelowRightDiagonal(currentCell)) + ) { + return false; + } + } + return true; + } + + private boolean checkSpaceForPlaceShip(Cell fromCell, int shipSize, boolean isHorizontal) { + return isHorizontal ? + fromCell.getY() >= 0 && fromCell.getY() + shipSize <= FIELD_SIZE : + fromCell.getX() >= 0 && fromCell.getX() + shipSize <= FIELD_SIZE; + } + + private boolean checkCellAbove(Cell currentCell) { + return currentCell.getX() == 0 || isCellEmpty(cells[currentCell.getX() - 1][currentCell.getY()]); + } + + private boolean checkCellBelow(Cell currentCell) { + return currentCell.getX() == 9 || isCellEmpty(cells[currentCell.getX() + 1][currentCell.getY()]); + } + + private boolean checkCellOnTheRight(Cell currentCell) { + return currentCell.getY() == 9 || isCellEmpty(cells[currentCell.getX()][currentCell.getY() + 1]); + } + + private boolean checkCellOnTheLeft(Cell currentCell) { + return currentCell.getY() == 0 || isCellEmpty(cells[currentCell.getX()][currentCell.getY() - 1]); + } + + private boolean checkCellAboveLeftDiagonal(Cell currentCell) { + return currentCell.getX() == 0 || currentCell.getY() == 0 || + isCellEmpty(cells[currentCell.getX() - 1][currentCell.getY() - 1]); + } + + private boolean checkCellBelowLeftDiagonal(Cell currentCell) { + return currentCell.getX() == 9 || currentCell.getY() == 0 || + isCellEmpty(cells[currentCell.getX() + 1][currentCell.getY() - 1]); + } + + private boolean checkCellAboveRightDiagonal(Cell currentCell) { + return currentCell.getX() == 0 || currentCell.getY() == 9 || + isCellEmpty(cells[currentCell.getX() - 1][currentCell.getY() + 1]); + } + + private boolean checkCellBelowRightDiagonal(Cell currentCell) { + return currentCell.getX() == 9 || currentCell.getY() == 9 || + isCellEmpty(cells[currentCell.getX() + 1][currentCell.getY() + 1]); + } + + + public boolean hasAvailableShips() { + return !this.availableShips.isEmpty(); + } + + public static void addShipsOneByOne(Player currentPlayer) { + showHelp(); + for (Ship ship : currentPlayer.getField().getAvailableShips()) { + currentPlayer.getField().printField(); + Cell position; + boolean isHorizontal = true; + do { + System.out.print("Ship's type: " + ship.getName() + ". Size: " + ship.getSize() + ". Specify coordinates: "); + String[] cellPossition = getInputPosition().split(" "); + int x = Integer.parseInt(cellPossition[0].substring(1)) - 1; + int y = Integer.parseInt(String.valueOf(cellPossition[0].charAt(0) - 97)); + position = currentPlayer.getField().getCellByPosition(x, y); + if (cellPossition.length == 2) { + isHorizontal = !"v".equals(cellPossition[1]); + } + } while (currentPlayer.getField().addShipOnBattlefield(ship, position, isHorizontal)); + } + } + + public static void generateRandomPlacesForShips(Player currentPlayer) { + for (Ship ship : currentPlayer.getField().getAvailableShips()) { + Cell toPos; + boolean isHorizontal; + do { + toPos = currentPlayer.getField().getCellByPosition(generateRandomForCell(), + generateRandomForCell()); + isHorizontal = generateRandomDirection(); + } while (currentPlayer.getField().addShipOnBattlefield(ship, toPos, isHorizontal)); + } + } +} diff --git a/src/main/java/course_project/board/Board.java b/src/main/java/course_project/board/Board.java new file mode 100644 index 00000000..0d5a0275 --- /dev/null +++ b/src/main/java/course_project/board/Board.java @@ -0,0 +1,113 @@ +package course_project.board; + +import course_project.player.Player; + +import static course_project.utils.Colors.*; + +public class Board { + + public static final int FIELD_SIZE = 10; + private static final String SHIP = ANSI_GREEN + "■" + ANSI_RESET; + private static final String WATER = BACKGROUND_CYAN + " " + ANSI_RESET; + private static final String MISS = ANSI_MAGENTA + "▓" + ANSI_RESET; + private static final String HIT = ANSI_YELLOW + "×" + ANSI_RESET; + private static final String DESTROY = ANSI_RED + "*" + ANSI_RESET; + + Cell[][] cells; + + protected Board() { + this.cells = new Cell[FIELD_SIZE][FIELD_SIZE]; + fillCells(); + } + + public void fillCells() { + for (int i = 0; i < FIELD_SIZE; i++) { + for (int j = 0; j < FIELD_SIZE; j++) { + cells[i][j] = new Cell(i, j); + } + } + } + + public void printField() { + StringBuilder field = new StringBuilder(); + field.append("\t" + "A B C D E F G H I J").append("\n"); + + for (int i = 0; i < FIELD_SIZE; i++) { + field.append(String.format("|%-2d|", i + 1)); + for (int j = 0; j < FIELD_SIZE; j++) { + Cell currentCell = getCellByPosition(i, j); + String symbol = WATER; + if (!isCellEmpty(currentCell)) { + symbol = SHIP; + } + field.append(String.format("%s ", symbol)); + } + field.append("\n"); + } + System.out.println(field); + } + + public void showTwoFields(Player currentPlayer, Player enemy) { + + StringBuilder twoFields = new StringBuilder(); + + twoFields.append("\t" + "A B C D E F G H I J").append("\t\t\t " + "A B C D E F G H I J").append("\n"); + + for (int i = 0; i < FIELD_SIZE; i++) { + twoFields.append(String.format("|%-2d|", i + 1)); + for (int j = 0; j < FIELD_SIZE; j++) { + if (currentPlayer.getField().getCellByPosition(i, j).isHit()) { + checkCellStateAndMarkIt(currentPlayer, twoFields, i, j); + } else { + if (currentPlayer.getField().isCellEmpty(currentPlayer.getField().getCellByPosition(i, j))) { + twoFields.append(String.format("%s ", WATER)); + } else { + twoFields.append(String.format("%s ", SHIP)); + } + } + } + twoFields.append("\t\t").append(String.format("|%-2d|", i + 1)); + for (int j = 0; j < FIELD_SIZE; j++) { + if (enemy.getField().getCellByPosition(i, j).isHit()) { + checkCellStateAndMarkIt(enemy, twoFields, i, j); + } else { + twoFields.append(String.format("%s ", WATER)); + } + } + twoFields.append("\n"); + } + System.out.println(twoFields); + } + + private void checkCellStateAndMarkIt(Player currentPlayer, StringBuilder bothFields, int i, int j) { + if (currentPlayer.getField().isHit(currentPlayer.getField().getCellByPosition(i, j))) { + if (currentPlayer.getField().getCellByPosition(i, j).getReference().isDestroyed()) { + bothFields.append(String.format("%s ", DESTROY)); + } else { + bothFields.append(String.format("%s ", HIT)); + } + } else { + bothFields.append(String.format("%s ", MISS)); + } + } + + public Cell getCellByPosition(int x, int y) { + for (Cell[] cellRow : this.cells) { + for (Cell cellColumn : cellRow) { + if (cellColumn.getX() == x && cellColumn.getY() == y) { + return cellColumn; + } + } + } + return null; + } + + public boolean isCellEmpty(Cell currentCell) { + return currentCell.getShipReference() == null; + } + + public boolean isHit(Cell toCell) { + return !isCellEmpty(cells[toCell.getX()][toCell.getY()]); + } + +} diff --git a/src/main/java/course_project/board/Cell.java b/src/main/java/course_project/board/Cell.java new file mode 100644 index 00000000..75eb2c89 --- /dev/null +++ b/src/main/java/course_project/board/Cell.java @@ -0,0 +1,48 @@ +package course_project.board; +//done +import course_project.ships.Ship; + +public class Cell { + + private final int x; + private final int y; + private boolean hit; + private Ship reference; + + public Cell(int x, int y) { + this.x = x; + this.y = y; + this.reference = null; + this.hit = false; + } + + public boolean isHit() { + return this.hit; + } + + public void setHit(boolean hit) { + this.hit = hit; + } + + public Ship getShipReference() { + if (this.reference == null) return null; + else return reference; + } + + public void setShipAtCell(Ship ship) { + this.reference = ship; + } + + public int getX() { + return this.x; + } + + public int getY() { + return this.y; + } + + public Ship getReference() { + return this.reference; + } + +} diff --git a/src/main/java/course_project/dialogue/Menu.java b/src/main/java/course_project/dialogue/Menu.java new file mode 100644 index 00000000..c37f97e2 --- /dev/null +++ b/src/main/java/course_project/dialogue/Menu.java @@ -0,0 +1,208 @@ +package course_project.dialogue; + +import course_project.logic.GameLogic; +import course_project.player.Player; +import course_project.ships.Ship; + +import java.util.Scanner; + +import static course_project.board.Battlefield.generateRandomPlacesForShips; +import static course_project.board.Battlefield.addShipsOneByOne; + +@SuppressWarnings("java:S1118") +public class Menu { + + private static final String START_MESSAGE = "\n\t\t\t\t\tWelcome to Sea Battle mini-game. \n\t\t\t\tFirst of all, you should select game mode:"; + private static final String WRONG_INPUT = "Please, enter a valid coordinates."; + private static final Scanner scanner = new Scanner(System.in); + + private static Player player; + private static Player enemy; + + public static void showGreetings() { + System.out.println(START_MESSAGE); + } + + public static void showMainMenu() { + System.out.println("\t\t\t\t- 1. Human vs Computer" + + "\t\t- 2. Human vs Human" + + "\n\t\t\t\t- 3. Computer vs Computer" + + "\t- 4. Exit"); + String mode = getInput(); + switch (mode) { + case "1": + startHumanVSComputer(); + break; + case "2": + startHumanVSHuman(); + break; + case "3": + startComputerVSComputer(); + break; + case "4": + exit(); + break; + default: + System.out.println(WRONG_INPUT); + showMainMenu(); + } + } + + private static void startHumanVSComputer() { + player = new Player(getInputName(), false); + enemy = new Player("Artem Nikolaev", true); + showPlayerMenu(player); + generateRandomPlacesForShips(enemy); + GameLogic game = new GameLogic(player, enemy); + game.run(); + } + + private static void startHumanVSHuman() { + player = new Player(getInputName(), false); + enemy = new Player(getInputName(), false); + showPlayerMenu(player); + showPlayerMenu(enemy); + GameLogic game = new GameLogic(player, enemy); + game.run(); + } + + private static void startComputerVSComputer() { + player = new Player("Computer 1", true); + enemy = new Player("Computer 2", true); + generateRandomPlacesForShips(player); + generateRandomPlacesForShips(enemy); + GameLogic game = new GameLogic(player, enemy); + game.run(); + } + + private static String getInputName() { + System.out.println("\t\tPlease, provide your name, it can contain only English letters in any case:"); + String name; + while (true) { + name = getInputNameS(); + if (name.matches("^[a-zA-Z ]{2,}$")) { + return name; + } else { + System.out.println("The name is incorrect, it can contain only English letters in any case"); + } + } + } + + private static void showPlayerMenu(Player currentPlayer) { + System.out.println("\tThe next step is to choose the type of ship placement. " + currentPlayer.getName() + ", please, select your choice:" + + "\n\t\t\t\t\t- 1 Add ships on the field manually" + + "\n\t\t\t\t\t- 2 Auto adding ships"); + String input = getInput(); + switch (input) { + case "1": + addShipsOneByOne(currentPlayer); + currentPlayer.getField().printField(); + System.out.println("Battlefield was successfully filled. \n"); + break; + case "2": + generateRandomPlacesForShips(currentPlayer); + currentPlayer.getField().printField(); + System.out.println("Battlefield was successfully filled. \n"); + break; + default: + System.out.println(WRONG_INPUT); + showPlayerMenu(currentPlayer); + } + } + + public static void showHelp() { + System.out.println("\tIn order to manually place the ship on the field, you need specify the correct coordinates, for example, g4 or B3 v. " + + "\n\t\t\t\t\t\tBy default, the direction is set to horizontal." + + "\n\t\t\t\t\tIf you want to rotate ship, add 'v' letter after coordinates." + + "\n\t\t\t\t\tIf you want to leave the game at any time, enter 'exit'"); + } + + public static void showCoordinatesHelp(){ + System.out.println("In order to select which cell you want to hit, you need specify the correct coordinates, for example, a5 or H6\n"); + } + + public static String getPlayerMotionInput() { + while (true) { + String input = getInput(); + if ("exit".equals(input)) { + exit(); + } else if (input.matches("^[a-j]([1-9]|10)$")) { + return input; + } else { + System.out.println(WRONG_INPUT); + } + + } + } + + public static String getInputPosition() { + while (true) { + String input = getInput(); + if ("exit".equals(input)) { + exit(); + } else if (input.matches("^[a-j]([1-9]|10)$") || input.matches("^[a-j]([1-9]|10)\\s[v]$")) { + return input; + } else { + System.out.println(WRONG_INPUT); + } + } + } + + private static String getInput() { + return scanner.nextLine().trim().toLowerCase(); + } + + private static String getInputNameS() { + return scanner.nextLine().trim(); + } + + + public static void destroyTrigger(String enemy, String currentPlayer, Ship ship, int x, int y) { + System.out.println(currentPlayer + " hit " + enemy + "'s ship at coordinates " + Character.toUpperCase((char) (y + 97)) + "" + (x + 1) + " and destroy " + ship.getName() + "."); + } + + public static void showWinScreen(Player currentPlayer, Player opponent) { + System.out.println("\n" + currentPlayer.getName() + ", congratulations, you won the game."); + showCongratulationsPicture(); + System.out.println("\n" + opponent.getName() + ", better luck next time.\n"); + + currentPlayer.getField().showTwoFields(currentPlayer, opponent); + System.out.println("This is the end of the game. Thank you for participating and see you soon."); + exit(); + } + + private static void exit() { + scanner.close(); + Runtime.getRuntime().exit(0); + } + + private static void showCongratulationsPicture() { + System.out.println(" .''. \n" + + " .''. . *''* :_\\/_: . \n" + + " :_\\/_: _\\(/_ .:.*_\\/_* : /\\ : .'.:.'.\n" + + " .''.: /\\ : ./)\\ ':'* /\\ * : '..'. -=:o:=-\n" + + " :_\\/_:'.:::. ' *''* * '.\\'/.' _\\(/_'.':'.'\n" + + " : /\\ : ::::: *_\\/_* -= o =- /)\\ ' *\n" + + " '..' ':::' * /\\ * .'/.\\'. '\n" + + " * *..* :\n" + + " *\n" + + " *"); + } + + public static void showLogo(){ + System.out.println(" |__\n" + + " |\\/\n" + + " ---\n" + + " / | [\n" + + " ! | |||\n" + + " _/| _/|-++'\n" + + " + +--| |--|--|_ |-\n" + + " { /|__| |/\\__| |--- |||__/\n" + + " +---------------___[}-_===_.'____ ||\n" + + " ____`-' ||___-{]_| _[}- | |_[___\\==-- \\/ _\n" + + " __..._____--==/___]_|__|_____________________________[___\\==--___,-----' |\n" + + "| Ilia.Prokofev./\n" + + " \\_______________________________________________________________________|"); + } + +} diff --git a/src/main/java/course_project/logic/GameLogic.java b/src/main/java/course_project/logic/GameLogic.java new file mode 100644 index 00000000..229bd1ea --- /dev/null +++ b/src/main/java/course_project/logic/GameLogic.java @@ -0,0 +1,120 @@ +package course_project.logic; + +import course_project.player.Player; +import course_project.ships.Ship; + +import static course_project.dialogue.Menu.*; +import static course_project.utils.RandomPositionGenerator.generateRandomForCell; + +public class GameLogic { + + private final Player player1; + private final Player player2; + private Player currentPlayer; + + public GameLogic(Player firstPlayer, Player secondPlayer) { + this.player1 = firstPlayer; + this.player2 = secondPlayer; + currentPlayer = firstPlayer; + } + + private void changeCurrentPlayer() { + if (currentPlayer == player1) { + currentPlayer = player2; + } else { + currentPlayer = player1; + } + } + + private Player getEnemy() { + return currentPlayer == player1 ? player2 : player1; + } + + public void run() { + showCoordinatesHelp(); + while (currentPlayer.getField().hasAvailableShips() && getEnemy().getField().hasAvailableShips()) { + if (currentPlayer.isComputer() && getEnemy().isComputer()) { + CPUTurn(currentPlayer); + } else if (!currentPlayer.isComputer() && getEnemy().isComputer()) { + playerTurn(currentPlayer); + } else if (currentPlayer.isComputer() && !getEnemy().isComputer()) { + CPUTurn(currentPlayer); + } + } + } + + private void endGame() { + if (currentPlayer.getField().hasAvailableShips()) { + showWinScreen(currentPlayer, getEnemy()); + } else { + showWinScreen(getEnemy(), currentPlayer); + } + } + + private void CPUTurn(Player currentPlayer) { + int x = generateRandomForCell(); + int y = generateRandomForCell(); + + if (!getEnemy().getField().getCellByPosition(x, y).isHit()) { + getEnemy().getField().getCellByPosition(x, y).setHit(true); + if (!getEnemy().getField().isCellEmpty(getEnemy().getField().getCellByPosition(x, y))) { + Ship enemyShip = getEnemy().getField().getCellByPosition(x, y).getReference(); + enemyShip.hitCountIncrease(); + if (enemyShip.isDestroyed()) { + destroyTrigger(getEnemy().getName(), currentPlayer.getName(), enemyShip, x, y); + getEnemy().getField().availableShipsDecrease(enemyShip); + if (!getEnemy().getField().hasAvailableShips()) { + endGame(); + } + } else { + System.out.println(currentPlayer.getName() + " hit " + getEnemy().getName() + "'s ship at coordinates " + Character.toUpperCase((char) (y + 97)) + "" + (x + 1) + "."); + System.out.println(currentPlayer.getName() + " makes a move one more time."); + } + CPUTurn(currentPlayer); + } else { + System.out.println(currentPlayer.getName() + " select " + Character.toUpperCase((char) (y + 97)) + "" + (x + 1) + " and miss.\n"); + changeCurrentPlayer(); + } + } else { + CPUTurn(currentPlayer); + } + } + + private void playerTurn(Player currentPlayer) { + currentPlayer.getField().showTwoFields(currentPlayer, getEnemy()); + System.out.println(currentPlayer.getName() + ", it's your turn. Enter coordinates: "); + try { + String pos = getPlayerMotionInput(); + int x = Integer.parseInt(pos.substring(1)) - 1; + int y = Integer.parseInt(String.valueOf(pos.charAt(0) - 97)); + + if (getEnemy().getField().getCellByPosition(x, y).isHit()) { + System.out.println(currentPlayer.getName() + ", you have already chosen " + Character.toUpperCase((char) (y + 97)) + "" + (x + 1) + " coordinate, please re-enter: "); + playerTurn(currentPlayer); + } else { + getEnemy().getField().getCellByPosition(x, y).setHit(true); + if (!getEnemy().getField().isCellEmpty(getEnemy().getField().getCellByPosition(x, y))) { + Ship enemyShip = getEnemy().getField().getCellByPosition(x, y).getReference(); + enemyShip.hitCountIncrease(); + if (enemyShip.isDestroyed()) { + destroyTrigger(getEnemy().getName(), currentPlayer.getName(), enemyShip, x, y); + getEnemy().getField().availableShipsDecrease(enemyShip); + + if (!getEnemy().getField().hasAvailableShips()) { + endGame(); + } + } else { + System.out.println(currentPlayer.getName() + " hit " + getEnemy().getName() + "'s ship at coordinates " + Character.toUpperCase((char) (y + 97)) + "" + (x + 1)); + System.out.println(currentPlayer.getName() + " makes a move one more time."); + } + playerTurn(currentPlayer); + } else { + System.out.println(currentPlayer.getName() + " select " + Character.toUpperCase((char) (y + 97)) + "" + (x + 1) + " and miss."); + changeCurrentPlayer(); + } + } + } catch (NumberFormatException e) { + playerTurn(currentPlayer); + } + } +} \ No newline at end of file diff --git a/src/main/java/course_project/player/Player.java b/src/main/java/course_project/player/Player.java new file mode 100644 index 00000000..129ce9ed --- /dev/null +++ b/src/main/java/course_project/player/Player.java @@ -0,0 +1,28 @@ +package course_project.player; + +import course_project.board.Battlefield; + +public class Player { + + private final boolean isComputer; + private final String name; + private final Battlefield battlefield; + + public Player(String name, boolean isComputer) { + this.isComputer = isComputer; + this.name = name; + this.battlefield = new Battlefield(); + } + + public boolean isComputer() { + return this.isComputer; + } + + public String getName() { + return this.name; + } + + public Battlefield getField() { + return this.battlefield; + } +} diff --git a/src/main/java/course_project/ships/Battleship.java b/src/main/java/course_project/ships/Battleship.java new file mode 100644 index 00000000..45bc6f90 --- /dev/null +++ b/src/main/java/course_project/ships/Battleship.java @@ -0,0 +1,11 @@ +package course_project.ships; + +public final class Battleship extends Ship { + + private static final int SIZE = 4; + private static final String SHIP_NAME = "Battleship"; + + public Battleship() { + super(SIZE, SHIP_NAME); + } +} \ No newline at end of file diff --git a/src/main/java/course_project/ships/Cruiser.java b/src/main/java/course_project/ships/Cruiser.java new file mode 100644 index 00000000..9d50b433 --- /dev/null +++ b/src/main/java/course_project/ships/Cruiser.java @@ -0,0 +1,11 @@ +package course_project.ships; + +public final class Cruiser extends Ship { + + private static final int SIZE = 2; + private static final String SHIP_NAME = "Cruiser"; + + public Cruiser() { + super(SIZE, SHIP_NAME); + } +} \ No newline at end of file diff --git a/src/main/java/course_project/ships/Destroyer.java b/src/main/java/course_project/ships/Destroyer.java new file mode 100644 index 00000000..26d7cb37 --- /dev/null +++ b/src/main/java/course_project/ships/Destroyer.java @@ -0,0 +1,11 @@ +package course_project.ships; + +public final class Destroyer extends Ship { + + private static final int SIZE = 3; + private static final String SHIP_NAME = "Destroyer"; + + public Destroyer() { + super(SIZE, SHIP_NAME); + } +} \ No newline at end of file diff --git a/src/main/java/course_project/ships/PatrolBoat.java b/src/main/java/course_project/ships/PatrolBoat.java new file mode 100644 index 00000000..8cbd5641 --- /dev/null +++ b/src/main/java/course_project/ships/PatrolBoat.java @@ -0,0 +1,11 @@ +package course_project.ships; + +public final class PatrolBoat extends Ship { + + private static final int SIZE = 1; + private static final String SHIP_NAME = "Patrol Boat"; + + public PatrolBoat() { + super(SIZE, SHIP_NAME); + } +} diff --git a/src/main/java/course_project/ships/Ship.java b/src/main/java/course_project/ships/Ship.java new file mode 100644 index 00000000..c4c95a50 --- /dev/null +++ b/src/main/java/course_project/ships/Ship.java @@ -0,0 +1,30 @@ +package course_project.ships; + +public abstract class Ship { + + private final int size; + private final String name; + private int hitCount; + + protected Ship(int size, String shipName) { + this.size = size; + this.name = shipName; + this.hitCount = 0; + } + + public int getSize() { + return this.size; + } + + public String getName() { + return this.name; + } + + public boolean isDestroyed() { + return this.hitCount == this.size; + } + + public void hitCountIncrease() { + this.hitCount++; + } +} diff --git a/src/main/java/course_project/utils/Colors.java b/src/main/java/course_project/utils/Colors.java new file mode 100644 index 00000000..fc1963c6 --- /dev/null +++ b/src/main/java/course_project/utils/Colors.java @@ -0,0 +1,10 @@ +package course_project.utils; + +public final class Colors { + public static final String ANSI_RESET = "\u001B[0m"; + public static final String ANSI_RED = "\033[1;91m"; + public static final String BACKGROUND_CYAN = "\u001B[46m"; + public static final String ANSI_GREEN = "\u001B[32m"; + public static final String ANSI_MAGENTA = "\u001B[35m"; + public static final String ANSI_YELLOW = "\u001B[33m"; +} diff --git a/src/main/java/course_project/utils/RandomDirectionGenerator.java b/src/main/java/course_project/utils/RandomDirectionGenerator.java new file mode 100644 index 00000000..0b9396b3 --- /dev/null +++ b/src/main/java/course_project/utils/RandomDirectionGenerator.java @@ -0,0 +1,9 @@ +package course_project.utils; + +public class RandomDirectionGenerator { + + public static boolean generateRandomDirection() { + return Math.random() <= 0.5; + } + +} diff --git a/src/main/java/course_project/utils/RandomPositionGenerator.java b/src/main/java/course_project/utils/RandomPositionGenerator.java new file mode 100644 index 00000000..395f4b3b --- /dev/null +++ b/src/main/java/course_project/utils/RandomPositionGenerator.java @@ -0,0 +1,11 @@ +package course_project.utils; + +import java.util.Random; + +public class RandomPositionGenerator { + + public static int generateRandomForCell() { + Random random = new Random(); + return random.nextInt(10); + } +} From 655d9049ac2b87fda35b805ccdaa4c931a537ab8 Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Tue, 21 Sep 2021 16:46:50 +0300 Subject: [PATCH 64/69] Edit README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 9f3cb03e..bc5b886f 100644 --- a/README.md +++ b/README.md @@ -2,8 +2,9 @@ ## *Prokofev Ilia* -| Index | Solution | Short description +| Index | Solution | Short description| | :---: | --- | --- | +|**Course Project**|[Sea Battle course project](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/course_project)|Console version of the classic Sea Battle game with graphical representation| | HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_1)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_1/char_count) | The app that reads input arguments and prints them, until "error" argument | |-----| [Traffic Light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_2/traffic_light)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_2/traffic_light) | The app that reads console and calculate current traffic light's color | | HW2 | [Pyramid Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_2/pyramid_printer)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_2/pyramid_printer) | The app that reads console and prints a pyramid based on this | From 3d5a14d2f4bf4499c893cb96d4421ab349240273 Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Tue, 21 Sep 2021 16:47:10 +0300 Subject: [PATCH 65/69] Edit README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bc5b886f..060d4578 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ | Index | Solution | Short description| | :---: | --- | --- | -|**Course Project**|[Sea Battle course project](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/course_project)|Console version of the classic Sea Battle game with graphical representation| +|**Course Project**|[Sea Battle](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/course_project)|Console version of the classic Sea Battle game with graphical representation| | HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_1)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_1/char_count) | The app that reads input arguments and prints them, until "error" argument | |-----| [Traffic Light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_2/traffic_light)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_2/traffic_light) | The app that reads console and calculate current traffic light's color | | HW2 | [Pyramid Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_2/pyramid_printer)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_2/pyramid_printer) | The app that reads console and prints a pyramid based on this | From 0b4857bac3a713ab6c1adf29376ef54163764acb Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Wed, 22 Sep 2021 00:35:43 +0300 Subject: [PATCH 66/69] Edit MapProblemsMutableGenerator --- .../map_problems_generator/MapProblemsMutableGenerator.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/homework_6/map_problems_generator/MapProblemsMutableGenerator.java b/src/main/java/homework_6/map_problems_generator/MapProblemsMutableGenerator.java index 3956948d..c9d45e76 100644 --- a/src/main/java/homework_6/map_problems_generator/MapProblemsMutableGenerator.java +++ b/src/main/java/homework_6/map_problems_generator/MapProblemsMutableGenerator.java @@ -1,5 +1,7 @@ package homework_6.map_problems_generator; +import java.util.Objects; + public class MapProblemsMutableGenerator { private int weight; @@ -18,7 +20,7 @@ public void setWeight(int weight) { @Override public int hashCode() { - return (int)(Math.random() * 50 + 1); + return Objects.hashCode(weight); } @Override From 0d77640ea465e58e881a3708803e8f4942f5f72d Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Wed, 22 Sep 2021 03:11:02 +0300 Subject: [PATCH 67/69] Minor refactoring --- src/main/java/course_project/Main.java | 2 +- src/main/java/course_project/SeaBattle.java | 2 +- src/main/java/course_project/board/Board.java | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/course_project/Main.java b/src/main/java/course_project/Main.java index 59fb35f3..2c694d4b 100644 --- a/src/main/java/course_project/Main.java +++ b/src/main/java/course_project/Main.java @@ -3,6 +3,6 @@ public class Main { public static void main(String[] args) { - SeaBattle.run(); + SeaBattle.initializeGame(); } } diff --git a/src/main/java/course_project/SeaBattle.java b/src/main/java/course_project/SeaBattle.java index 42e4b4ae..c0680377 100644 --- a/src/main/java/course_project/SeaBattle.java +++ b/src/main/java/course_project/SeaBattle.java @@ -4,7 +4,7 @@ final class SeaBattle { - public static void run() { + public static void initializeGame() { Menu.showLogo(); Menu.showGreetings(); Menu.showMainMenu(); diff --git a/src/main/java/course_project/board/Board.java b/src/main/java/course_project/board/Board.java index 0d5a0275..1a81d24b 100644 --- a/src/main/java/course_project/board/Board.java +++ b/src/main/java/course_project/board/Board.java @@ -8,7 +8,7 @@ public class Board { public static final int FIELD_SIZE = 10; private static final String SHIP = ANSI_GREEN + "■" + ANSI_RESET; - private static final String WATER = BACKGROUND_CYAN + " " + ANSI_RESET; + private static final String WATER = "~"; private static final String MISS = ANSI_MAGENTA + "▓" + ANSI_RESET; private static final String HIT = ANSI_YELLOW + "×" + ANSI_RESET; private static final String DESTROY = ANSI_RED + "*" + ANSI_RESET; From 775070cb269f1bf6520eb4c5faf0866312fd0de0 Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Wed, 22 Sep 2021 18:56:57 +0300 Subject: [PATCH 68/69] Delete seriesUp method FIX HW_6 --- .../custom_annotation/HelloGenerator.java | 16 --------------- .../map_problems_generator/Main.java | 11 ++++++++-- .../MapProblemsMutableGenerator.java | 20 ++++++++----------- 3 files changed, 17 insertions(+), 30 deletions(-) diff --git a/src/main/java/homework_4/custom_annotation/HelloGenerator.java b/src/main/java/homework_4/custom_annotation/HelloGenerator.java index 9eef10ae..12ac97af 100644 --- a/src/main/java/homework_4/custom_annotation/HelloGenerator.java +++ b/src/main/java/homework_4/custom_annotation/HelloGenerator.java @@ -11,22 +11,6 @@ public static void main(String args[]) { HelloGenerator helloGenerator1 = new HelloGenerator(null, 5); System.out.println(helloGenerator); System.out.println(helloGenerator1); - seriesUp(3); - } - - public static int[] seriesUp(int n) { - int[] res = new int[n * (n + 1) / 2]; - int index = 0; - - for (int i = 1; i <= n; i++) { - for (int j = 0; j < i; j++) { - res[index + j] = j + 1; - } - index += i; - } - - System.out.println(Arrays.toString(res)); - return res; } @CustomAnnotation diff --git a/src/main/java/homework_6/map_problems_generator/Main.java b/src/main/java/homework_6/map_problems_generator/Main.java index 235535d8..9a2d40fc 100644 --- a/src/main/java/homework_6/map_problems_generator/Main.java +++ b/src/main/java/homework_6/map_problems_generator/Main.java @@ -1,8 +1,15 @@ package homework_6.map_problems_generator; +import java.util.HashMap; + public class Main { public static void main(String[] args) { - new MapProblemsGenerator().makeCollision(); - new MapProblemsGenerator().makeUnreachedObject(); + + HashMap hash = new HashMap(); + MapProblemsMutableGenerator mapProblemsMutableGenerator = new MapProblemsMutableGenerator(50); + hash.put(mapProblemsMutableGenerator, 1); + System.out.println(hash.get(mapProblemsMutableGenerator)); + mapProblemsMutableGenerator.setWeight(25); + System.out.println(hash.get(mapProblemsMutableGenerator)); } } diff --git a/src/main/java/homework_6/map_problems_generator/MapProblemsMutableGenerator.java b/src/main/java/homework_6/map_problems_generator/MapProblemsMutableGenerator.java index c9d45e76..0471a07f 100644 --- a/src/main/java/homework_6/map_problems_generator/MapProblemsMutableGenerator.java +++ b/src/main/java/homework_6/map_problems_generator/MapProblemsMutableGenerator.java @@ -4,30 +4,26 @@ public class MapProblemsMutableGenerator { - private int weight; + private int weight; public MapProblemsMutableGenerator(int weight) { this.weight = weight; } - public int getWeight() { - return weight; - } - public void setWeight(int weight) { this.weight = weight; } @Override - public int hashCode() { - return Objects.hashCode(weight); + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + MapProblemsMutableGenerator that = (MapProblemsMutableGenerator) o; + return weight == that.weight; } @Override - public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null || getClass() != obj.getClass()) return false; - MapProblemsMutableGenerator newObj = (MapProblemsMutableGenerator) obj; - return weight == newObj.weight; + public int hashCode() { + return Objects.hash(weight); } } From 77a16b2824004964a48123b35e7241ad1da837f9 Mon Sep 17 00:00:00 2001 From: bttrthnubtch Date: Thu, 23 Sep 2021 00:10:42 +0300 Subject: [PATCH 69/69] FIX HW_3 --- .../java/homework_3/ImmutableClassMan.java | 62 ++++++++++--------- .../map_problems_generator/Main.java | 8 +-- 2 files changed, 37 insertions(+), 33 deletions(-) diff --git a/src/main/java/homework_3/ImmutableClassMan.java b/src/main/java/homework_3/ImmutableClassMan.java index 18a3a731..f87ab8f9 100644 --- a/src/main/java/homework_3/ImmutableClassMan.java +++ b/src/main/java/homework_3/ImmutableClassMan.java @@ -13,50 +13,54 @@ 6. A parameterized constructor should initialize all the fields performing a deep copy (So that data members can’t be modified with object reference). */ +import java.util.ArrayList; +import java.util.List; + public final class ImmutableClassMan { private final int age; private final String name; - private final Integer iq; - - public ImmutableClassMan(int age, String name, Integer iq) { - this.age = age; - this.name = name; - this.iq = new Integer(iq); - } + private final ArrayList job; - public ImmutableClassMan(int age, String name) { - this.age = age; - this.name = name; - this.iq = new Integer(null); + public int getAge() { + return age; } - public ImmutableClassMan(int age) { - this.age = age; - this.name = ""; - this.iq = null; + public String getName() { + return name; } - public ImmutableClassMan() { - this.age = 6; - this.name = "Ivan"; - this.iq = new Integer(128); + public List getJob() { + if (job != null){ + return new ArrayList<>(job); + } + return new ArrayList<>(); } - - public int getAge() { - return this.age; + public ImmutableClassMan(int age, String name, List job) { + this.age = age; + this.name = name; + this.job = new ArrayList<>(job); } - public String getName() { - return this.name; + public ImmutableClassMan(int age, String name) { + this.age = age; + this.name = name; + this.job = null; } - public Integer getIq() { - return this.iq; + public ImmutableClassMan addNewJob (String job){ + List newList = getJob(); + newList.add(job); + return new ImmutableClassMan(age, name, newList); } - public ImmutableClassMan returnModifyMan(Integer iq) { - return new ImmutableClassMan(age, name, iq); + @Override + public String toString() { + return "ImmutableClassMan{" + + "age=" + age + + ", name='" + name + '\'' + + ", job=" + job + + '}'; } -} +} \ No newline at end of file diff --git a/src/main/java/homework_6/map_problems_generator/Main.java b/src/main/java/homework_6/map_problems_generator/Main.java index 9a2d40fc..1b033b13 100644 --- a/src/main/java/homework_6/map_problems_generator/Main.java +++ b/src/main/java/homework_6/map_problems_generator/Main.java @@ -5,11 +5,11 @@ public class Main { public static void main(String[] args) { - HashMap hash = new HashMap(); + HashMap map = new HashMap(); MapProblemsMutableGenerator mapProblemsMutableGenerator = new MapProblemsMutableGenerator(50); - hash.put(mapProblemsMutableGenerator, 1); - System.out.println(hash.get(mapProblemsMutableGenerator)); + map.put(mapProblemsMutableGenerator, 1); + System.out.println(map.get(mapProblemsMutableGenerator)); mapProblemsMutableGenerator.setWeight(25); - System.out.println(hash.get(mapProblemsMutableGenerator)); + System.out.println(map.get(mapProblemsMutableGenerator)); } }