From 63e147fc20854c8b4fb061a595cfcfb0fc1ab51c Mon Sep 17 00:00:00 2001 From: krishnom Date: Sat, 19 Oct 2019 16:06:39 +0530 Subject: [PATCH 01/19] Update README.md --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index 9bd523c..09e20c9 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,6 @@ +https://travis-ci.org/Krishnom/UdemyJavaCourse.svg?branch=master + + # UdemyJavaCourse Course related code From 6a7edf8550f6a71bc8fdf2dd227a0c5965110c56 Mon Sep 17 00:00:00 2001 From: krishnom Date: Sat, 19 Oct 2019 16:08:45 +0530 Subject: [PATCH 02/19] Updated README to show CI build status --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 09e20c9..150c1f0 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -https://travis-ci.org/Krishnom/UdemyJavaCourse.svg?branch=master +[![Build Status](https://travis-ci.org/Krishnom/UdemyJavaCourse.svg?branch=master)](https://travis-ci.org/Krishnom/UdemyJavaCourse) # UdemyJavaCourse From 5b1e5765b994d40eff30096ddd985d363662bf3a Mon Sep 17 00:00:00 2001 From: Dinesh Date: Mon, 28 Oct 2019 22:13:47 +0530 Subject: [PATCH 03/19] Update NumberOfDaysInMonth.java --- Section5/src/main/java/exercise13/NumberOfDaysInMonth.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Section5/src/main/java/exercise13/NumberOfDaysInMonth.java b/Section5/src/main/java/exercise13/NumberOfDaysInMonth.java index 703f301..1ab6795 100644 --- a/Section5/src/main/java/exercise13/NumberOfDaysInMonth.java +++ b/Section5/src/main/java/exercise13/NumberOfDaysInMonth.java @@ -39,6 +39,6 @@ public static int getDaysInMonth(int month, int year) { } private static boolean isaValidYear(int year) { - return year < 1 || year > 9999; + return year < 0 || year > 9999; } -} \ No newline at end of file +} From bf6877bac8ebfc8e51f8667ca92dd4e2585952c0 Mon Sep 17 00:00:00 2001 From: Om Paliwal Date: Sat, 2 Nov 2019 23:56:31 +0530 Subject: [PATCH 04/19] Section 9 code --- .idea/compiler.xml | 31 +++++ .idea/encodings.xml | 14 +++ .idea/gradle.xml | 4 + ..._org_apiguardian_apiguardian_api_1_1_0.xml | 13 ++ ..._org_junit_jupiter_junit_jupiter_5_5_2.xml | 13 ++ ..._junit_jupiter_junit_jupiter_api_5_5_2.xml | 13 ++ ...nit_jupiter_junit_jupiter_engine_5_5_2.xml | 13 ++ ...nit_jupiter_junit_jupiter_params_5_5_2.xml | 13 ++ ..._platform_junit_platform_commons_1_5_2.xml | 13 ++ ...t_platform_junit_platform_engine_1_5_2.xml | 13 ++ ...Maven__org_opentest4j_opentest4j_1_2_0.xml | 13 ++ .idea/misc.xml | 19 +++ .idea/modules.xml | 2 + Root.iml | 10 +- Section3/Section3.iml | 8 ++ Section3/pom.xml | 31 +---- Section4/Section4.iml | 4 +- Section4/pom.xml | 54 +-------- Section5/Section5.iml | 8 +- Section5/pom.xml | 39 +----- Section6/pom.xml | 38 +----- Section7/Section7.iml | 8 ++ Section7/pom.xml | 32 +---- Section8/pom.xml | 29 +---- Section9/Section9.iml | 22 ++++ Section9/pom.xml | 16 +++ .../java/challenge/innerclass/Albums.java | 112 ++++++++++++++++++ .../java/challenge/innerclass/AlbumsMain.java | 97 +++++++++++++++ .../main/java/challenge/innerclass/Song.java | 31 +++++ .../java/challenge/interfaces/ISaveable.java | 9 ++ .../main/java/challenge/interfaces/Main.java | 58 +++++++++ .../java/challenge/interfaces/Monster.java | 55 +++++++++ .../java/challenge/interfaces/Player.java | 67 +++++++++++ .../main/java/example/innerclass/Button.java | 26 ++++ .../main/java/example/innerclass/Main.java | 40 +++++++ .../challenge/interfaces/MonsterTest.java | 22 ++++ pom.xml | 25 ++++ 37 files changed, 816 insertions(+), 199 deletions(-) create mode 100644 .idea/compiler.xml create mode 100644 .idea/encodings.xml create mode 100644 .idea/gradle.xml create mode 100644 .idea/libraries/Maven__org_apiguardian_apiguardian_api_1_1_0.xml create mode 100644 .idea/libraries/Maven__org_junit_jupiter_junit_jupiter_5_5_2.xml create mode 100644 .idea/libraries/Maven__org_junit_jupiter_junit_jupiter_api_5_5_2.xml create mode 100644 .idea/libraries/Maven__org_junit_jupiter_junit_jupiter_engine_5_5_2.xml create mode 100644 .idea/libraries/Maven__org_junit_jupiter_junit_jupiter_params_5_5_2.xml create mode 100644 .idea/libraries/Maven__org_junit_platform_junit_platform_commons_1_5_2.xml create mode 100644 .idea/libraries/Maven__org_junit_platform_junit_platform_engine_1_5_2.xml create mode 100644 .idea/libraries/Maven__org_opentest4j_opentest4j_1_2_0.xml create mode 100644 Section9/Section9.iml create mode 100644 Section9/pom.xml create mode 100644 Section9/src/main/java/challenge/innerclass/Albums.java create mode 100644 Section9/src/main/java/challenge/innerclass/AlbumsMain.java create mode 100644 Section9/src/main/java/challenge/innerclass/Song.java create mode 100644 Section9/src/main/java/challenge/interfaces/ISaveable.java create mode 100644 Section9/src/main/java/challenge/interfaces/Main.java create mode 100644 Section9/src/main/java/challenge/interfaces/Monster.java create mode 100644 Section9/src/main/java/challenge/interfaces/Player.java create mode 100644 Section9/src/main/java/example/innerclass/Button.java create mode 100644 Section9/src/main/java/example/innerclass/Main.java create mode 100644 Section9/src/test/challenge/interfaces/MonsterTest.java diff --git a/.idea/compiler.xml b/.idea/compiler.xml new file mode 100644 index 0000000..be80161 --- /dev/null +++ b/.idea/compiler.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/encodings.xml b/.idea/encodings.xml new file mode 100644 index 0000000..d3156f6 --- /dev/null +++ b/.idea/encodings.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/gradle.xml b/.idea/gradle.xml new file mode 100644 index 0000000..3e3960b --- /dev/null +++ b/.idea/gradle.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/.idea/libraries/Maven__org_apiguardian_apiguardian_api_1_1_0.xml b/.idea/libraries/Maven__org_apiguardian_apiguardian_api_1_1_0.xml new file mode 100644 index 0000000..f854ab0 --- /dev/null +++ b/.idea/libraries/Maven__org_apiguardian_apiguardian_api_1_1_0.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/Maven__org_junit_jupiter_junit_jupiter_5_5_2.xml b/.idea/libraries/Maven__org_junit_jupiter_junit_jupiter_5_5_2.xml new file mode 100644 index 0000000..5db0740 --- /dev/null +++ b/.idea/libraries/Maven__org_junit_jupiter_junit_jupiter_5_5_2.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/Maven__org_junit_jupiter_junit_jupiter_api_5_5_2.xml b/.idea/libraries/Maven__org_junit_jupiter_junit_jupiter_api_5_5_2.xml new file mode 100644 index 0000000..8fbc8ce --- /dev/null +++ b/.idea/libraries/Maven__org_junit_jupiter_junit_jupiter_api_5_5_2.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/Maven__org_junit_jupiter_junit_jupiter_engine_5_5_2.xml b/.idea/libraries/Maven__org_junit_jupiter_junit_jupiter_engine_5_5_2.xml new file mode 100644 index 0000000..cca5485 --- /dev/null +++ b/.idea/libraries/Maven__org_junit_jupiter_junit_jupiter_engine_5_5_2.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/Maven__org_junit_jupiter_junit_jupiter_params_5_5_2.xml b/.idea/libraries/Maven__org_junit_jupiter_junit_jupiter_params_5_5_2.xml new file mode 100644 index 0000000..e2713d0 --- /dev/null +++ b/.idea/libraries/Maven__org_junit_jupiter_junit_jupiter_params_5_5_2.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/Maven__org_junit_platform_junit_platform_commons_1_5_2.xml b/.idea/libraries/Maven__org_junit_platform_junit_platform_commons_1_5_2.xml new file mode 100644 index 0000000..4192cdc --- /dev/null +++ b/.idea/libraries/Maven__org_junit_platform_junit_platform_commons_1_5_2.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/Maven__org_junit_platform_junit_platform_engine_1_5_2.xml b/.idea/libraries/Maven__org_junit_platform_junit_platform_engine_1_5_2.xml new file mode 100644 index 0000000..cbbd9b7 --- /dev/null +++ b/.idea/libraries/Maven__org_junit_platform_junit_platform_engine_1_5_2.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/Maven__org_opentest4j_opentest4j_1_2_0.xml b/.idea/libraries/Maven__org_opentest4j_opentest4j_1_2_0.xml new file mode 100644 index 0000000..fbc1b16 --- /dev/null +++ b/.idea/libraries/Maven__org_opentest4j_opentest4j_1_2_0.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml index a90a6f9..7099446 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -3,6 +3,25 @@ + + + + diff --git a/.idea/modules.xml b/.idea/modules.xml index d54e8c9..299b63d 100644 --- a/.idea/modules.xml +++ b/.idea/modules.xml @@ -2,12 +2,14 @@ + + \ No newline at end of file diff --git a/Root.iml b/Root.iml index 4fd5057..346cf8b 100644 --- a/Root.iml +++ b/Root.iml @@ -1,6 +1,6 @@ - + @@ -8,5 +8,13 @@ + + + + + + + + \ No newline at end of file diff --git a/Section3/Section3.iml b/Section3/Section3.iml index 08c1eba..f07e6a5 100644 --- a/Section3/Section3.iml +++ b/Section3/Section3.iml @@ -11,5 +11,13 @@ + + + + + + + + \ No newline at end of file diff --git a/Section3/pom.xml b/Section3/pom.xml index 5f59628..c9a3ab7 100644 --- a/Section3/pom.xml +++ b/Section3/pom.xml @@ -4,31 +4,10 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - udemyjavacourse + + udemyjavacourse + JavaUdemyCourse + 0.0.1 + Section3 - 0.0.1 - - - - UTF-8 - 11 - 11 - - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - 3.0.0-M3 - - - some test to exclude here - - - - - \ No newline at end of file diff --git a/Section4/Section4.iml b/Section4/Section4.iml index 2ee8fba..5cc9145 100644 --- a/Section4/Section4.iml +++ b/Section4/Section4.iml @@ -10,13 +10,13 @@ + - + - \ No newline at end of file diff --git a/Section4/pom.xml b/Section4/pom.xml index 1262ee9..7698eee 100644 --- a/Section4/pom.xml +++ b/Section4/pom.xml @@ -3,54 +3,10 @@ xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - - udemyjavacourse + + udemyjavacourse + JavaUdemyCourse + 0.0.1 + Section4 - 0.0.1 - - UTF-8 - 11 - 11 - - - - org.junit.jupiter - junit-jupiter-api - 5.5.2 - test - - - org.junit.jupiter - junit-jupiter - 5.5.2 - test - - - org.junit.jupiter - junit-jupiter-engine - 5.5.2 - test - - - org.junit.jupiter - junit-jupiter-params - 5.5.2 - test - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - 3.0.0-M3 - - - some test to exclude here - - - - - \ No newline at end of file diff --git a/Section5/Section5.iml b/Section5/Section5.iml index fed7c58..5cc9145 100644 --- a/Section5/Section5.iml +++ b/Section5/Section5.iml @@ -10,11 +10,13 @@ - - + + - + + + \ No newline at end of file diff --git a/Section5/pom.xml b/Section5/pom.xml index f914a20..7f01a5b 100644 --- a/Section5/pom.xml +++ b/Section5/pom.xml @@ -3,39 +3,10 @@ xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - - udemyjavacourse + + udemyjavacourse + JavaUdemyCourse + 0.0.1 + Section5 - 0.0.1 - - - - UTF-8 - 11 - 11 - - - - org.junit.jupiter - junit-jupiter-params - 5.5.2 - test - - - udemyjavacourse - Section4 - 0.0.1 - test - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - 3.0.0-M3 - - - \ No newline at end of file diff --git a/Section6/pom.xml b/Section6/pom.xml index 3289046..14e054e 100644 --- a/Section6/pom.xml +++ b/Section6/pom.xml @@ -3,38 +3,10 @@ xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - - udemyjavacourse + + udemyjavacourse + JavaUdemyCourse + 0.0.1 + Section6 - 0.0.1 - - - - UTF-8 - 11 - 11 - - - - org.junit.jupiter - junit-jupiter - 5.5.2 - test - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - 3.0.0-M3 - - - some test to exclude here - - - - - \ No newline at end of file diff --git a/Section7/Section7.iml b/Section7/Section7.iml index 1e3fe72..5cc9145 100644 --- a/Section7/Section7.iml +++ b/Section7/Section7.iml @@ -10,5 +10,13 @@ + + + + + + + + \ No newline at end of file diff --git a/Section7/pom.xml b/Section7/pom.xml index ebc6354..85f59c1 100644 --- a/Section7/pom.xml +++ b/Section7/pom.xml @@ -3,32 +3,10 @@ xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - - udemyjavacourse + + udemyjavacourse + JavaUdemyCourse + 0.0.1 + Section7 - 0.0.1 - - - - UTF-8 - 11 - 11 - - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - 3.0.0-M3 - - - some test to exclude here - - - - - \ No newline at end of file diff --git a/Section8/pom.xml b/Section8/pom.xml index c5aca75..a4846a7 100644 --- a/Section8/pom.xml +++ b/Section8/pom.xml @@ -4,29 +4,10 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - udemyjavacourse + + udemyjavacourse + JavaUdemyCourse + 0.0.1 + Section8 - 0.0.1 - - - org.junit.jupiter - junit-jupiter - 5.5.2 - test - - - - UTF-8 - 11 - 11 - - - - - org.apache.maven.plugins - maven-surefire-plugin - 3.0.0-M3 - - - \ No newline at end of file diff --git a/Section9/Section9.iml b/Section9/Section9.iml new file mode 100644 index 0000000..0789ae0 --- /dev/null +++ b/Section9/Section9.iml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Section9/pom.xml b/Section9/pom.xml new file mode 100644 index 0000000..a46b321 --- /dev/null +++ b/Section9/pom.xml @@ -0,0 +1,16 @@ + + + 4.0.0 + + + udemyjavacourse + JavaUdemyCourse + 0.0.1 + + + Section9 + + + \ No newline at end of file diff --git a/Section9/src/main/java/challenge/innerclass/Albums.java b/Section9/src/main/java/challenge/innerclass/Albums.java new file mode 100644 index 0000000..360c81f --- /dev/null +++ b/Section9/src/main/java/challenge/innerclass/Albums.java @@ -0,0 +1,112 @@ +package challenge.innerclass; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.ListIterator; + +public class Albums { + private SongList songList = new SongList(); + private String artist; + + public Albums(String artist) { + this.artist = artist; + addSong(new Song("Kesariya Balam", 2.10)); + addSong(new Song("Kawaron Tabariyo", 5.09)); + addSong(new Song("Jad Dekhu Banne Ri Lal Pili Ankhyan", 4.27)); + addSong(new Song("Ghoomar", 4.20)); + } + + /** + * @param trackNumber track number of song starting from 1 + * @param playlist playlist where song from album needs to be added + */ + void addSongToPlaylist(int trackNumber, LinkedList playlist) { + int index = trackNumber - 1; + if (index >= 0 && (trackNumber <= songList.getSize())) { + Song songToAdd = songList.getSongNumber(index); + playlist.add(songToAdd); + System.out.println("Added to playlist " + songToAdd.toString()); + } else { + System.out.println("Track no " + trackNumber + " doesn't exists.\n" + + "Here are list of songs you can add"); + printListOfSongs(); + } + } + + public boolean addSong(Song song) { + if (!songList.find(song.getTitle())) { + songList.add(song); + System.out.println("Added " + song.toString()); + return true; + } + System.out.println("Song" + song.getTitle() + " already exist in album"); + return false; + } + + public void printListOfSongs() { + songList.printList(); + } + + + public void removeSongFromAlbum(String title) { + if (songList.remove(title)) { + System.out.println("Song " + title + " removed from album " + title); + } else { + System.out.println("Song with title \"" + title + "\" not found in album " + artist); + } + } + + private class SongList { + private ArrayList songs = new ArrayList<>(); + + private int getSize() { + return songs.size(); + } + + private Song getSongNumber(int titleNumber) { + return songs.get(titleNumber); + } + + public boolean add(String title, double duration) { + if (find(title)) { + System.out.println("Song with title " + title + " already present. Skipping duplicate entry"); + return false; + } + return songs.add(new Song(title, duration)); + } + + public boolean remove(String title) { + if (!find(title)) { + return false; + } + + ListIterator listIterator = songs.listIterator(); + while (listIterator.hasNext()) { + if (listIterator.next().getTitle().equals(title)) { + listIterator.remove(); + return true; + } + } + return false; + } + + public boolean find(String title) { + for (Song song : songs) { + if (song.getTitle().equals(title)) { + return true; + } + } + return false; + } + + public boolean add(Song song) { + return add(song.getTitle(), song.getDurationInSeconds()); + } + + public void printList() { + int i = 0; + for (Song song : songs) + System.out.println((++i) + ": " + song.toString()); + } + } +} \ No newline at end of file diff --git a/Section9/src/main/java/challenge/innerclass/AlbumsMain.java b/Section9/src/main/java/challenge/innerclass/AlbumsMain.java new file mode 100644 index 0000000..684b083 --- /dev/null +++ b/Section9/src/main/java/challenge/innerclass/AlbumsMain.java @@ -0,0 +1,97 @@ +package challenge.innerclass; + +import java.util.LinkedList; +import java.util.ListIterator; +import java.util.Scanner; + +public class AlbumsMain { + private static LinkedList playlist = new LinkedList<>(); + private static Albums ghoomar = new Albums("Ghoomer"); + private static boolean goingForward = true; + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + boolean quit = false; + ghoomar.addSongToPlaylist(1, playlist); + ghoomar.addSongToPlaylist(2, playlist); + ghoomar.addSongToPlaylist(3, playlist); + ghoomar.addSongToPlaylist(4, playlist); + ghoomar.addSongToPlaylist(5, playlist); + + ListIterator playlistIterator = playlist.listIterator(); + while (!quit) { + printMenu(); + System.out.print("Enter a choice from menu: "); + int option = scanner.nextInt(); + scanner.nextLine();//ignore new line + switch (option) { + case 1: + case 5: + System.out.println("Not implemented yet"); + break; + case 2: + if (goingForward) { + if (playlistIterator.hasNext()) { + playlistIterator.next().playSong(); + } + } else { + if (playlistIterator.hasPrevious()) { + playlistIterator.previous().playSong(); + } + } + break; + case 3: + if (!goingForward) { + if (playlistIterator.hasNext()) { + playlistIterator.next(); + } + goingForward = true; + } + + if (playlistIterator.hasNext()) { + playlistIterator.next().playSong(); + } else { + System.out.println("Reached at the end of playlist"); + } + break; + case 4: + if (goingForward) { + if (playlistIterator.hasPrevious()) { + playlistIterator.previous(); + } + goingForward = false; + } + + if (playlistIterator.hasPrevious()) { + playlistIterator.previous().playSong(); + } else { + System.out.println("Reached at the top of playlist"); + } + break; + case 6: + printPlaylistItems(playlist); + break; + case 7: + quit = true; + break; + } + } + } + + private static void printPlaylistItems(LinkedList playlist) { + int i = 0; + for (Song song : playlist) { + System.out.println((++i) + ". " + song.toString()); + } + } + + private static void printMenu() { + System.out.println("1:\tAdd Track to playlist\n" + + "2:\tSkip Song\n" + + "3:\tNext Song\n" + + "4:\tPrevious Song\n" + + "5:\tRemove a Song\n" + + "6:\tList All Songs\n" + + "7:\tQuit\n"); + } +} diff --git a/Section9/src/main/java/challenge/innerclass/Song.java b/Section9/src/main/java/challenge/innerclass/Song.java new file mode 100644 index 0000000..635368a --- /dev/null +++ b/Section9/src/main/java/challenge/innerclass/Song.java @@ -0,0 +1,31 @@ +package challenge.innerclass; + +public class Song { + private String title; + private double durationInSeconds; + + public Song(String title, double durationInSeconds) { + this.title = title; + this.durationInSeconds = durationInSeconds; + } + + public double getDurationInSeconds() { + return durationInSeconds; + } + + @Override + public String toString() { + return "Song{" + + "title='" + title + '\'' + + ", durationInSeconds=" + durationInSeconds + + '}'; + } + + public void playSong() { + System.out.println("Playing " + title); + } + + public String getTitle() { + return title; + } +} diff --git a/Section9/src/main/java/challenge/interfaces/ISaveable.java b/Section9/src/main/java/challenge/interfaces/ISaveable.java new file mode 100644 index 0000000..527b7d6 --- /dev/null +++ b/Section9/src/main/java/challenge/interfaces/ISaveable.java @@ -0,0 +1,9 @@ +package challenge.interfaces; + +import java.util.List; + +public interface ISaveable { + void read(List savedObject); + + List write(); +} diff --git a/Section9/src/main/java/challenge/interfaces/Main.java b/Section9/src/main/java/challenge/interfaces/Main.java new file mode 100644 index 0000000..61080b9 --- /dev/null +++ b/Section9/src/main/java/challenge/interfaces/Main.java @@ -0,0 +1,58 @@ +package challenge.interfaces; + +import java.util.List; + +public class Main { + public static void main(String[] args) { + Player player = new Player("Krishnom", 100, "Desert Eagle"); + + List state1 = saveState(player); + player.setWeapon("AK-47"); + player.setHealth(18); + List state2 = saveState(player); + + player.setHealth(80); + player.setWeapon("AWM"); + + System.out.println(player); + loadState(player, state1); + System.out.println(player); + loadState(player, state2); + System.out.println(player); + + + Monster monster = new Monster("Vampire", 200, 100); + + //Monster got attacked + monster.setHealth(80); + monster.setStrength(160); + state1 = saveState(monster); + + //Monster got a fatal attack + monster.setHealth(10); + monster.setStrength(0); + state2 = saveState(monster); + + loadState(monster, state1); + System.out.println(monster); + loadState(monster, state2); + System.out.println(monster); + + } + + private static void loadState(ISaveable saveable, List state1) { + saveable.read(state1); + } + + private static List saveState(ISaveable saveableObject) { + if (saveableObject != null) { + System.out.println("Saving state " + saveableObject.toString()); + return saveableObject.write(); + } else { + System.out.println("Cannot save state for this object"); + return null; + } + } + + +} diff --git a/Section9/src/main/java/challenge/interfaces/Monster.java b/Section9/src/main/java/challenge/interfaces/Monster.java new file mode 100644 index 0000000..0bbb631 --- /dev/null +++ b/Section9/src/main/java/challenge/interfaces/Monster.java @@ -0,0 +1,55 @@ +package challenge.interfaces; + +import java.util.ArrayList; +import java.util.List; + +public class Monster implements ISaveable { + private String name; + private int strength; + private int health; + + public Monster(String name, int strength, int health) { + this.name = name; + this.strength = strength; + this.health = health; + } + + public void setName(String name) { + this.name = name; + } + + public void setStrength(int strength) { + this.strength = strength; + } + + public void setHealth(int health) { + this.health = health; + } + + @Override + public String toString() { + return "Monster{" + + "strength=" + strength + + ", health=" + health + + ", name='" + name + '\'' + + '}'; + } + + @Override + public void read(List savedObject) { + if (savedObject != null && (!savedObject.isEmpty())) { + this.name = savedObject.get(0); + this.strength = Integer.parseInt(savedObject.get(1)); + this.health = Integer.parseInt(savedObject.get(2)); + } + } + + @Override + public List write() { + ArrayList savePoint = new ArrayList<>(); + savePoint.add(0, name); + savePoint.add(1, String.valueOf(strength)); + savePoint.add(2, String.valueOf(health)); + return savePoint; + } +} diff --git a/Section9/src/main/java/challenge/interfaces/Player.java b/Section9/src/main/java/challenge/interfaces/Player.java new file mode 100644 index 0000000..b3ea420 --- /dev/null +++ b/Section9/src/main/java/challenge/interfaces/Player.java @@ -0,0 +1,67 @@ +package challenge.interfaces; + +import java.util.ArrayList; +import java.util.List; + +public class Player implements ISaveable { + private String name; + private int health; + private String weapon; + + public Player(String name, int health, String weapon) { + this.name = name; + this.health = health; + this.weapon = weapon; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getWeapon() { + return weapon; + } + + public void setWeapon(String weapon) { + this.weapon = weapon; + } + + public int getHealth() { + return health; + } + + public void setHealth(int health) { + this.health = health; + } + + @Override + public String toString() { + return "Player{" + + "name='" + name + '\'' + + ", health=" + health + + ", weapon='" + weapon + '\'' + + '}'; + } + + @Override + public void read(List savedObject) { + if (savedObject != null && (!savedObject.isEmpty())) { + this.name = savedObject.get(0); + this.health = Integer.parseInt(savedObject.get(1)); + this.weapon = savedObject.get(2); + } + } + + @Override + public List write() { + List savedState = new ArrayList<>(); + savedState.add(0, name); + savedState.add(1, String.valueOf(health)); + savedState.add(2, weapon); + return savedState; + } +} diff --git a/Section9/src/main/java/example/innerclass/Button.java b/Section9/src/main/java/example/innerclass/Button.java new file mode 100644 index 0000000..12fdc8c --- /dev/null +++ b/Section9/src/main/java/example/innerclass/Button.java @@ -0,0 +1,26 @@ +package example.innerclass; + +public class Button { + private String title; + private OnClickListener onClickListener; + + public Button(String title) { + this.title = title; + } + + public String getTitle() { + return title; + } + + public void setOnClickListener(OnClickListener onClickListener) { + this.onClickListener = onClickListener; + } + + public void onClick() { + onClickListener.onClick(this.title); + } + + public interface OnClickListener { + void onClick(String title); + } +} diff --git a/Section9/src/main/java/example/innerclass/Main.java b/Section9/src/main/java/example/innerclass/Main.java new file mode 100644 index 0000000..b360a37 --- /dev/null +++ b/Section9/src/main/java/example/innerclass/Main.java @@ -0,0 +1,40 @@ +package example.innerclass; + +import java.util.Scanner; + +public class Main { + static Scanner scanner = new Scanner(System.in); + static Button button = new Button("Print"); + + public static void main(String[] args) { + button.setOnClickListener(new Button.OnClickListener() { + @Override + public void onClick(String title) { + System.out.println(title + " button clicked"); + } + }); + + start(); + } + + private static void start() { + boolean quit = false; + System.out.println("1. Click button\n2. Quit"); + while (!quit) { + System.out.print("Enter Choice: "); + int option = scanner.nextInt(); + scanner.nextLine(); + switch (option) { + case 1: + button.onClick(); + break; + case 2: + quit = true; + break; + default: + System.out.println("Invalid option"); + break; + } + } + } +} diff --git a/Section9/src/test/challenge/interfaces/MonsterTest.java b/Section9/src/test/challenge/interfaces/MonsterTest.java new file mode 100644 index 0000000..5c374ea --- /dev/null +++ b/Section9/src/test/challenge/interfaces/MonsterTest.java @@ -0,0 +1,22 @@ +package challenge.interfaces; + +import org.junit.jupiter.api.Test; + +import java.util.List; + +class MonsterTest { + + @Test + void whenSavedStateIsLoadedPlayerMovesBackToThatState() { + Player aplayer = new Player("Ethen", 100, "AK-47"); + aplayer.setHealth(94); + List savedState = aplayer.write(); //save state + + //lets change player's health and weapons + aplayer.setHealth(10); + aplayer.setWeapon("AWM"); + + aplayer.read(savedState); + + } +} \ No newline at end of file diff --git a/pom.xml b/pom.xml index 2059ca4..8dc548e 100644 --- a/pom.xml +++ b/pom.xml @@ -16,5 +16,30 @@ Section6 Section7 Section8 + Section9 + + + + + org.junit.jupiter + junit-jupiter + 5.5.2 + test + + + + UTF-8 + 11 + 11 + + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.0.0-M3 + + + \ No newline at end of file From f94ece10516b1ff892d293255b0a1a6b95615b4c Mon Sep 17 00:00:00 2001 From: Om Paliwal Date: Sun, 3 Nov 2019 09:05:56 +0530 Subject: [PATCH 05/19] ignoring .class files and target folder --- .gitignore | 2 ++ Section9/Section9.iml | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 6a3417b..eab9e4a 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,3 @@ /out/ +*.class +target/ diff --git a/Section9/Section9.iml b/Section9/Section9.iml index 0789ae0..5cc9145 100644 --- a/Section9/Section9.iml +++ b/Section9/Section9.iml @@ -5,7 +5,7 @@ - + From 57765e72c751b10b8ebb0622d1bce3c4a689773c Mon Sep 17 00:00:00 2001 From: Om Paliwal Date: Sun, 3 Nov 2019 09:25:01 +0530 Subject: [PATCH 06/19] Updated .gitignore file to not include idea project files. --- .gitignore | 9 +- .idea/.gitignore | 2 - .idea/compiler.xml | 31 ----- .idea/dictionaries/opaliwal.xml | 15 --- .idea/encodings.xml | 14 -- .idea/gradle.xml | 4 - ..._org_apiguardian_apiguardian_api_1_1_0.xml | 13 -- ..._org_junit_jupiter_junit_jupiter_5_5_2.xml | 13 -- ..._junit_jupiter_junit_jupiter_api_5_5_2.xml | 13 -- ...nit_jupiter_junit_jupiter_engine_5_5_2.xml | 13 -- ...nit_jupiter_junit_jupiter_params_5_5_2.xml | 13 -- ..._platform_junit_platform_commons_1_5_2.xml | 13 -- ...t_platform_junit_platform_engine_1_5_2.xml | 13 -- ...Maven__org_opentest4j_opentest4j_1_2_0.xml | 13 -- .idea/misc.xml | 28 ---- .idea/modules.xml | 15 --- .idea/uiDesigner.xml | 124 ------------------ .idea/vcs.xml | 6 - Root.iml | 20 --- Section3/Section3.iml | 23 ---- Section4/Section4.iml | 22 ---- Section5/Section5.iml | 22 ---- Section6/Section6.iml | 22 ---- Section7/Section7.iml | 22 ---- Section8/Section8.iml | 22 ---- Section9/Section9.iml | 22 ---- 26 files changed, 7 insertions(+), 520 deletions(-) delete mode 100644 .idea/.gitignore delete mode 100644 .idea/compiler.xml delete mode 100644 .idea/dictionaries/opaliwal.xml delete mode 100644 .idea/encodings.xml delete mode 100644 .idea/gradle.xml delete mode 100644 .idea/libraries/Maven__org_apiguardian_apiguardian_api_1_1_0.xml delete mode 100644 .idea/libraries/Maven__org_junit_jupiter_junit_jupiter_5_5_2.xml delete mode 100644 .idea/libraries/Maven__org_junit_jupiter_junit_jupiter_api_5_5_2.xml delete mode 100644 .idea/libraries/Maven__org_junit_jupiter_junit_jupiter_engine_5_5_2.xml delete mode 100644 .idea/libraries/Maven__org_junit_jupiter_junit_jupiter_params_5_5_2.xml delete mode 100644 .idea/libraries/Maven__org_junit_platform_junit_platform_commons_1_5_2.xml delete mode 100644 .idea/libraries/Maven__org_junit_platform_junit_platform_engine_1_5_2.xml delete mode 100644 .idea/libraries/Maven__org_opentest4j_opentest4j_1_2_0.xml delete mode 100644 .idea/misc.xml delete mode 100644 .idea/modules.xml delete mode 100644 .idea/uiDesigner.xml delete mode 100644 .idea/vcs.xml delete mode 100644 Root.iml delete mode 100644 Section3/Section3.iml delete mode 100644 Section4/Section4.iml delete mode 100644 Section5/Section5.iml delete mode 100644 Section6/Section6.iml delete mode 100644 Section7/Section7.iml delete mode 100644 Section8/Section8.iml delete mode 100644 Section9/Section9.iml diff --git a/.gitignore b/.gitignore index eab9e4a..812fe7f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,8 @@ -/out/ -*.class target/ +*.class +*.jar +*.war +*.ear +*.logs +*.iml +.idea/ \ No newline at end of file diff --git a/.idea/.gitignore b/.idea/.gitignore deleted file mode 100644 index 5c98b42..0000000 --- a/.idea/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -# Default ignored files -/workspace.xml \ No newline at end of file diff --git a/.idea/compiler.xml b/.idea/compiler.xml deleted file mode 100644 index be80161..0000000 --- a/.idea/compiler.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/dictionaries/opaliwal.xml b/.idea/dictionaries/opaliwal.xml deleted file mode 100644 index 9493df9..0000000 --- a/.idea/dictionaries/opaliwal.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - activa - asus - maruti - omprakash - paliwal - scooty - upto - xtreme - zebronix - - - \ No newline at end of file diff --git a/.idea/encodings.xml b/.idea/encodings.xml deleted file mode 100644 index d3156f6..0000000 --- a/.idea/encodings.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/gradle.xml b/.idea/gradle.xml deleted file mode 100644 index 3e3960b..0000000 --- a/.idea/gradle.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/.idea/libraries/Maven__org_apiguardian_apiguardian_api_1_1_0.xml b/.idea/libraries/Maven__org_apiguardian_apiguardian_api_1_1_0.xml deleted file mode 100644 index f854ab0..0000000 --- a/.idea/libraries/Maven__org_apiguardian_apiguardian_api_1_1_0.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/libraries/Maven__org_junit_jupiter_junit_jupiter_5_5_2.xml b/.idea/libraries/Maven__org_junit_jupiter_junit_jupiter_5_5_2.xml deleted file mode 100644 index 5db0740..0000000 --- a/.idea/libraries/Maven__org_junit_jupiter_junit_jupiter_5_5_2.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/libraries/Maven__org_junit_jupiter_junit_jupiter_api_5_5_2.xml b/.idea/libraries/Maven__org_junit_jupiter_junit_jupiter_api_5_5_2.xml deleted file mode 100644 index 8fbc8ce..0000000 --- a/.idea/libraries/Maven__org_junit_jupiter_junit_jupiter_api_5_5_2.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/libraries/Maven__org_junit_jupiter_junit_jupiter_engine_5_5_2.xml b/.idea/libraries/Maven__org_junit_jupiter_junit_jupiter_engine_5_5_2.xml deleted file mode 100644 index cca5485..0000000 --- a/.idea/libraries/Maven__org_junit_jupiter_junit_jupiter_engine_5_5_2.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/libraries/Maven__org_junit_jupiter_junit_jupiter_params_5_5_2.xml b/.idea/libraries/Maven__org_junit_jupiter_junit_jupiter_params_5_5_2.xml deleted file mode 100644 index e2713d0..0000000 --- a/.idea/libraries/Maven__org_junit_jupiter_junit_jupiter_params_5_5_2.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/libraries/Maven__org_junit_platform_junit_platform_commons_1_5_2.xml b/.idea/libraries/Maven__org_junit_platform_junit_platform_commons_1_5_2.xml deleted file mode 100644 index 4192cdc..0000000 --- a/.idea/libraries/Maven__org_junit_platform_junit_platform_commons_1_5_2.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/libraries/Maven__org_junit_platform_junit_platform_engine_1_5_2.xml b/.idea/libraries/Maven__org_junit_platform_junit_platform_engine_1_5_2.xml deleted file mode 100644 index cbbd9b7..0000000 --- a/.idea/libraries/Maven__org_junit_platform_junit_platform_engine_1_5_2.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/libraries/Maven__org_opentest4j_opentest4j_1_2_0.xml b/.idea/libraries/Maven__org_opentest4j_opentest4j_1_2_0.xml deleted file mode 100644 index fbc1b16..0000000 --- a/.idea/libraries/Maven__org_opentest4j_opentest4j_1_2_0.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml deleted file mode 100644 index 7099446..0000000 --- a/.idea/misc.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml deleted file mode 100644 index 299b63d..0000000 --- a/.idea/modules.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/uiDesigner.xml b/.idea/uiDesigner.xml deleted file mode 100644 index e96534f..0000000 --- a/.idea/uiDesigner.xml +++ /dev/null @@ -1,124 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml deleted file mode 100644 index 94a25f7..0000000 --- a/.idea/vcs.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/Root.iml b/Root.iml deleted file mode 100644 index 346cf8b..0000000 --- a/Root.iml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Section3/Section3.iml b/Section3/Section3.iml deleted file mode 100644 index f07e6a5..0000000 --- a/Section3/Section3.iml +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Section4/Section4.iml b/Section4/Section4.iml deleted file mode 100644 index 5cc9145..0000000 --- a/Section4/Section4.iml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Section5/Section5.iml b/Section5/Section5.iml deleted file mode 100644 index 5cc9145..0000000 --- a/Section5/Section5.iml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Section6/Section6.iml b/Section6/Section6.iml deleted file mode 100644 index 5cc9145..0000000 --- a/Section6/Section6.iml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Section7/Section7.iml b/Section7/Section7.iml deleted file mode 100644 index 5cc9145..0000000 --- a/Section7/Section7.iml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Section8/Section8.iml b/Section8/Section8.iml deleted file mode 100644 index 5cc9145..0000000 --- a/Section8/Section8.iml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Section9/Section9.iml b/Section9/Section9.iml deleted file mode 100644 index 5cc9145..0000000 --- a/Section9/Section9.iml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file From 8e9a6275e608185258b82f16657550828836e2d6 Mon Sep 17 00:00:00 2001 From: Om Paliwal Date: Sun, 3 Nov 2019 10:52:13 +0530 Subject: [PATCH 07/19] Code refactoring for section 9 tests --- .../challenge/interfaces/MonsterTest.java | 22 ---------------- .../challenge/interfaces/MonsterTest.java | 25 +++++++++++++++++++ 2 files changed, 25 insertions(+), 22 deletions(-) delete mode 100644 Section9/src/test/challenge/interfaces/MonsterTest.java create mode 100644 Section9/src/test/java/challenge/interfaces/MonsterTest.java diff --git a/Section9/src/test/challenge/interfaces/MonsterTest.java b/Section9/src/test/challenge/interfaces/MonsterTest.java deleted file mode 100644 index 5c374ea..0000000 --- a/Section9/src/test/challenge/interfaces/MonsterTest.java +++ /dev/null @@ -1,22 +0,0 @@ -package challenge.interfaces; - -import org.junit.jupiter.api.Test; - -import java.util.List; - -class MonsterTest { - - @Test - void whenSavedStateIsLoadedPlayerMovesBackToThatState() { - Player aplayer = new Player("Ethen", 100, "AK-47"); - aplayer.setHealth(94); - List savedState = aplayer.write(); //save state - - //lets change player's health and weapons - aplayer.setHealth(10); - aplayer.setWeapon("AWM"); - - aplayer.read(savedState); - - } -} \ No newline at end of file diff --git a/Section9/src/test/java/challenge/interfaces/MonsterTest.java b/Section9/src/test/java/challenge/interfaces/MonsterTest.java new file mode 100644 index 0000000..57cd124 --- /dev/null +++ b/Section9/src/test/java/challenge/interfaces/MonsterTest.java @@ -0,0 +1,25 @@ +package challenge.interfaces; + +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class MonsterTest { + + @Test + public void whenSavedStateIsLoadedPlayerMovesBackToThatState() { + Player player = new Player("Ethen", 100, "AK-47"); + player.setHealth(94); + List savedState = player.write(); //save state + + //lets change player's health and weapons + player.setHealth(10); + player.setWeapon("AWM"); + player.read(savedState); + + assertEquals(94,player.getHealth()); + assertEquals("AK-47",player.getWeapon()); + } +} \ No newline at end of file From ad52a9413a3bd35d8a860829470b48c45e8cd736 Mon Sep 17 00:00:00 2001 From: Om Paliwal Date: Mon, 4 Nov 2019 21:55:45 +0530 Subject: [PATCH 08/19] Fix: Test failing for CRLF and LF differences --- .../src/test/java/exercise9/TestHelper.java | 9 ++- .../src/test/java/exercise21/TestHelper.java | 12 +++- .../java/challenge/arrays/TestHelper.java | 8 ++- .../abstractclasses/challenge_description | 57 +++++++++++++++++++ 4 files changed, 81 insertions(+), 5 deletions(-) create mode 100644 Section9/src/main/java/challenge/abstractclasses/challenge_description diff --git a/Section4/src/test/java/exercise9/TestHelper.java b/Section4/src/test/java/exercise9/TestHelper.java index cf60310..006a829 100644 --- a/Section4/src/test/java/exercise9/TestHelper.java +++ b/Section4/src/test/java/exercise9/TestHelper.java @@ -17,6 +17,7 @@ public class TestHelper { @BeforeEach public void setUpStreams() { + System.setProperty("line.separator", "\n"); sysOut = System.out; sysIn = System.in; System.setOut(new PrintStream(outContent)); @@ -29,7 +30,13 @@ public void revertStreams() { } public void assertSysout(String sysout) { - Assertions.assertEquals(sysout, outContent.toString().strip()); + String actualOutput = outContent.toString().strip(); + + //making string platform independent. Windows use CRLF(\r\n) as line seperator while linux uses LF(\n) + actualOutput = actualOutput.replace("\r\n","\n"); + sysout = sysout.replace("\r\n","\n"); + + Assertions.assertEquals(sysout, actualOutput); } //Before running tests that depends on user input, user must have to set this diff --git a/Section5/src/test/java/exercise21/TestHelper.java b/Section5/src/test/java/exercise21/TestHelper.java index 82cf7ef..6366bd4 100644 --- a/Section5/src/test/java/exercise21/TestHelper.java +++ b/Section5/src/test/java/exercise21/TestHelper.java @@ -17,6 +17,7 @@ public class TestHelper { @BeforeEach public void setUpStreams() { + System.setProperty("line.separator", "\n"); sysOut = System.out; sysIn = System.in; System.setOut(new PrintStream(outContent)); @@ -29,7 +30,13 @@ public void revertStreams() { } public void assertSysout(String sysout) { - Assertions.assertEquals(sysout, outContent.toString().strip()); + String actualOutput = outContent.toString().strip(); + + //making string platform independent. Windows use CRLF(\r\n) as line seperator while linux uses LF(\n) + actualOutput = actualOutput.replace("\r\n","\n"); + sysout = sysout.replace("\r\n","\n"); + + Assertions.assertEquals(sysout, actualOutput); } //Before running tests that depends on user input, user must have to set this @@ -38,5 +45,4 @@ public void setInputContent(String input) { inputContent = new ByteArrayInputStream(input.getBytes()); System.setIn(inputContent); } -} - +} \ No newline at end of file diff --git a/Section8/src/test/java/challenge/arrays/TestHelper.java b/Section8/src/test/java/challenge/arrays/TestHelper.java index 34cca31..7711c51 100644 --- a/Section8/src/test/java/challenge/arrays/TestHelper.java +++ b/Section8/src/test/java/challenge/arrays/TestHelper.java @@ -29,7 +29,13 @@ public void revertStreams() { } public void assertSysout(String sysout) { - Assertions.assertEquals(sysout, outContent.toString().strip()); + String actualOutput = outContent.toString().strip(); + + //making string platform independent. Windows use CRLF(\r\n) as line seperator while linux uses LF(\n) + actualOutput = actualOutput.replace("\r\n", "\n"); + sysout = sysout.replace("\r\n", "\n"); + + Assertions.assertEquals(sysout, actualOutput); } //Before running tests that depends on user input, user must have to set this diff --git a/Section9/src/main/java/challenge/abstractclasses/challenge_description b/Section9/src/main/java/challenge/abstractclasses/challenge_description new file mode 100644 index 0000000..5d222fd --- /dev/null +++ b/Section9/src/main/java/challenge/abstractclasses/challenge_description @@ -0,0 +1,57 @@ +* For this challenge, create an abstract class to define items that can be stored in a list. +* The class should contain 2 references to items which will represent the next and previous +* items (in the case of a linked list). +* I.e., if you call your abstract class ListItem, then it would have 2 member variables of +* type ListItem that will hold references to the next/right and previous/left ListItems. + +* The abstract class will also need to hold a value - try to be as flexible as possible +* when defining the type of this value. + +* The class will also need methods to move to the next item and back to the previous item, +* and methods to set the next and previous items. + +* You should also specify a compareTo() method that takes a parameter of the same type as the +* class and returns 0 if the values are equal, greater than zero if the value sorts greater than +* the parameter and less than zero if it sorts less than the parameter. + +* Create a concrete class from your abstract list item class and use this in a LinkedList +* class to implement a linked list that will add items in order (so that they are sorted +* alphabetically). Duplicate values are not added. + +* Note that you are creating your own LinkedList class here, not using the built-in Java one.. + +* The rules for adding an item to the linked list are: +* If the head of the list is null, make the head refer to the item to be added. +* If the item to be added is less than the current item in the list, add the item before the +* current item (i.e., make the previous item's "next" refer to the new item, and the new item's +* "next" refer to the current item). +* If the item to be added is greater than the current item, move onto the next item and compare +* again (if there is no next item then that is where the new item belongs). + +* Care will be needed when inserting before the first item in the list (as it will not have a previous +* item). + +* You will also need a method to remove an item from the list. + +* Hint: If you are creating classes with names such as List, LinkedList, Node etc, make sure that +* you create your classes before referring to them. In previous videos we have often referred to +* classes that we create later, but if you use names that IntelliJ recognises as Java classes (such +* as LinkedList) then it will create imports for them and possibly cause you problems later. + +* Optional: create a class to use your concrete class to implement a Binary Search Tree: +* When adding items to a Binary Search Tree, if the item to be added is less than the current item +* then move to the left, if it is greater than the current item then move to the right. + +* The new item is added when an attempt to move in the required direction would involve following a +* null reference. +* Once again, duplicates are not allowed. + +* Hint: to avoid typing loads of "addItem" lines, split a string into an array and create your list in +* a loop as in the example below. + +* Create a string data array to avoid typing loads of addItem instructions: + String stringData = "Darwin Brisbane Perth Melbourne Canberra Adelaide Sydney Canberra"; + + String[] data = stringData.split(" "); + for (String s : data) { +* create new item with value set to the string s \ No newline at end of file From 9a2523ccb012e3b1274a568580b9847304992077 Mon Sep 17 00:00:00 2001 From: Om Paliwal Date: Sat, 30 Nov 2019 10:25:42 +0530 Subject: [PATCH 09/19] Section 9 : Challenge code for abstract classes --- README.md | 1 + .../abstractclasses/LinkedListMain.java | 20 +++ .../challenge/abstractclasses/ListItem.java | 21 +++ .../abstractclasses/MyLinkedList.java | 155 ++++++++++++++++++ .../java/challenge/abstractclasses/Node.java | 41 +++++ .../challenge/abstractclasses/NodeList.java | 12 ++ .../challenge/abstractclasses/SearchTree.java | 116 +++++++++++++ .../abstractclasses/MyLinkedListTest.java | 88 ++++++++++ 8 files changed, 454 insertions(+) create mode 100644 Section9/src/main/java/challenge/abstractclasses/LinkedListMain.java create mode 100644 Section9/src/main/java/challenge/abstractclasses/ListItem.java create mode 100644 Section9/src/main/java/challenge/abstractclasses/MyLinkedList.java create mode 100644 Section9/src/main/java/challenge/abstractclasses/Node.java create mode 100644 Section9/src/main/java/challenge/abstractclasses/NodeList.java create mode 100644 Section9/src/main/java/challenge/abstractclasses/SearchTree.java create mode 100644 Section9/src/test/java/challenge/abstractclasses/MyLinkedListTest.java diff --git a/README.md b/README.md index 150c1f0..5249889 100644 --- a/README.md +++ b/README.md @@ -13,3 +13,4 @@ Course related code - Section 6: OOPS Part1: Classes, Constructors and Inheritance. - Section 7: OOPS Part2: Composition, Encapsulation and Polymorphism - Section 8: Arrays, ArrayList, AutoBoxing and LinkedList +- Section 9: Abstract Classes, Inner Classes and Interfaces diff --git a/Section9/src/main/java/challenge/abstractclasses/LinkedListMain.java b/Section9/src/main/java/challenge/abstractclasses/LinkedListMain.java new file mode 100644 index 0000000..dea79ef --- /dev/null +++ b/Section9/src/main/java/challenge/abstractclasses/LinkedListMain.java @@ -0,0 +1,20 @@ +package challenge.abstractclasses; + +public class LinkedListMain { + + public static void main(String[] args) { + SearchTree linkedList = new SearchTree(); + String[] unionTerritories = {"Delhi", "Goa", "Andaman & Nikobar", "Puducherry", "Daman and Diu", + "Chandigarh", "Lakshadweep", "Dadra and Nagar Haveli"}; //All Union Territories + + //traverse empty list + linkedList.traverse(); + + for(String ut: unionTerritories){ + System.out.println("Adding UT "+ut+" in List."); + linkedList.addNode(new Node(ut)); + } + System.out.println(linkedList.toString()); + System.out.println("Total UTs : "+linkedList.size()); + } +} diff --git a/Section9/src/main/java/challenge/abstractclasses/ListItem.java b/Section9/src/main/java/challenge/abstractclasses/ListItem.java new file mode 100644 index 0000000..81a63d4 --- /dev/null +++ b/Section9/src/main/java/challenge/abstractclasses/ListItem.java @@ -0,0 +1,21 @@ +package challenge.abstractclasses; + +public abstract class ListItem { + ListItem prev; + ListItem next; + Object value; + + public ListItem(Object value) { + this.value = value; + } + + public abstract void setNext(ListItem node); + public abstract ListItem next(); + public abstract void setPrev(ListItem node); + public abstract ListItem prev(); + public abstract int compareTo(ListItem node); + + public Object getValue() { + return value; + } +} diff --git a/Section9/src/main/java/challenge/abstractclasses/MyLinkedList.java b/Section9/src/main/java/challenge/abstractclasses/MyLinkedList.java new file mode 100644 index 0000000..8827a77 --- /dev/null +++ b/Section9/src/main/java/challenge/abstractclasses/MyLinkedList.java @@ -0,0 +1,155 @@ +package challenge.abstractclasses; + +public class MyLinkedList implements NodeList { + ListItem head = null; + + @Override + public ListItem getRoot() { + return head; + } + + public boolean addNode(ListItem node) { + boolean result = false; + if (node == null) { + throw new NullPointerException("Cannot add NULL node to list"); + } + + if (head == null) { + head = node; + return true; + } + + ListItem currentNode = head; + + while (currentNode != null) { + //Item already exists + if (currentNode.compareTo(node) == 0) { + System.out.println("Item already present"); + break; + } else if (currentNode.compareTo(node) < 0) { // Item is greater than + currentNode = currentNode.next(); + } else { + //New item is less than current item. add before this element + if (currentNode == head) { + node.setNext(head); + head.setPrev(node); + head = node; + } else { + // x <- newNode -> z(current) + // x -> newNode <- z(current) + node.setPrev(currentNode.prev()); + node.setNext(currentNode); + currentNode.prev().setNext(node); + currentNode.setPrev(node); + } + result = true; + break; + } + } + + if (currentNode == null) { + appendNode(node); + result = true; + } + + return result; + } + + private void appendNode(ListItem newNode) { + if (head == null) { + head = newNode; + return; + } + + ListItem current = head; + while (current.next() != null) { + current = current.next(); + } + + current.setNext(newNode); + newNode.setPrev(current); + + System.out.println("Added node at the end of list"); + } + + @Override + public void traverse() { + traverse(head); + } + + @Override + public void traverse(ListItem root) { + ListItem current = root; + if (root == null) { + System.out.println("List is empty"); + return; + } + + while (current != null) { + System.out.print(current.getValue() + ", "); + current = current.next(); + } + System.out.println(); + } + + @Override + public ListItem searchNode(ListItem node) { + ListItem current = head; + while (current != null) { + if (current.compareTo(node) == 0) { + return current; + } + current = current.next(); + } + + System.out.println("SEARCH: Node " + node.getValue() + " not found"); + return null; + } + + @Override + public int size() { + int count = 0; + ListItem current = head; + while (current != null) { + count++; + current = current.next(); + } + return count; + } + + public boolean removeNode(ListItem node) { + ListItem nodeFound = searchNode(node); + + if (nodeFound == null) { + System.out.println("REMOVE: Node " + node.value + "does not exist"); + return false; + } + + if (nodeFound == head && this.size() == 1) { //only node + head = null; + } else if (nodeFound == head) { //first node + head = head.next(); + } else if (nodeFound.next() == null) { //last node + nodeFound.prev().setNext(null); + } else { + nodeFound.prev().setNext(nodeFound.next()); + nodeFound.next().setPrev(nodeFound.prev()); + } + return true; + } + + @Override + public String toString() { + ListItem currentItem = head; + StringBuilder printValue = new StringBuilder(); + printValue.append("["); + while(currentItem.next() != null){ + printValue.append(currentItem.getValue()+","); + currentItem = currentItem.next(); + } + + printValue.append(currentItem.getValue()); + printValue.append("]"); + return String.valueOf(printValue); + } +} diff --git a/Section9/src/main/java/challenge/abstractclasses/Node.java b/Section9/src/main/java/challenge/abstractclasses/Node.java new file mode 100644 index 0000000..abf3b73 --- /dev/null +++ b/Section9/src/main/java/challenge/abstractclasses/Node.java @@ -0,0 +1,41 @@ +package challenge.abstractclasses; + + +/** + * A general node of LinkedList + */ +public class Node extends ListItem { + + public Node(Object value) { + super(value); + } + + @Override + public void setNext(ListItem node) { + next = node; + } + + @Override + public ListItem next() { + return next; + } + + @Override + public void setPrev(ListItem node) { + prev = node; + } + + @Override + public ListItem prev() { + return prev; + } + + @Override + public int compareTo(ListItem node) { + if(node == null){ + return -1; + }else { + return ((String)this.value).compareTo((String)node.value); + } + } +} diff --git a/Section9/src/main/java/challenge/abstractclasses/NodeList.java b/Section9/src/main/java/challenge/abstractclasses/NodeList.java new file mode 100644 index 0000000..0a14aae --- /dev/null +++ b/Section9/src/main/java/challenge/abstractclasses/NodeList.java @@ -0,0 +1,12 @@ +package challenge.abstractclasses; + +public interface NodeList { + + public ListItem getRoot(); + public boolean addNode(ListItem node); + public void traverse(); + public void traverse(ListItem root); + public boolean removeNode(ListItem node); + ListItem searchNode(ListItem node); + int size(); +} diff --git a/Section9/src/main/java/challenge/abstractclasses/SearchTree.java b/Section9/src/main/java/challenge/abstractclasses/SearchTree.java new file mode 100644 index 0000000..38bdf88 --- /dev/null +++ b/Section9/src/main/java/challenge/abstractclasses/SearchTree.java @@ -0,0 +1,116 @@ +package challenge.abstractclasses; + +public class SearchTree implements NodeList { + ListItem root = null; + private int count = 0; + + @Override + public ListItem getRoot() { + return root; + } + + @Override + public boolean addNode(ListItem node) { + boolean itemAdded = false; + if (root == null) { + root = node; + count++; + return true; + } + + ListItem currentNode = root; + while (currentNode != null) { + int comparision = currentNode.compareTo(node); + if (comparision < 0) { + //Item node is greater than current node, Move right. + if (currentNode.next() != null) { + currentNode = currentNode.next(); + } else { + currentNode.setNext(node); + itemAdded = true; + break; + } + } else if (comparision > 0) { + //Item node is smaller than currentNode, move right + if (currentNode.prev() != null) { + currentNode = currentNode.prev(); + } else { + currentNode.setPrev(node); + itemAdded = true; + break; + } + } else { + System.out.println("Node already present."); + itemAdded = false; + break; + } + } + + if(itemAdded){ + count++; + } + + return itemAdded; + } + + @Override + public void traverse() { + if(root == null) { + System.out.println("Tree is empty"); + return; + }else{ + traverse(root); + } + } + + @Override + public void traverse(ListItem rootNode) { + if(rootNode == null){ + return; + } + + //items have been added such that the smallest element will be at left most node + traverse(rootNode.prev()); + System.out.println(rootNode.getValue()+" ,"); + traverse(rootNode.next()); + } + + @Override + public boolean removeNode(ListItem node) { + System.out.println("Not implemented citing the complexity of algorithm"); + return false; + } + + @Override + public ListItem searchNode(ListItem node) { + System.out.println("Not implemented yet"); + return null; + } + + @Override + public int size() { + return count; + } + + + @Override + public String toString() { + String output = "{"; + getTree(root, output); + output += "}"; + return output; + } + + public String getTree(ListItem node, String output) { + if(node == null){ + return ""; + } + + //items have been added such that the smallest element will be at left most node + traverse(node.prev()); + output += node.value+","; + traverse(node.next()); + + return output; + } +} diff --git a/Section9/src/test/java/challenge/abstractclasses/MyLinkedListTest.java b/Section9/src/test/java/challenge/abstractclasses/MyLinkedListTest.java new file mode 100644 index 0000000..5f81cf4 --- /dev/null +++ b/Section9/src/test/java/challenge/abstractclasses/MyLinkedListTest.java @@ -0,0 +1,88 @@ +package challenge.abstractclasses; + + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class MyLinkedListTest { + String[] listItems = {"o", "m", "p", "r", "a", "k", "a", "s", "h"}; + String[] orderedUniqueListItems = {"a", "h", "k", "m", "o", "p", "r", "s"}; + MyLinkedList linkedList; + + @BeforeEach + public void setup() { + linkedList = new MyLinkedList(); + + //populate + for (String s : listItems) { + linkedList.addNode(new Node(s)); + } + } + + @Test + public void onlyUniqueItemsAreStoredInList() { + assert orderedUniqueListItems.length == linkedList.size(); + } + + + @Test + public void itemsAreAddedInOrder() { + ListItem current = linkedList.getRoot(); + for (String s : orderedUniqueListItems) { + Assertions.assertEquals(s, current.getValue()); + current = current.next(); + } + } + + @Test + public void removeFirstItem() { + linkedList.removeNode(new Node("a")); + Assertions.assertEquals("[h,k,m,o,p,r,s]", linkedList.toString()); + } + + @Test + public void removeLastItem() { + linkedList.removeNode(new Node("s")); + Assertions.assertEquals("[a,h,k,m,o,p,r]", linkedList.toString()); + } + + @Test + public void removeAnyItem() { + linkedList.removeNode(new Node("k")); + Assertions.assertEquals("[a,h,m,o,p,r,s]", linkedList.toString()); + } + + @Test + public void searchReturnsNode() { + ListItem item = linkedList.searchNode(new Node("h")); + assert item.getValue() == "h"; + } + + @Test public void smallestNodeShouldAddToBeginning(){ + MyLinkedList anotherList = new MyLinkedList(); + + anotherList.addNode(new Node("c")); + anotherList.addNode(new Node("d")); + anotherList.addNode(new Node("e")); + + assert "[c,d,e]".equals(anotherList.toString()); + + anotherList.addNode(new Node("a")); + assert "[a,c,d,e]".equals(anotherList.toString()); + } + + @Test public void largestNodeShouldAppendToList(){ + MyLinkedList anotherList = new MyLinkedList(); + + anotherList.addNode(new Node("c")); + anotherList.addNode(new Node("d")); + anotherList.addNode(new Node("e")); + + assert "[c,d,e]".equals(anotherList.toString()); + + anotherList.addNode(new Node("f")); + assert "[c,d,e,f]".equals(anotherList.toString()); + } + +} \ No newline at end of file From 82cca5ff54930650e483d3dda6c3f3f93583dee0 Mon Sep 17 00:00:00 2001 From: Om Paliwal Date: Sun, 1 Dec 2019 01:57:18 +0530 Subject: [PATCH 10/19] Section 10: Generics --- Section10/pom.xml | 14 +++ .../main/java/generics/challenge/League.java | 44 ++++++++++ .../generics/challenge/LeagueImplMain.java | 48 +++++++++++ .../java/generics/example/CricketPlayer.java | 7 ++ .../java/generics/example/FootballPlayer.java | 7 ++ .../main/java/generics/example/Player.java | 13 +++ .../java/generics/example/SoccerPlayer.java | 7 ++ .../src/main/java/generics/example/Team.java | 86 +++++++++++++++++++ .../main/java/generics/example/TeamMain.java | 69 +++++++++++++++ .../test/java/generics/example/TeamTest.java | 36 ++++++++ pom.xml | 1 + 11 files changed, 332 insertions(+) create mode 100644 Section10/pom.xml create mode 100644 Section10/src/main/java/generics/challenge/League.java create mode 100644 Section10/src/main/java/generics/challenge/LeagueImplMain.java create mode 100644 Section10/src/main/java/generics/example/CricketPlayer.java create mode 100644 Section10/src/main/java/generics/example/FootballPlayer.java create mode 100644 Section10/src/main/java/generics/example/Player.java create mode 100644 Section10/src/main/java/generics/example/SoccerPlayer.java create mode 100644 Section10/src/main/java/generics/example/Team.java create mode 100644 Section10/src/main/java/generics/example/TeamMain.java create mode 100644 Section10/src/test/java/generics/example/TeamTest.java diff --git a/Section10/pom.xml b/Section10/pom.xml new file mode 100644 index 0000000..7891164 --- /dev/null +++ b/Section10/pom.xml @@ -0,0 +1,14 @@ + + + 4.0.0 + + + udemyjavacourse + JavaUdemyCourse + 0.0.1 + + Section10 + + \ No newline at end of file diff --git a/Section10/src/main/java/generics/challenge/League.java b/Section10/src/main/java/generics/challenge/League.java new file mode 100644 index 0000000..10d966d --- /dev/null +++ b/Section10/src/main/java/generics/challenge/League.java @@ -0,0 +1,44 @@ +package generics.challenge; + +import generics.example.Team; + +import java.util.ArrayList; +import java.util.Collections; + +public class League { + + private String title; + private ArrayList teams = new ArrayList<>(); + + public League(String title) { + this.title = title; + } + + public boolean addTeam(T team) { + if (teams.contains(team)) { + System.out.println("Team " + team.getName() + " already added to league " + getTitle()); + return false; + } + teams.add(team); + System.out.println("Team " + team.getName() + " Added to league " + getTitle()); + return true; + } + + public void showLeagueTable() { + Collections.sort(teams); + System.out.println("==================================================="); + System.out.println("League scoreboard"); + for (T team : teams) { + System.out.println(team.getName() + " : " + team.getRanking()); + } + System.out.println("==================================================="); + } + + public String getTitle() { + return title; + } + + public T getTeam(int i) { + return teams.get(i); + } +} diff --git a/Section10/src/main/java/generics/challenge/LeagueImplMain.java b/Section10/src/main/java/generics/challenge/LeagueImplMain.java new file mode 100644 index 0000000..4db98f2 --- /dev/null +++ b/Section10/src/main/java/generics/challenge/LeagueImplMain.java @@ -0,0 +1,48 @@ +package generics.challenge; + +import generics.example.CricketPlayer; +import generics.example.Team; + +import java.time.LocalDate; + +public class LeagueImplMain { + public static void main(String[] args) { + String[] participatingTeams = {"India", "Pakistan", "Australia", "New Zealand", "England"}; + League> worldCupLeague = new League<>("ODI Worldcup"); + for (String teamName : participatingTeams) { + //Create team + Team cricketTeam = new Team<>(teamName); + //Create player + cricketTeam.addPlayer(new CricketPlayer(teamName + " Player1")); + //Add team to league + worldCupLeague.addTeam(cricketTeam); + } + + //lets play 15 games randomly + int match = 1; + int noOfTeams = participatingTeams.length; + + while (match <= 15) { + //(Math.random() * ((max - min) + 1)) + min + int team1Code = (int) (Math.random() * noOfTeams); + int team2Code = (int) (Math.random() * noOfTeams); + + if (team1Code == team2Code) { + continue; + } + + System.out.println("Match #" + match); + Team team1 = worldCupLeague.getTeam(team1Code); + Team team2 = worldCupLeague.getTeam(team2Code); + + int team1Score = (int) (Math.random() * 400); + int team2Score = (int) (Math.random() * 400); + + team1.matchResults(team2, team1Score, team2Score); + match++; + worldCupLeague.showLeagueTable(); + } + System.out.println("And the winner of the worldcup " + LocalDate.now().getYear() + + " is " + worldCupLeague.getTeam(0).getName()); + } +} diff --git a/Section10/src/main/java/generics/example/CricketPlayer.java b/Section10/src/main/java/generics/example/CricketPlayer.java new file mode 100644 index 0000000..a9532b4 --- /dev/null +++ b/Section10/src/main/java/generics/example/CricketPlayer.java @@ -0,0 +1,7 @@ +package generics.example; + +public class CricketPlayer extends Player { + public CricketPlayer(String name) { + super(name); + } +} diff --git a/Section10/src/main/java/generics/example/FootballPlayer.java b/Section10/src/main/java/generics/example/FootballPlayer.java new file mode 100644 index 0000000..b41bc7b --- /dev/null +++ b/Section10/src/main/java/generics/example/FootballPlayer.java @@ -0,0 +1,7 @@ +package generics.example; + +public class FootballPlayer extends Player { + public FootballPlayer(String name) { + super(name); + } +} diff --git a/Section10/src/main/java/generics/example/Player.java b/Section10/src/main/java/generics/example/Player.java new file mode 100644 index 0000000..cb22619 --- /dev/null +++ b/Section10/src/main/java/generics/example/Player.java @@ -0,0 +1,13 @@ +package generics.example; + +public class Player { + private String name; + + public Player(String name) { + this.name = name; + } + + public String getName() { + return name; + } +} diff --git a/Section10/src/main/java/generics/example/SoccerPlayer.java b/Section10/src/main/java/generics/example/SoccerPlayer.java new file mode 100644 index 0000000..1ea9f03 --- /dev/null +++ b/Section10/src/main/java/generics/example/SoccerPlayer.java @@ -0,0 +1,7 @@ +package generics.example; + +public class SoccerPlayer extends Player { + public SoccerPlayer(String name) { + super(name); + } +} diff --git a/Section10/src/main/java/generics/example/Team.java b/Section10/src/main/java/generics/example/Team.java new file mode 100644 index 0000000..a865a4d --- /dev/null +++ b/Section10/src/main/java/generics/example/Team.java @@ -0,0 +1,86 @@ +package generics.example; + +import java.util.ArrayList; + +public class Team implements Comparable> { + private static final int WINNING_POINTS = 2; + private String name; + private int played = 0; + private int points = 0; + private int won = 0; + private int tied = 0; + private int lost = 0; + private ArrayList members = new ArrayList<>(); + + public Team(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + + public void addPlayer(T player) { + if (members.contains(player)) { + System.out.println("Player already present"); + return; + } + + members.add(player); + System.out.println("Player " + player.getName() + " added to " + name); + } + + public int getTeamSize() { + return members.size(); + } + + + public void matchResults(Team opponent, int ourScore, int opponentScore) { + String message; + played++; + if (ourScore > opponentScore) { + won++; + points += WINNING_POINTS; + message = " beat "; + } else if (ourScore == opponentScore) { + tied++; + points++; + message = " tied with "; + } else { + lost++; + message = " lost to "; + } + + if (opponent != null) { + System.out.println(getName() + message + opponent.getName()); + opponent.matchResults(null, opponentScore, ourScore); + } + } + + public int getPoints() { + return points; + } + + public int getRanking() { + return won * 2 + tied; + } + + /** + * compare based on ranking + * + * @param opponentTeam Team to compare with + * @return -1 if teams ranking is greater than team opponentTeam, 1 of lower, 0 if same + */ + @Override + public int compareTo(Team opponentTeam) { + + if (this.getRanking() > opponentTeam.getRanking()) { + return -1; + } else if (this.getRanking() < opponentTeam.getRanking()) { + return 1; + } else { + return 0; + } + } +} diff --git a/Section10/src/main/java/generics/example/TeamMain.java b/Section10/src/main/java/generics/example/TeamMain.java new file mode 100644 index 0000000..bf517aa --- /dev/null +++ b/Section10/src/main/java/generics/example/TeamMain.java @@ -0,0 +1,69 @@ +package generics.example; + +public class TeamMain { + + public static void main(String[] args) { + + //Let's play india and pakistan cricket match + + playCricketMatch(); +// playFootBallMatch(); + } + + private static void playFootBallMatch() { + //Indian team + FootballPlayer bhaichung = new FootballPlayer("Baichung Bhutia"); + FootballPlayer chhetri = new FootballPlayer("Sunil Chhetri"); + + //Pakistani team + FootballPlayer iqbal = new FootballPlayer("Amjad Iqbal"); + FootballPlayer essa = new FootballPlayer("Muhammad Essa"); + + Team indianTeam = new Team<>("Indian Soccer Team"); + Team pakistanTeam = new Team<>("Pakistani Soccer Team"); + + //3 match series + pakistanTeam.matchResults(indianTeam, 2, 10); + pakistanTeam.matchResults(indianTeam, 5, 3); + pakistanTeam.matchResults(indianTeam, 3, 1); + System.out.println("Pakistan : " + pakistanTeam.getRanking() + " India : " + indianTeam.getRanking()); + + announceWinner(indianTeam, pakistanTeam); + } + + private static void playCricketMatch() { + String[] indianCricketTeamPlayer = {"Sachin Tendulkar", "Sehwag", "Ganguly", "Dhoni"}; + String[] pakistaniCricketTeamPlayer = {"Injemam Ul Haq", "Yunis Khan", "Yusif Youhana", "Shoeb Akhtar"}; + Team indianCricketTeam = new Team<>("Indian Cricket Team"); + Team pakistanCricketTeam = new Team<>("Pakistan Cricket Team"); + + for (String player : indianCricketTeamPlayer) { + indianCricketTeam.addPlayer(new CricketPlayer(player)); + } + + for (String player : pakistaniCricketTeamPlayer) { + pakistanCricketTeam.addPlayer(new CricketPlayer(player)); + } + + //3 match ODI series + pakistanCricketTeam.matchResults(indianCricketTeam, 150, 346); + pakistanCricketTeam.matchResults(indianCricketTeam, 298, 190); + pakistanCricketTeam.matchResults(indianCricketTeam, 312, 400); + + //print rankings + System.out.println("Pakistan : " + pakistanCricketTeam.getRanking() + " India : " + indianCricketTeam.getRanking()); + announceWinner(indianCricketTeam, pakistanCricketTeam); + } + + private static void announceWinner(Team team1, Team team2) { + int results = team1.compareTo(team2); + if (results == 1) { + System.out.println(team2.getName() + " Wins the series"); + } else if (results == -1) { + System.out.println(team1.getName() + " Wins the series"); + } else { + System.out.println("Series drawn between " + team1.getName() + + " and " + team2.getName()); + } + } +} diff --git a/Section10/src/test/java/generics/example/TeamTest.java b/Section10/src/test/java/generics/example/TeamTest.java new file mode 100644 index 0000000..b7de7c4 --- /dev/null +++ b/Section10/src/test/java/generics/example/TeamTest.java @@ -0,0 +1,36 @@ +package generics.example; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class TeamTest { + + private static final short WINNING_POINTS = 2; + + @Test + void cricketPlayerIsAbleToJoinCricketTeam() { + Team cricketPlayerTeam = new Team("Cricket Team"); + cricketPlayerTeam.addPlayer(new CricketPlayer("A Cricket Player")); + } + + @Test + void teamWithHighestRankingWins() { + Team cricketPlayerTeamA = new Team("Cricket Team A"); + Team cricketPlayerTeamB = new Team("Cricket Team B"); + cricketPlayerTeamA.matchResults(cricketPlayerTeamB, 340, 330); //A wins + cricketPlayerTeamA.matchResults(cricketPlayerTeamB, 330, 330); //Draw + //A will win with 2 points + assertEquals(-1, cricketPlayerTeamA.compareTo(cricketPlayerTeamB)); + } + + @Test + void everyWinGivesPointsToWinningTeam() { + Team cricketPlayerTeamA = new Team("Cricket Team A"); + Team cricketPlayerTeamB = new Team("Cricket Team B"); + cricketPlayerTeamA.matchResults(cricketPlayerTeamB, 340, 330); //A wins + //A will win with WINNING_PONTS points + assertEquals(WINNING_POINTS, cricketPlayerTeamA.getPoints()); + } + +} \ No newline at end of file diff --git a/pom.xml b/pom.xml index 8dc548e..f01abdf 100644 --- a/pom.xml +++ b/pom.xml @@ -17,6 +17,7 @@ Section7 Section8 Section9 + Section10 From 27619d09302eb5bb2c1b124b0be21b936435d495 Mon Sep 17 00:00:00 2001 From: Om Paliwal Date: Sun, 1 Dec 2019 01:57:18 +0530 Subject: [PATCH 11/19] Section 10: Generics --- README.md | 1 + Section10/pom.xml | 14 +++ .../main/java/generics/challenge/League.java | 44 ++++++++++ .../generics/challenge/LeagueImplMain.java | 48 +++++++++++ .../java/generics/example/CricketPlayer.java | 7 ++ .../java/generics/example/FootballPlayer.java | 7 ++ .../main/java/generics/example/Player.java | 13 +++ .../java/generics/example/SoccerPlayer.java | 7 ++ .../src/main/java/generics/example/Team.java | 86 +++++++++++++++++++ .../main/java/generics/example/TeamMain.java | 69 +++++++++++++++ .../test/java/generics/example/TeamTest.java | 36 ++++++++ pom.xml | 1 + 12 files changed, 333 insertions(+) create mode 100644 Section10/pom.xml create mode 100644 Section10/src/main/java/generics/challenge/League.java create mode 100644 Section10/src/main/java/generics/challenge/LeagueImplMain.java create mode 100644 Section10/src/main/java/generics/example/CricketPlayer.java create mode 100644 Section10/src/main/java/generics/example/FootballPlayer.java create mode 100644 Section10/src/main/java/generics/example/Player.java create mode 100644 Section10/src/main/java/generics/example/SoccerPlayer.java create mode 100644 Section10/src/main/java/generics/example/Team.java create mode 100644 Section10/src/main/java/generics/example/TeamMain.java create mode 100644 Section10/src/test/java/generics/example/TeamTest.java diff --git a/README.md b/README.md index 5249889..7e4c078 100644 --- a/README.md +++ b/README.md @@ -14,3 +14,4 @@ Course related code - Section 7: OOPS Part2: Composition, Encapsulation and Polymorphism - Section 8: Arrays, ArrayList, AutoBoxing and LinkedList - Section 9: Abstract Classes, Inner Classes and Interfaces +- Section 10: Java Generics \ No newline at end of file diff --git a/Section10/pom.xml b/Section10/pom.xml new file mode 100644 index 0000000..7891164 --- /dev/null +++ b/Section10/pom.xml @@ -0,0 +1,14 @@ + + + 4.0.0 + + + udemyjavacourse + JavaUdemyCourse + 0.0.1 + + Section10 + + \ No newline at end of file diff --git a/Section10/src/main/java/generics/challenge/League.java b/Section10/src/main/java/generics/challenge/League.java new file mode 100644 index 0000000..10d966d --- /dev/null +++ b/Section10/src/main/java/generics/challenge/League.java @@ -0,0 +1,44 @@ +package generics.challenge; + +import generics.example.Team; + +import java.util.ArrayList; +import java.util.Collections; + +public class League { + + private String title; + private ArrayList teams = new ArrayList<>(); + + public League(String title) { + this.title = title; + } + + public boolean addTeam(T team) { + if (teams.contains(team)) { + System.out.println("Team " + team.getName() + " already added to league " + getTitle()); + return false; + } + teams.add(team); + System.out.println("Team " + team.getName() + " Added to league " + getTitle()); + return true; + } + + public void showLeagueTable() { + Collections.sort(teams); + System.out.println("==================================================="); + System.out.println("League scoreboard"); + for (T team : teams) { + System.out.println(team.getName() + " : " + team.getRanking()); + } + System.out.println("==================================================="); + } + + public String getTitle() { + return title; + } + + public T getTeam(int i) { + return teams.get(i); + } +} diff --git a/Section10/src/main/java/generics/challenge/LeagueImplMain.java b/Section10/src/main/java/generics/challenge/LeagueImplMain.java new file mode 100644 index 0000000..4db98f2 --- /dev/null +++ b/Section10/src/main/java/generics/challenge/LeagueImplMain.java @@ -0,0 +1,48 @@ +package generics.challenge; + +import generics.example.CricketPlayer; +import generics.example.Team; + +import java.time.LocalDate; + +public class LeagueImplMain { + public static void main(String[] args) { + String[] participatingTeams = {"India", "Pakistan", "Australia", "New Zealand", "England"}; + League> worldCupLeague = new League<>("ODI Worldcup"); + for (String teamName : participatingTeams) { + //Create team + Team cricketTeam = new Team<>(teamName); + //Create player + cricketTeam.addPlayer(new CricketPlayer(teamName + " Player1")); + //Add team to league + worldCupLeague.addTeam(cricketTeam); + } + + //lets play 15 games randomly + int match = 1; + int noOfTeams = participatingTeams.length; + + while (match <= 15) { + //(Math.random() * ((max - min) + 1)) + min + int team1Code = (int) (Math.random() * noOfTeams); + int team2Code = (int) (Math.random() * noOfTeams); + + if (team1Code == team2Code) { + continue; + } + + System.out.println("Match #" + match); + Team team1 = worldCupLeague.getTeam(team1Code); + Team team2 = worldCupLeague.getTeam(team2Code); + + int team1Score = (int) (Math.random() * 400); + int team2Score = (int) (Math.random() * 400); + + team1.matchResults(team2, team1Score, team2Score); + match++; + worldCupLeague.showLeagueTable(); + } + System.out.println("And the winner of the worldcup " + LocalDate.now().getYear() + + " is " + worldCupLeague.getTeam(0).getName()); + } +} diff --git a/Section10/src/main/java/generics/example/CricketPlayer.java b/Section10/src/main/java/generics/example/CricketPlayer.java new file mode 100644 index 0000000..a9532b4 --- /dev/null +++ b/Section10/src/main/java/generics/example/CricketPlayer.java @@ -0,0 +1,7 @@ +package generics.example; + +public class CricketPlayer extends Player { + public CricketPlayer(String name) { + super(name); + } +} diff --git a/Section10/src/main/java/generics/example/FootballPlayer.java b/Section10/src/main/java/generics/example/FootballPlayer.java new file mode 100644 index 0000000..b41bc7b --- /dev/null +++ b/Section10/src/main/java/generics/example/FootballPlayer.java @@ -0,0 +1,7 @@ +package generics.example; + +public class FootballPlayer extends Player { + public FootballPlayer(String name) { + super(name); + } +} diff --git a/Section10/src/main/java/generics/example/Player.java b/Section10/src/main/java/generics/example/Player.java new file mode 100644 index 0000000..cb22619 --- /dev/null +++ b/Section10/src/main/java/generics/example/Player.java @@ -0,0 +1,13 @@ +package generics.example; + +public class Player { + private String name; + + public Player(String name) { + this.name = name; + } + + public String getName() { + return name; + } +} diff --git a/Section10/src/main/java/generics/example/SoccerPlayer.java b/Section10/src/main/java/generics/example/SoccerPlayer.java new file mode 100644 index 0000000..1ea9f03 --- /dev/null +++ b/Section10/src/main/java/generics/example/SoccerPlayer.java @@ -0,0 +1,7 @@ +package generics.example; + +public class SoccerPlayer extends Player { + public SoccerPlayer(String name) { + super(name); + } +} diff --git a/Section10/src/main/java/generics/example/Team.java b/Section10/src/main/java/generics/example/Team.java new file mode 100644 index 0000000..a865a4d --- /dev/null +++ b/Section10/src/main/java/generics/example/Team.java @@ -0,0 +1,86 @@ +package generics.example; + +import java.util.ArrayList; + +public class Team implements Comparable> { + private static final int WINNING_POINTS = 2; + private String name; + private int played = 0; + private int points = 0; + private int won = 0; + private int tied = 0; + private int lost = 0; + private ArrayList members = new ArrayList<>(); + + public Team(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + + public void addPlayer(T player) { + if (members.contains(player)) { + System.out.println("Player already present"); + return; + } + + members.add(player); + System.out.println("Player " + player.getName() + " added to " + name); + } + + public int getTeamSize() { + return members.size(); + } + + + public void matchResults(Team opponent, int ourScore, int opponentScore) { + String message; + played++; + if (ourScore > opponentScore) { + won++; + points += WINNING_POINTS; + message = " beat "; + } else if (ourScore == opponentScore) { + tied++; + points++; + message = " tied with "; + } else { + lost++; + message = " lost to "; + } + + if (opponent != null) { + System.out.println(getName() + message + opponent.getName()); + opponent.matchResults(null, opponentScore, ourScore); + } + } + + public int getPoints() { + return points; + } + + public int getRanking() { + return won * 2 + tied; + } + + /** + * compare based on ranking + * + * @param opponentTeam Team to compare with + * @return -1 if teams ranking is greater than team opponentTeam, 1 of lower, 0 if same + */ + @Override + public int compareTo(Team opponentTeam) { + + if (this.getRanking() > opponentTeam.getRanking()) { + return -1; + } else if (this.getRanking() < opponentTeam.getRanking()) { + return 1; + } else { + return 0; + } + } +} diff --git a/Section10/src/main/java/generics/example/TeamMain.java b/Section10/src/main/java/generics/example/TeamMain.java new file mode 100644 index 0000000..bf517aa --- /dev/null +++ b/Section10/src/main/java/generics/example/TeamMain.java @@ -0,0 +1,69 @@ +package generics.example; + +public class TeamMain { + + public static void main(String[] args) { + + //Let's play india and pakistan cricket match + + playCricketMatch(); +// playFootBallMatch(); + } + + private static void playFootBallMatch() { + //Indian team + FootballPlayer bhaichung = new FootballPlayer("Baichung Bhutia"); + FootballPlayer chhetri = new FootballPlayer("Sunil Chhetri"); + + //Pakistani team + FootballPlayer iqbal = new FootballPlayer("Amjad Iqbal"); + FootballPlayer essa = new FootballPlayer("Muhammad Essa"); + + Team indianTeam = new Team<>("Indian Soccer Team"); + Team pakistanTeam = new Team<>("Pakistani Soccer Team"); + + //3 match series + pakistanTeam.matchResults(indianTeam, 2, 10); + pakistanTeam.matchResults(indianTeam, 5, 3); + pakistanTeam.matchResults(indianTeam, 3, 1); + System.out.println("Pakistan : " + pakistanTeam.getRanking() + " India : " + indianTeam.getRanking()); + + announceWinner(indianTeam, pakistanTeam); + } + + private static void playCricketMatch() { + String[] indianCricketTeamPlayer = {"Sachin Tendulkar", "Sehwag", "Ganguly", "Dhoni"}; + String[] pakistaniCricketTeamPlayer = {"Injemam Ul Haq", "Yunis Khan", "Yusif Youhana", "Shoeb Akhtar"}; + Team indianCricketTeam = new Team<>("Indian Cricket Team"); + Team pakistanCricketTeam = new Team<>("Pakistan Cricket Team"); + + for (String player : indianCricketTeamPlayer) { + indianCricketTeam.addPlayer(new CricketPlayer(player)); + } + + for (String player : pakistaniCricketTeamPlayer) { + pakistanCricketTeam.addPlayer(new CricketPlayer(player)); + } + + //3 match ODI series + pakistanCricketTeam.matchResults(indianCricketTeam, 150, 346); + pakistanCricketTeam.matchResults(indianCricketTeam, 298, 190); + pakistanCricketTeam.matchResults(indianCricketTeam, 312, 400); + + //print rankings + System.out.println("Pakistan : " + pakistanCricketTeam.getRanking() + " India : " + indianCricketTeam.getRanking()); + announceWinner(indianCricketTeam, pakistanCricketTeam); + } + + private static void announceWinner(Team team1, Team team2) { + int results = team1.compareTo(team2); + if (results == 1) { + System.out.println(team2.getName() + " Wins the series"); + } else if (results == -1) { + System.out.println(team1.getName() + " Wins the series"); + } else { + System.out.println("Series drawn between " + team1.getName() + + " and " + team2.getName()); + } + } +} diff --git a/Section10/src/test/java/generics/example/TeamTest.java b/Section10/src/test/java/generics/example/TeamTest.java new file mode 100644 index 0000000..b7de7c4 --- /dev/null +++ b/Section10/src/test/java/generics/example/TeamTest.java @@ -0,0 +1,36 @@ +package generics.example; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class TeamTest { + + private static final short WINNING_POINTS = 2; + + @Test + void cricketPlayerIsAbleToJoinCricketTeam() { + Team cricketPlayerTeam = new Team("Cricket Team"); + cricketPlayerTeam.addPlayer(new CricketPlayer("A Cricket Player")); + } + + @Test + void teamWithHighestRankingWins() { + Team cricketPlayerTeamA = new Team("Cricket Team A"); + Team cricketPlayerTeamB = new Team("Cricket Team B"); + cricketPlayerTeamA.matchResults(cricketPlayerTeamB, 340, 330); //A wins + cricketPlayerTeamA.matchResults(cricketPlayerTeamB, 330, 330); //Draw + //A will win with 2 points + assertEquals(-1, cricketPlayerTeamA.compareTo(cricketPlayerTeamB)); + } + + @Test + void everyWinGivesPointsToWinningTeam() { + Team cricketPlayerTeamA = new Team("Cricket Team A"); + Team cricketPlayerTeamB = new Team("Cricket Team B"); + cricketPlayerTeamA.matchResults(cricketPlayerTeamB, 340, 330); //A wins + //A will win with WINNING_PONTS points + assertEquals(WINNING_POINTS, cricketPlayerTeamA.getPoints()); + } + +} \ No newline at end of file diff --git a/pom.xml b/pom.xml index 8dc548e..f01abdf 100644 --- a/pom.xml +++ b/pom.xml @@ -17,6 +17,7 @@ Section7 Section8 Section9 + Section10 From 2f5ed4aec41eafc68ec1b2fd7806f383f7a2fe6d Mon Sep 17 00:00:00 2001 From: Om Paliwal Date: Sun, 8 Dec 2019 10:02:50 +0530 Subject: [PATCH 12/19] Section 11: package and scope exercise/challenge --- README.md | 3 +- Section11/pom.xml | 13 +++++ .../main/java/challenge/packages/Main.java | 29 ++++++++++ .../main/java/challenge/packages/Series.java | 53 +++++++++++++++++ .../src/main/java/challenge/scope/README.md | 17 ++++++ .../src/main/java/challenge/scope/X.java | 17 ++++++ .../src/main/java/challenge/scope/main/X.java | 13 +++++ .../java/challenge/packages/SeriesTest.java | 57 +++++++++++++++++++ pom.xml | 3 + 9 files changed, 204 insertions(+), 1 deletion(-) create mode 100644 Section11/pom.xml create mode 100644 Section11/src/main/java/challenge/packages/Main.java create mode 100644 Section11/src/main/java/challenge/packages/Series.java create mode 100644 Section11/src/main/java/challenge/scope/README.md create mode 100644 Section11/src/main/java/challenge/scope/X.java create mode 100644 Section11/src/main/java/challenge/scope/main/X.java create mode 100644 Section11/src/test/java/challenge/packages/SeriesTest.java diff --git a/README.md b/README.md index 7e4c078..e9b0a9e 100644 --- a/README.md +++ b/README.md @@ -14,4 +14,5 @@ Course related code - Section 7: OOPS Part2: Composition, Encapsulation and Polymorphism - Section 8: Arrays, ArrayList, AutoBoxing and LinkedList - Section 9: Abstract Classes, Inner Classes and Interfaces -- Section 10: Java Generics \ No newline at end of file +- Section 10: Java Generics +- Section 11: Naming Conventions, Packages, Scope, static keyword and final keyword \ No newline at end of file diff --git a/Section11/pom.xml b/Section11/pom.xml new file mode 100644 index 0000000..066e45a --- /dev/null +++ b/Section11/pom.xml @@ -0,0 +1,13 @@ + + + 4.0.0 + + + udemyjavacourse + JavaUdemyCourse + 0.0.1 + + Section11 + \ No newline at end of file diff --git a/Section11/src/main/java/challenge/packages/Main.java b/Section11/src/main/java/challenge/packages/Main.java new file mode 100644 index 0000000..0b3e8c0 --- /dev/null +++ b/Section11/src/main/java/challenge/packages/Main.java @@ -0,0 +1,29 @@ +package challenge.packages; + +public class Main { + public static void main(String[] args) { + int[] series = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + + //Print nth sum + System.out.println("----------------Sum Series-------------------------"); + for (int i : series) { + System.out.println("Sum of first " + i + " numbers is " + Series.nSum(i)); + } + System.out.println("------------------------------------------------"); + + + //Print nth sum + System.out.println("----------------Factorial series-------------------------"); + for (int i : series) { + System.out.println("Factorial(" + i + ") : " + Series.factorial(i)); + } + System.out.println("------------------------------------------------"); + + //Print fibonacci series + System.out.println("----------------Fibonacci Series-------------------------"); + for (int i : series) { + System.out.println("Fibonacci(" + i + ") : " + Series.fibonacci(i)); + } + System.out.println("------------------------------------------------"); + } +} diff --git a/Section11/src/main/java/challenge/packages/Series.java b/Section11/src/main/java/challenge/packages/Series.java new file mode 100644 index 0000000..ba48e35 --- /dev/null +++ b/Section11/src/main/java/challenge/packages/Series.java @@ -0,0 +1,53 @@ +package challenge.packages; + +public class Series { + + /** + * Sum of first n natural numbers + * + * @param n + * @return + */ + public static long nSum(int n) { + if (n <= 0) { + return 0; + } else { + //thanks to https://www.math-only-math.com/sum-of-first-n-natural-numbers.html + return ((n + 1) * n) / 2; + } + } + + /** + * get factorial of n numbers + * + * @param n + * @return + */ + public static long factorial(int n) { + + if (n <= 0) { + return -1; + } else if (n == 1) { + return 1; + } else { + //thanks to https://probabilityformula.org/factorial.html + return n * factorial(n - 1); + } + } + + /** + * Returns nth fibonacci number (starting from 0) + * + * @param n any non negative integer + * @return + */ + public static long fibonacci(int n) { + if (n <= 0) { + return 0; + } else if (n == 1) { + return 1; + } else { + return fibonacci(n - 1) + fibonacci(n - 2); + } + } +} diff --git a/Section11/src/main/java/challenge/scope/README.md b/Section11/src/main/java/challenge/scope/README.md new file mode 100644 index 0000000..f248c23 --- /dev/null +++ b/Section11/src/main/java/challenge/scope/README.md @@ -0,0 +1,17 @@ +## Scope +### Problem statement +- [X] Write a small program to read an integer from the keyboard +(using Scanner) and print out the times table for that number. +The table should run from 1 to 12. + +- [X] You are allowed to use one variable called scanner for your +Scanner instance. +- [X] You can use as many other variables as you need, but they must must all be called x. That includes any class instances and loop control variables that you may decide +to use. + +- [X] If you use a class, the class can be called X (capital), but any instances of it must be called x (lower case). +Any methods you create must also be called x. + +### Optional Challenge: +- [X] Change your program so that ALL variables (including the scanner +instance) are called x. \ No newline at end of file diff --git a/Section11/src/main/java/challenge/scope/X.java b/Section11/src/main/java/challenge/scope/X.java new file mode 100644 index 0000000..0c2696d --- /dev/null +++ b/Section11/src/main/java/challenge/scope/X.java @@ -0,0 +1,17 @@ +package challenge.scope; + +//Multiplier Table class +public class X { + private int x; + + public X(int x) { + this.x = x; + } + + public void printTable() { + System.out.println("Table of " + x); + for (int x = 1; x <= 12; x++) { + System.out.println(this.x + "\tX\t" + x + "\t=\t" + (x * this.x)); + } + } +} diff --git a/Section11/src/main/java/challenge/scope/main/X.java b/Section11/src/main/java/challenge/scope/main/X.java new file mode 100644 index 0000000..e94874b --- /dev/null +++ b/Section11/src/main/java/challenge/scope/main/X.java @@ -0,0 +1,13 @@ +package challenge.scope.main; + +import java.util.Scanner; + +public class X { + static Scanner x = new Scanner(System.in); + + public static void main(String[] args) { + System.out.print("Enter number : "); + challenge.scope.X x = new challenge.scope.X(X.x.nextInt()); + x.printTable(); + } +} diff --git a/Section11/src/test/java/challenge/packages/SeriesTest.java b/Section11/src/test/java/challenge/packages/SeriesTest.java new file mode 100644 index 0000000..24a229b --- /dev/null +++ b/Section11/src/test/java/challenge/packages/SeriesTest.java @@ -0,0 +1,57 @@ +package challenge.packages; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class SeriesTest { + + public static Stream sumOfNNumberData() { + return Stream.of( + Arguments.of(0, 0), + Arguments.of(10, 55), + Arguments.of(100000, 705082704), + Arguments.of(-10, 0) + ); + } + + public static Stream factorialData() { + return Stream.of( + Arguments.of(0, -1), + Arguments.of(1, 1), + Arguments.of(5, 120), + Arguments.of(-1, -1) + ); + } + + public static Stream fibonacciData() { + return Stream.of( + Arguments.of(0, 0), + Arguments.of(1, 1), + Arguments.of(9, 34), + Arguments.of(-1, 0) + ); + } + + @ParameterizedTest(name = "Sum of first {0} numbers is {1}") + @MethodSource("sumOfNNumberData") + void nSum(int num, long sumOfN) { + assertEquals(sumOfN, Series.nSum(num)); + } + + @ParameterizedTest(name = "Factorial of first {0} numbers is {1}") + @MethodSource("factorialData") + void factorial(int n, long factorialOfN) { + assertEquals(factorialOfN, Series.factorial(n)); + } + + @ParameterizedTest(name = "{0}th fibonacci number is {1}") + @MethodSource("fibonacciData") + void fibonacci(int n, long nThFibonacci) { + assertEquals(nThFibonacci, Series.fibonacci(n)); + } +} \ No newline at end of file diff --git a/pom.xml b/pom.xml index f01abdf..2c391a2 100644 --- a/pom.xml +++ b/pom.xml @@ -18,6 +18,7 @@ Section8 Section9 Section10 + Section11 @@ -42,5 +43,7 @@ 3.0.0-M3 + src/main/java + src/test/java \ No newline at end of file From 5bde5597af01c4d73b115d6dafec4587dff333af Mon Sep 17 00:00:00 2001 From: Om Paliwal Date: Sun, 8 Dec 2019 11:28:52 +0530 Subject: [PATCH 13/19] Section 11: Examples: final keyword, static keywords and static initializer block --- .../exercise/finalkeyword/ExampleClass.java | 16 +++++++ .../main/java/exercise/finalkeyword/Main.java | 17 +++++++ .../java/exercise/finalkeyword/Password.java | 45 +++++++++++++++++++ .../exercise/finalkeyword/PasswordMain.java | 13 ++++++ .../static_initializer/SIBExample.java | 29 ++++++++++++ .../static_initializer/SIBExampleMain.java | 9 ++++ .../main/java/example/interfaces/Test.java | 6 +++ pom.xml | 1 - 8 files changed, 135 insertions(+), 1 deletion(-) create mode 100644 Section11/src/main/java/exercise/finalkeyword/ExampleClass.java create mode 100644 Section11/src/main/java/exercise/finalkeyword/Main.java create mode 100644 Section11/src/main/java/exercise/finalkeyword/Password.java create mode 100644 Section11/src/main/java/exercise/finalkeyword/PasswordMain.java create mode 100644 Section11/src/main/java/exercise/static_initializer/SIBExample.java create mode 100644 Section11/src/main/java/exercise/static_initializer/SIBExampleMain.java create mode 100644 Section9/src/main/java/example/interfaces/Test.java diff --git a/Section11/src/main/java/exercise/finalkeyword/ExampleClass.java b/Section11/src/main/java/exercise/finalkeyword/ExampleClass.java new file mode 100644 index 0000000..28f30f1 --- /dev/null +++ b/Section11/src/main/java/exercise/finalkeyword/ExampleClass.java @@ -0,0 +1,16 @@ +package exercise.finalkeyword; + +public class ExampleClass { + + public static int instanceCount = 0; + private final int instanceNumber; + + public ExampleClass() { + instanceCount++; + this.instanceNumber = instanceCount; + } + + public int getInstanceNumber() { + return instanceNumber; + } +} diff --git a/Section11/src/main/java/exercise/finalkeyword/Main.java b/Section11/src/main/java/exercise/finalkeyword/Main.java new file mode 100644 index 0000000..2c3ec25 --- /dev/null +++ b/Section11/src/main/java/exercise/finalkeyword/Main.java @@ -0,0 +1,17 @@ +package exercise.finalkeyword; + +public class Main extends ExampleClass { + public static void main(String[] args) { + ExampleClass class1 = new ExampleClass(); + ExampleClass class2 = new ExampleClass(); + ExampleClass class3 = new ExampleClass(); + + System.out.println("Total instances of " + + ExampleClass.class.getSimpleName() + + " : " + ExampleClass.instanceCount); + + System.out.println(class1.getInstanceNumber()); + System.out.println(class2.getInstanceNumber()); + System.out.println(class3.getInstanceNumber()); + } +} diff --git a/Section11/src/main/java/exercise/finalkeyword/Password.java b/Section11/src/main/java/exercise/finalkeyword/Password.java new file mode 100644 index 0000000..13bc71e --- /dev/null +++ b/Section11/src/main/java/exercise/finalkeyword/Password.java @@ -0,0 +1,45 @@ +package exercise.finalkeyword; + +public class Password { + private int key = 9876543; + private int encryptedPassword; + + public Password(int password) { + this.encryptedPassword = encryptDecrypt(password); + } + + private int encryptDecrypt(int password) { + return password ^ key; + } + + /** + * This is made final to prevent overriding by subclasses. + * Reason being that someone can do like below code + * + * public class ExtendedPassword extends Password { + * private int decryptedPassword; + * public ExtendedPassword(int password) { + * super(password); + * this.decryptedPassword = password; + * } + *

+ * \@Override public void storePassword() { + * System.out.println("Saving password as " + this.decryptedPassword); + * } + * } + * + */ + final void storePassword() { + System.out.println("Saving password as " + encryptedPassword); + } + + boolean logMeIn(int password) { + if (encryptDecrypt(password) == encryptedPassword) { + System.out.println("Welcome"); + return true; + } else { + System.out.println("Can't let you in buddy."); + return false; + } + } +} diff --git a/Section11/src/main/java/exercise/finalkeyword/PasswordMain.java b/Section11/src/main/java/exercise/finalkeyword/PasswordMain.java new file mode 100644 index 0000000..2fa2e4f --- /dev/null +++ b/Section11/src/main/java/exercise/finalkeyword/PasswordMain.java @@ -0,0 +1,13 @@ +package exercise.finalkeyword; + +public class PasswordMain { + public static void main(String[] args) { + Password password = new Password(123456); + password.storePassword(); + password.logMeIn(1); + password.logMeIn(-1); + password.logMeIn(0); + password.logMeIn(123465); + password.logMeIn(123456); + } +} diff --git a/Section11/src/main/java/exercise/static_initializer/SIBExample.java b/Section11/src/main/java/exercise/static_initializer/SIBExample.java new file mode 100644 index 0000000..62607de --- /dev/null +++ b/Section11/src/main/java/exercise/static_initializer/SIBExample.java @@ -0,0 +1,29 @@ +package exercise.static_initializer; + +public class SIBExample { + //This variable will be like constant + public static final String howYouDoin; + + static { + howYouDoin = "How you doing dear?"; + System.out.println("First static block called"); + } + + static { + System.out.println("Second static init block called"); + } + + public SIBExample() { + //Below will be compile error +// howYouDoin = "dfdfd"; + System.out.println("Constructor called"); + } + + public static String getString() { + return "SIBExample{" + + howYouDoin + + "}"; + } + + +} diff --git a/Section11/src/main/java/exercise/static_initializer/SIBExampleMain.java b/Section11/src/main/java/exercise/static_initializer/SIBExampleMain.java new file mode 100644 index 0000000..82e5d33 --- /dev/null +++ b/Section11/src/main/java/exercise/static_initializer/SIBExampleMain.java @@ -0,0 +1,9 @@ +package exercise.static_initializer; + +public class SIBExampleMain { + + public static void main(String[] args) { + SIBExample sibExample = new SIBExample(); + System.out.println(SIBExample.getString()); + } +} diff --git a/Section9/src/main/java/example/interfaces/Test.java b/Section9/src/main/java/example/interfaces/Test.java new file mode 100644 index 0000000..d0c0be1 --- /dev/null +++ b/Section9/src/main/java/example/interfaces/Test.java @@ -0,0 +1,6 @@ +package example.interfaces; + +interface Test { + int CONSTANT_VAR = 1000; + +} diff --git a/pom.xml b/pom.xml index 2c391a2..1078034 100644 --- a/pom.xml +++ b/pom.xml @@ -21,7 +21,6 @@ Section11 - org.junit.jupiter From 3315895b6f74f9c61c0b241aaf948f32aa2c129f Mon Sep 17 00:00:00 2001 From: krishnom Date: Tue, 10 Dec 2019 23:12:53 +0530 Subject: [PATCH 14/19] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index e9b0a9e..54d14af 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ [![Build Status](https://travis-ci.org/Krishnom/UdemyJavaCourse.svg?branch=master)](https://travis-ci.org/Krishnom/UdemyJavaCourse) - +[Code Quality](https://www.codacy.com/gh/Krishnom/UdemyJavaCourse?utm_source=github.com&utm_medium=referral&utm_content=Krishnom/UdemyJavaCourse&utm_campaign=Badge_Grade_Dashboard) # UdemyJavaCourse Course related code @@ -15,4 +15,4 @@ Course related code - Section 8: Arrays, ArrayList, AutoBoxing and LinkedList - Section 9: Abstract Classes, Inner Classes and Interfaces - Section 10: Java Generics -- Section 11: Naming Conventions, Packages, Scope, static keyword and final keyword \ No newline at end of file +- Section 11: Naming Conventions, Packages, Scope, static keyword and final keyword From 13d00c9fd522dafbd3a5cceec4e00d0f88d2b5bc Mon Sep 17 00:00:00 2001 From: krishnom Date: Tue, 10 Dec 2019 23:13:38 +0530 Subject: [PATCH 15/19] Code Quality Badge --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 54d14af..9ae98a7 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ [![Build Status](https://travis-ci.org/Krishnom/UdemyJavaCourse.svg?branch=master)](https://travis-ci.org/Krishnom/UdemyJavaCourse) -[Code Quality](https://www.codacy.com/gh/Krishnom/UdemyJavaCourse?utm_source=github.com&utm_medium=referral&utm_content=Krishnom/UdemyJavaCourse&utm_campaign=Badge_Grade_Dashboard) +[![Codacy Badge](https://api.codacy.com/project/badge/Grade/4cbe076de2f343af805b39540cebebdf)](https://www.codacy.com/gh/Krishnom/UdemyJavaCourse?utm_source=github.com&utm_medium=referral&utm_content=Krishnom/UdemyJavaCourse&utm_campaign=Badge_Grade) # UdemyJavaCourse Course related code From c9bbd2e46f7668a89957b9e2d9a812f509e685a6 Mon Sep 17 00:00:00 2001 From: krishnom Date: Sat, 4 Jan 2020 14:23:38 +0530 Subject: [PATCH 16/19] Integrate Github Action workflow for maven --- .github/workflows/maven.yml | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 .github/workflows/maven.yml diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml new file mode 100644 index 0000000..89cbf21 --- /dev/null +++ b/.github/workflows/maven.yml @@ -0,0 +1,17 @@ +name: Java CI + +on: [push] + +jobs: + build: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v1 + - name: Set up JDK 1.11 + uses: actions/setup-java@v1 + with: + java-version: 1.11 + - name: Build with Maven + run: mvn -B package --file pom.xml From a0c59a0a7903dcd58ac47775b00c984d8a1ec923 Mon Sep 17 00:00:00 2001 From: krishnom Date: Sat, 4 Jan 2020 14:30:12 +0530 Subject: [PATCH 17/19] Enable code coverage (#11) * Initial Commit: Enabling code coverage * Initial Commit: Code coverage status * enabled code coverage using coveralls. https://github.com/trautonen/coveralls-maven-plugin * enabled code coverage using coveralls. https://github.com/trautonen/coveralls-maven-plugin * enabled code coverage using coveralls. https://github.com/trautonen/coveralls-maven-plugin --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 9ae98a7..49ef803 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,6 @@ [![Build Status](https://travis-ci.org/Krishnom/UdemyJavaCourse.svg?branch=master)](https://travis-ci.org/Krishnom/UdemyJavaCourse) -[![Codacy Badge](https://api.codacy.com/project/badge/Grade/4cbe076de2f343af805b39540cebebdf)](https://www.codacy.com/gh/Krishnom/UdemyJavaCourse?utm_source=github.com&utm_medium=referral&utm_content=Krishnom/UdemyJavaCourse&utm_campaign=Badge_Grade) + +[![Coverage Status](https://coveralls.io/repos/github/Krishnom/UdemyJavaCourse/badge.svg?branch=master)](https://coveralls.io/github/Krishnom/UdemyJavaCourse?branch=master) # UdemyJavaCourse Course related code From f32c35e356469161328f4abb71c2208389ebcfcf Mon Sep 17 00:00:00 2001 From: krishnom Date: Sat, 4 Jan 2020 14:31:18 +0530 Subject: [PATCH 18/19] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 49ef803..994980d 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ [![Build Status](https://travis-ci.org/Krishnom/UdemyJavaCourse.svg?branch=master)](https://travis-ci.org/Krishnom/UdemyJavaCourse) -[![Coverage Status](https://coveralls.io/repos/github/Krishnom/UdemyJavaCourse/badge.svg?branch=master)](https://coveralls.io/github/Krishnom/UdemyJavaCourse?branch=master) +[![Codacy Badge](https://api.codacy.com/project/badge/Grade/658b238e0b8e4ef0905d047ccd5eda7a)](https://www.codacy.com/manual/BalajiTechs/UdemyJavaCourse?utm_source=github.com&utm_medium=referral&utm_content=Krishnom/UdemyJavaCourse&utm_campaign=Badge_Grade) # UdemyJavaCourse Course related code From 1c29040b65e3d106c67834e4065d2953b36c36d8 Mon Sep 17 00:00:00 2001 From: krishnom Date: Sat, 4 Jan 2020 14:36:56 +0530 Subject: [PATCH 19/19] Update README.md --- README.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/README.md b/README.md index 994980d..53a3dda 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,4 @@ -[![Build Status](https://travis-ci.org/Krishnom/UdemyJavaCourse.svg?branch=master)](https://travis-ci.org/Krishnom/UdemyJavaCourse) - -[![Codacy Badge](https://api.codacy.com/project/badge/Grade/658b238e0b8e4ef0905d047ccd5eda7a)](https://www.codacy.com/manual/BalajiTechs/UdemyJavaCourse?utm_source=github.com&utm_medium=referral&utm_content=Krishnom/UdemyJavaCourse&utm_campaign=Badge_Grade) +[![Build Status](https://travis-ci.org/Krishnom/UdemyJavaCourse.svg?branch=master)](https://travis-ci.org/Krishnom/UdemyJavaCourse) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/658b238e0b8e4ef0905d047ccd5eda7a)](https://www.codacy.com/manual/BalajiTechs/UdemyJavaCourse?utm_source=github.com&utm_medium=referral&utm_content=Krishnom/UdemyJavaCourse&utm_campaign=Badge_Grade) # UdemyJavaCourse Course related code