├── Basic Web Project
└── phonebook
│ ├── target
│ └── classes
│ │ ├── application.properties
│ │ ├── phonebook
│ │ ├── entity
│ │ │ └── Contact.class
│ │ ├── PhonebookApplication.class
│ │ └── controller
│ │ │ └── ContactController.class
│ │ └── templates
│ │ └── index.html
│ ├── src
│ ├── main
│ │ ├── resources
│ │ │ ├── application.properties
│ │ │ └── templates
│ │ │ │ └── index.html
│ │ └── java
│ │ │ └── phonebook
│ │ │ ├── PhonebookApplication.java
│ │ │ ├── entity
│ │ │ └── Contact.java
│ │ │ └── controller
│ │ │ └── ContactController.java
│ └── test
│ │ └── java
│ │ └── phonebook
│ │ └── PhonebookApplicationTests.java
│ ├── .idea
│ ├── .gitignore
│ ├── encodings.xml
│ ├── misc.xml
│ ├── compiler.xml
│ └── jarRepositories.xml
│ └── pom.xml
├── Methods - Exercise
├── Videos
│ └── Methods_Videos.txt
└── Solutions
│ ├── NxNMatrix_07.java
│ ├── AddAndSubtract_05.java
│ ├── SmallestOfThreeNumbers_01.java
│ ├── VowelsCount_02.java
│ ├── CharactersInRange_03.java
│ ├── FactorialDivision_08.java
│ ├── MiddleCharacters_06.java
│ ├── PalindromeIntegers_09.java
│ ├── TopNumber_10.java
│ └── PasswordValidator_04.java
├── Basic Syntax, Conditional Statements and Loops - Exercise
├── Videos
│ └── BasicSyntax_Videos.txt
└── Solutions
│ ├── TriangleOfNumbers_08.java
│ ├── Orders_09.java
│ ├── PrintAndSum_04.java
│ ├── Ages_01.java
│ ├── Division_02.java
│ ├── RageExpenses_11.java
│ ├── StrongNumber_06.java
│ ├── PadawanEquipment_10.java
│ ├── Login_05.java
│ ├── Vacation_03.java
│ └── VendingMachine_07.java
├── Objects and Classes - Exercise
├── Videos
│ └── ObjectsAndClasses_Exercise_Videos.txt
└── Solutions
│ ├── AdvertisementMessage_01
│ ├── Main.java
│ └── Message.java
│ ├── OpinionPoll_03
│ ├── Person.java
│ └── Main.java
│ ├── OrderByAge_06
│ ├── Person.java
│ └── Main.java
│ ├── Students_04
│ ├── Student.java
│ └── Main.java
│ ├── groomingSalon
│ ├── Main.java
│ ├── Pet.java
│ └── GroomingSalon.java
│ ├── Articles_02
│ ├── Article.java
│ └── Main.java
│ └── VehicleCatalogue_05
│ ├── Vehicle.java
│ └── Main.java
├── Text Procressing - Exercise
├── Videos
│ └── Textprocessing_Ex_Videos.txt
├── Demos
│ ├── DemoChars.java
│ └── DemoStrings.java
└── Solutions
│ ├── ReplaceRepeatingChars_06.java
│ ├── CaeserCipher_04.java
│ ├── ExtractFile_03.java
│ ├── MultiplyBigNumbers_05.java
│ ├── StringExplosion_07.java
│ ├── MultiplyBigNumbers2_05.java
│ ├── ValidUsernames_01.java
│ ├── CharacterMultiplier_02.java
│ └── LettersChangeNumbers_08.java
├── Maps - Exercise
├── Videos
│ └── Maps-Exercise_Videos.txt
└── Solutions
│ ├── CompanyUsers_08.java
│ ├── MinerTask_02.java
│ ├── Courses_05.java
│ ├── CountCharsInAString_01.java
│ ├── SoftUniParking_04.java
│ ├── SoftUniExamResults_10.java
│ ├── StudentAcademy_06.java
│ ├── Orders_03.java
│ ├── Forcebook_09.java
│ └── LegendaryFarming_07.java
├── Arrays - Exercise
├── Videos
│ └── Arrays_Exercise_Videos.txt
└── Solutions
│ ├── MaxSequenceEqualElements_07.java
│ ├── MagicSum_08.java
│ ├── CommonElements_02.java
│ ├── ArrayRotation_04.java
│ ├── Train_01.java
│ ├── TopIntegers_05.java
│ ├── ZigZagArrays_3.java
│ ├── EqualSums_06.java
│ ├── TreasureHunt_10.java
│ └── ArrayModifier_09.java
├── Data Types and Variables - Exercise
├── Videos
│ └── DataTypesAndVariables_Videos.txt
└── Solutions
│ ├── Elevator_03.java
│ ├── IntegerOperations_01.java
│ ├── SumOfChars_04.java
│ ├── TriplesLatinLetters_06.java
│ ├── PrintPart_05.java
│ ├── WaterOverflow_07.java
│ ├── SpiceMustFlow_09.java
│ ├── BeerKegs_08.java
│ ├── SumDigits_02.java
│ ├── Snowballs_11.java
│ └── Pokemon_10.java
├── Lists - Exercise
├── Videos
│ └── Lists_Exercise_Videos.txt
└── Solutions
│ ├── BombNumbers_05.java
│ ├── AppendArrays_07.java
│ ├── HouseParty_03.java
│ ├── Train_01.java
│ ├── ChangeList_02.java
│ ├── CardsGame_06.java
│ ├── PokemonDontGo_09.java
│ ├── AnonymousThreat_08.java
│ └── SoftuniCoursePlaning_10.java
├── RegEx - Exercise
├── ExtractEmails_06.java
├── SoftuniBarIncome_03.java
├── NetherRealms_05.java
├── Furniture_01.java
├── Race_02.java
└── StarEnigma_04.java
├── Lists - Lab
├── ListOfProducts_06.java
├── GaussTrick_02.java
├── SumAdjacentEqualNumbers_01.java
├── RemoveNegativesAndReverse_07.java
├── MergingLists_03.java
├── ListManipulationsBasics_04.java
└── ListManipulationsAdvanced_05.java
├── Mid-Exam-Preparation
├── BlackFlag_01.java
├── TheFlag_02.java
└── Numbers_03.java
├── Final-Exam-Preparation-1
├── TheImitationGame_01.java
├── EmojiDetector_02.java
└── NeedForSpeed_03.java
└── Final-Exam-Preparation-2
├── MirrorWords_02.java
├── WorldTour_01.java
└── ThePianist_03.java
/Basic Web Project/phonebook/target/classes/application.properties:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/Basic Web Project/phonebook/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/Basic Web Project/phonebook/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 |
--------------------------------------------------------------------------------
/Methods - Exercise/Videos/Methods_Videos.txt:
--------------------------------------------------------------------------------
1 | 11. Array Manipulator -> https://youtu.be/q20FbOcR1qM
2 | 10. Lady Bugs -> https://youtu.be/gH7P3RXPTXQ
--------------------------------------------------------------------------------
/Basic Web Project/phonebook/target/classes/phonebook/entity/Contact.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DesislavaTopuzakova/Java-Fundamentals-January-2023/HEAD/Basic Web Project/phonebook/target/classes/phonebook/entity/Contact.class
--------------------------------------------------------------------------------
/Basic Web Project/phonebook/target/classes/phonebook/PhonebookApplication.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DesislavaTopuzakova/Java-Fundamentals-January-2023/HEAD/Basic Web Project/phonebook/target/classes/phonebook/PhonebookApplication.class
--------------------------------------------------------------------------------
/Basic Web Project/phonebook/.idea/encodings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Basic Web Project/phonebook/target/classes/phonebook/controller/ContactController.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DesislavaTopuzakova/Java-Fundamentals-January-2023/HEAD/Basic Web Project/phonebook/target/classes/phonebook/controller/ContactController.class
--------------------------------------------------------------------------------
/Basic Syntax, Conditional Statements and Loops - Exercise/Videos/BasicSyntax_Videos.txt:
--------------------------------------------------------------------------------
1 | 10. Padawan Equipment -> https://pastebin.com/udpW9C6D
2 | видео: https://youtu.be/tButUIUb7u8
3 |
4 | 05. Messages (More Exercises) -> https://pastebin.com/yjbH1Ren
5 | видео: https://youtu.be/fzg7eWRZdE0
--------------------------------------------------------------------------------
/Objects and Classes - Exercise/Videos/ObjectsAndClasses_Exercise_Videos.txt:
--------------------------------------------------------------------------------
1 | 05. Vehicle Catalogue -> https://pastebin.com/i7u1fvYp
2 | видео: https://youtu.be/3yxpwIGZnzc
3 |
4 | 02. Articles -> https://pastebin.com/PPLYjm6K
5 | видео от 52:00 -> https://softuni.bg/trainings/resources/video/77020/video-28-october-2022-desislava-topuzakova-programming-fundamentals-with-java-september-2022/3837
--------------------------------------------------------------------------------
/Text Procressing - Exercise/Videos/Textprocessing_Ex_Videos.txt:
--------------------------------------------------------------------------------
1 | 03. Extract Files (59:00) -> https://softuni.bg/trainings/resources/video/77378/video-11-november-2022-desislava-topuzakova-programming-fundamentals-with-java-september-2022/3837
2 |
3 | 07. String Explosion (1:26:00) -> https://softuni.bg/trainings/resources/video/77378/video-11-november-2022-desislava-topuzakova-programming-fundamentals-with-java-september-2022/3837
--------------------------------------------------------------------------------
/Basic Web Project/phonebook/src/main/java/phonebook/PhonebookApplication.java:
--------------------------------------------------------------------------------
1 | package phonebook;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class PhonebookApplication {
8 |
9 | public static void main(String[] args) {
10 | SpringApplication.run(PhonebookApplication.class, args);
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/Maps - Exercise/Videos/Maps-Exercise_Videos.txt:
--------------------------------------------------------------------------------
1 | 02. A Miner Task -> https://pastebin.com/33NN2cwG
2 | видео: https://youtu.be/ChHMQXbx-BE?t=2560
3 |
4 | 03. Orders -> https://pastebin.com/BHiCkuGW
5 | видео: https://youtu.be/ChHMQXbx-BE?t=3516
6 |
7 | 05. Courses -> https://pastebin.com/HiHB0BHe
8 | видео: https://youtu.be/ChHMQXbx-BE?t=3710
9 |
10 | 10. SoftUni Exam Results -> https://pastebin.com/LFaraC9W
11 | видео: https://youtu.be/ChHMQXbx-BE?t=7414
--------------------------------------------------------------------------------
/Basic Web Project/phonebook/src/test/java/phonebook/PhonebookApplicationTests.java:
--------------------------------------------------------------------------------
1 | package phonebook;
2 |
3 | import org.junit.Test;
4 | import org.junit.runner.RunWith;
5 | import org.springframework.boot.test.context.SpringBootTest;
6 | import org.springframework.test.context.junit4.SpringRunner;
7 |
8 | @RunWith(SpringRunner.class)
9 | @SpringBootTest
10 | public class PhonebookApplicationTests {
11 |
12 | @Test
13 | public void contextLoads() {
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/Text Procressing - Exercise/Demos/DemoChars.java:
--------------------------------------------------------------------------------
1 | public class DemoChars {
2 | public static void main(String[] args) {
3 | char letter = 'T';
4 | int number = 66;
5 |
6 | System.out.println((int) letter); //ascii кода на моя символ
7 | System.out.println((char) number); //символа с дадения ascii код
8 |
9 | System.out.println('a' + 'c'); //int + int = int
10 | System.out.println("" + 'a' + 'c'); //"" + 'a' = "a" + 'c' = "ac"
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/Arrays - Exercise/Videos/Arrays_Exercise_Videos.txt:
--------------------------------------------------------------------------------
1 | 07. Max Sequence of Equal Elements -> https://pastebin.com/fiudHYva
2 | видео: https://youtu.be/Po6e3xLR_k8
3 |
4 | 05. Top Integers -> https://pastebin.com/31nu1L63
5 | видео: https://youtu.be/NCgPXDs0J50?t=8153
6 |
7 | 09. Array Modifier -> https://pastebin.com/uiRqkbkP
8 | видео: https://softuni.bg/trainings/resources/video/75973/video-30-september-2022-desislava-topuzakova-programming-fundamentals-with-java-september-2022/3837
9 |
10 | 10. Lady Bugs: https://youtu.be/gH7P3RXPTXQ
--------------------------------------------------------------------------------
/Basic Web Project/phonebook/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/Objects and Classes - Exercise/Solutions/AdvertisementMessage_01/Main.java:
--------------------------------------------------------------------------------
1 | package AdvertisementMessage_01;
2 |
3 | import java.util.Scanner;
4 |
5 | public class Main {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 |
9 | Message message = new Message();
10 | int n = Integer.parseInt(scanner.nextLine());
11 |
12 | for (int i = 0; i < n; i++) {
13 | String output = message.randomMessage();
14 | System.out.println(output);
15 | }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/Data Types and Variables - Exercise/Videos/DataTypesAndVariables_Videos.txt:
--------------------------------------------------------------------------------
1 | 07. Water Overflow -> https://pastebin.com/g3PJh8jQ
2 | видео: https://youtu.be/bMZkPePJ1Dw
3 |
4 | 11. Snowballs -> https://pastebin.com/9tkTBQx1
5 | видео: https://youtu.be/2fzK6GqGbkg
6 |
7 | 01. Data Type Finder (More Exercises) -> https://pastebin.com/tLbKDUzJ
8 | видео: https://youtu.be/vlDS4DD1Q4s
9 |
10 | 09. Spice Must Flow -> https://pastebin.com/2Nfzfgix
11 | видео: https://softuni.bg/trainings/resources/video/72245/video-27-may-2022-desislava-topuzakova-programming-fundamentals-with-java-may-2022/3731
12 |
--------------------------------------------------------------------------------
/Data Types and Variables - Exercise/Solutions/Elevator_03.java:
--------------------------------------------------------------------------------
1 | package DataTypes;
2 |
3 | import java.util.Scanner;
4 |
5 | public class Elevator_03 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 | int countPeople = Integer.parseInt(scanner.nextLine());
9 | int capacity = Integer.parseInt(scanner.nextLine());
10 |
11 | //курсове = хората / капацитета -> дробно число -> нагоре -> отпечатвам
12 | double courses = Math.ceil(countPeople * 1.0 / capacity);
13 | System.out.printf("%.0f", courses);
14 |
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/Methods - Exercise/Solutions/NxNMatrix_07.java:
--------------------------------------------------------------------------------
1 | package Methods;
2 |
3 | import java.util.Scanner;
4 |
5 | public class NxNMatrix_07 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 | int n = Integer.parseInt(scanner.nextLine()); //брой редове = брой колони
9 | printMatrix(n);
10 | }
11 |
12 | public static void printMatrix(int n) {
13 | for (int row = 1; row <= n; row++) {
14 | for (int col = 1; col <= n; col++) {
15 | System.out.print(n + " ");
16 | }
17 | System.out.println();
18 | }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/Basic Syntax, Conditional Statements and Loops - Exercise/Solutions/TriangleOfNumbers_08.java:
--------------------------------------------------------------------------------
1 | package BasicSyntax;
2 |
3 | import java.util.Scanner;
4 |
5 | public class TriangleOfNumbers_08 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 | int n = Integer.parseInt(scanner.nextLine());
9 |
10 | for (int row = 1; row <= n ; row++) {
11 | //колко пъти да печатам нещо
12 | for (int count = 1; count <= row ; count++) {
13 | System.out.print(row + " ");
14 | }
15 | System.out.println();
16 |
17 | }
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/Basic Web Project/phonebook/src/main/java/phonebook/entity/Contact.java:
--------------------------------------------------------------------------------
1 | package phonebook.entity;
2 |
3 | public class Contact {
4 | private String name;
5 | private String number;
6 |
7 | public Contact(String name, String number) {
8 | this.name = name;
9 | this.number = number;
10 | }
11 |
12 | public String getName() {
13 | return name;
14 | }
15 |
16 | public void setName(String name) {
17 | this.name = name;
18 | }
19 |
20 | public String getNumber() {
21 | return number;
22 | }
23 |
24 | public void setNumber(String number) {
25 | this.number = number;
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/Data Types and Variables - Exercise/Solutions/IntegerOperations_01.java:
--------------------------------------------------------------------------------
1 | package DataTypes;
2 |
3 | import java.util.Scanner;
4 |
5 | public class IntegerOperations_01 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 | int firstNumber = Integer.parseInt(scanner.nextLine());
9 | int secondNumber = Integer.parseInt(scanner.nextLine());
10 | int thirdNumber = Integer.parseInt(scanner.nextLine());
11 | int forthNumber = Integer.parseInt(scanner.nextLine());
12 |
13 | int result = ((firstNumber + secondNumber) / thirdNumber) * forthNumber;
14 | System.out.println(result);
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/Objects and Classes - Exercise/Solutions/OpinionPoll_03/Person.java:
--------------------------------------------------------------------------------
1 | package OpinionPoll_03;
2 |
3 | public class Person {
4 | //полета -> характеристики (име, възраст)
5 | private String name;
6 | private int age;
7 |
8 | //конструктор -> метод, чрез който създаваме обекти от клас
9 | public Person (String name, int age) {
10 | //нов празен обект
11 | this.name = name;
12 | this.age = age;
13 | }
14 |
15 | //getters -> методи, които ни дават коя е стойността срещу съответното поле
16 | public String getName() {
17 | return this.name;
18 | }
19 |
20 | public int getAge() {
21 | return this.age;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/Data Types and Variables - Exercise/Solutions/SumOfChars_04.java:
--------------------------------------------------------------------------------
1 | package DataTypes;
2 |
3 | import java.util.Scanner;
4 |
5 | public class SumOfChars_04 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 |
9 | int n = Integer.parseInt(scanner.nextLine()); //брой на символите
10 | int sum = 0; //сума на аски кодовете
11 |
12 | for (int count = 1; count <= n; count++) {
13 | char symbol = scanner.nextLine().charAt(0);
14 | int asciiCode = (int) symbol;
15 | sum += asciiCode; //sum = sum + asciiCode;
16 | }
17 |
18 | System.out.println("The sum equals: " + sum);
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/Text Procressing - Exercise/Solutions/ReplaceRepeatingChars_06.java:
--------------------------------------------------------------------------------
1 | package TextProcessing;
2 | import java.util.Scanner;
3 | public class ReplaceRepeatingChars_06 {
4 | public static void main(String[] args) {
5 | Scanner scanner = new Scanner(System.in);
6 | String inputText = scanner.nextLine();
7 | StringBuilder builder = new StringBuilder(inputText);
8 |
9 | for (int index = 0; index < builder.length() - 1 ; index++) {
10 | if(builder.charAt(index) == builder.charAt(index + 1)) {
11 | builder.deleteCharAt(index + 1);
12 | index--;
13 | }
14 | }
15 |
16 | System.out.println(builder);
17 |
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/Objects and Classes - Exercise/Solutions/OrderByAge_06/Person.java:
--------------------------------------------------------------------------------
1 | package OrderByAge_06;
2 |
3 | public class Person {
4 | //полета -> характеристики (name, id, age)
5 | private String name;
6 | private String id;
7 | private int age;
8 |
9 | //constructor
10 | public Person(String name, String id, int age) {
11 | //нов празен обект
12 | this.name = name;
13 | this.id = id;
14 | this.age = age;
15 | }
16 |
17 | //getters
18 | public String getName() {
19 | return this.name;
20 | }
21 |
22 | public String getId() {
23 | return this.id;
24 | }
25 |
26 | public int getAge() {
27 | return this.age;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/Text Procressing - Exercise/Solutions/CaeserCipher_04.java:
--------------------------------------------------------------------------------
1 | package TextProcessing;
2 |
3 | import java.util.Scanner;
4 |
5 | public class CaeserCipher_04 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 | String text = scanner.nextLine(); //първоначалния текст: "Programming is cool!"
9 | StringBuilder encryptedText = new StringBuilder(); //криптирания текст = ""
10 |
11 | for (char symbol : text.toCharArray()) {
12 | //'A' -> 'D'
13 | char encryptSymbol = (char)(symbol + 3); //криптирания символ
14 | encryptedText.append(encryptSymbol);
15 | }
16 |
17 | System.out.println(encryptedText);
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/Data Types and Variables - Exercise/Solutions/TriplesLatinLetters_06.java:
--------------------------------------------------------------------------------
1 | package DataTypes;
2 |
3 | import java.util.Scanner;
4 |
5 | public class TriplesLatinLetters_06 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 | int n = Integer.parseInt(scanner.nextLine());
9 | //тройки от символи: {буква1}{буква2}{буква3}
10 |
11 | for (char letter1 = 'a'; letter1 < 'a' + n ; letter1++) {
12 | for (char letter2 = 'a'; letter2 < 'a' + n; letter2++) {
13 | for (char letter3 = 'a'; letter3 < 'a' + n; letter3++) {
14 | System.out.printf("%c%c%c%n", letter1, letter2, letter3);
15 | }
16 | }
17 | }
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/Data Types and Variables - Exercise/Solutions/PrintPart_05.java:
--------------------------------------------------------------------------------
1 | package DataTypes;
2 |
3 | import java.util.Scanner;
4 |
5 | public class PrintPart_05 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 |
9 | int startCode = Integer.parseInt(scanner.nextLine()); //код, от който започвам
10 | int endCode = Integer.parseInt(scanner.nextLine()); // код, в който трябва да приключа
11 |
12 | //повтаряме: печатам кой е символа срещу съответния код
13 | //начало: startCode
14 | //край: endCode
15 | //промяна: +1 (преминавам към следващия код)
16 |
17 | for (int code = startCode; code <= endCode; code++) {
18 | System.out.print((char) code + " ");
19 | }
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/Basic Web Project/phonebook/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/Data Types and Variables - Exercise/Solutions/WaterOverflow_07.java:
--------------------------------------------------------------------------------
1 | package DataTypes;
2 |
3 | import java.util.Scanner;
4 |
5 | public class WaterOverflow_07 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 | int capacity = 255;
9 | int currentLiters = 0;
10 | int n = Integer.parseInt(scanner.nextLine());
11 | for (int i = 1; i <= n; i++) {
12 | int pouredLiters = Integer.parseInt(scanner.nextLine());
13 | currentLiters += pouredLiters;
14 | if(currentLiters > capacity) {
15 | System.out.println("Insufficient capacity!");
16 | currentLiters -= pouredLiters;
17 | }
18 | }
19 |
20 | System.out.println(currentLiters);
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/Lists - Exercise/Videos/Lists_Exercise_Videos.txt:
--------------------------------------------------------------------------------
1 | 01. Train -> https://pastebin.com/iNUGcesV
2 | видео: https://youtu.be/3VTWzepe9Bw?t=125
3 | 02. Change List -> https://pastebin.com/q8YkCytX
4 | 03. House Party -> https://pastebin.com/3jZ9fP6H
5 | видео: https://youtu.be/qjqKzdzS8cU?t=5092
6 | 04. List Operations -> https://pastebin.com/WWQMcqyv
7 | 05. Bomb Numbers -> https://pastebin.com/etfjys5k
8 | 06. Cards Game -> https://pastebin.com/S3wHpqps
9 | видео: https://youtu.be/qjqKzdzS8cU?t=7789
10 | 07. Append Arrays -> https://pastebin.com/uEgm6z6p
11 | видео: https://youtu.be/qjqKzdzS8cU?t=9615
12 | 08. Anonymous Threat -> https://pastebin.com/rDZKRHam
13 | 09. Pokemon Don't Go -> https://pastebin.com/9G5wB3Ln
14 | 10. SoftUni Course Planning -> https://pastebin.com/6f7jiuXC
15 | видео: https://youtu.be/g7Z2Vlh-RBg?t=8096
--------------------------------------------------------------------------------
/Objects and Classes - Exercise/Solutions/Students_04/Student.java:
--------------------------------------------------------------------------------
1 | package Students_04;
2 |
3 | public class Student {
4 | //полета -> характеристики (firstName, lastName, grade)
5 | private String firstName;
6 | private String lastName;
7 | private double grade;
8 |
9 | //конструктор -> метод, чрез който създаваме обекти от класа
10 | public Student (String fn, String ln, double grade) {
11 | //нов празен обект
12 | this.firstName = fn;
13 | this.lastName = ln;
14 | this.grade = grade;
15 | }
16 |
17 | //getters
18 | public double getGrade() {
19 | return this.grade;
20 | }
21 |
22 | public String getFirstName() {
23 | return this.firstName;
24 | }
25 |
26 | public String getLastName() {
27 | return this.lastName;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/Text Procressing - Exercise/Solutions/ExtractFile_03.java:
--------------------------------------------------------------------------------
1 | package TextProcessing;
2 | import java.util.Scanner;
3 | public class ExtractFile_03 {
4 | public static void main(String[] args) {
5 | Scanner scanner = new Scanner(System.in);
6 |
7 | String path = scanner.nextLine();
8 | //"C:\Internal\training-internal\Template.pptx"
9 | int indexLast = path.lastIndexOf("\\");
10 | String fullFileName = path.substring(indexLast + 1); //"Template.pptx"
11 |
12 | int indexPoint = fullFileName.indexOf(".");
13 | String fileName = fullFileName.substring(0, indexPoint);
14 | String fileExtension = fullFileName.substring(indexPoint + 1);
15 |
16 | System.out.println("File name: " + fileName);
17 | System.out.println("File extension: " + fileExtension);
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/RegEx - Exercise/ExtractEmails_06.java:
--------------------------------------------------------------------------------
1 | package RegEx;
2 |
3 | import java.util.Scanner;
4 | import java.util.regex.Matcher;
5 | import java.util.regex.Pattern;
6 |
7 | public class ExtractEmails_06 {
8 | public static void main(String[] args) {
9 | Scanner scanner = new Scanner(System.in);
10 |
11 | String regex = "[0-9A-Za-z]+[.\\-_]?[0-9A-Za-z]+@[A-Za-z]+-?[A-Za-z]+(\\.[A-Za-z]+-?[A-Za-z]+)+";
12 | Pattern pattern = Pattern.compile(regex);
13 |
14 | String text = scanner.nextLine();
15 | Matcher matcher = pattern.matcher(text);
16 | //text = "Just send email to s.miller@mit.edu and j.hopking@york.ac.uk for more information."
17 | //matcher = ["s.miller@mit.edu", "j.hopking@york.ac.uk"]
18 |
19 | while (matcher.find()) {
20 | System.out.println(matcher.group());
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/Basic Syntax, Conditional Statements and Loops - Exercise/Solutions/Orders_09.java:
--------------------------------------------------------------------------------
1 | package BasicSyntax;
2 |
3 | import java.util.Scanner;
4 |
5 | public class Orders_09 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 | int orders = Integer.parseInt(scanner.nextLine());
9 | double allMoney = 0;
10 | for (int order = 1; order <= orders; order++) {
11 | double pricePerCapsule = Double.parseDouble(scanner.nextLine());
12 | int daysInMonth = Integer.parseInt(scanner.nextLine());
13 | int capsulesCount = Integer.parseInt(scanner.nextLine());
14 | double moneyForOrder = ((daysInMonth * capsulesCount) * pricePerCapsule);
15 | System.out.printf("The price for the coffee is: $%.2f%n", moneyForOrder);
16 | allMoney += moneyForOrder;
17 | }
18 | System.out.printf("Total: $%.2f", allMoney);
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/Basic Web Project/phonebook/.idea/jarRepositories.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/Lists - Lab/ListOfProducts_06.java:
--------------------------------------------------------------------------------
1 | package Lists_Lab;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Collections;
5 | import java.util.List;
6 | import java.util.Scanner;
7 |
8 | public class ListOfProducts_06 {
9 | public static void main(String[] args) {
10 | Scanner scanner = new Scanner(System.in);
11 |
12 | int n = Integer.parseInt(scanner.nextLine()); //брой на продуктите
13 | List products = new ArrayList<>(); //списък с продуктите
14 |
15 | for (int i = 1; i <= n; i++) {
16 | String product = scanner.nextLine(); //име на продукта
17 | products.add(product);
18 | }
19 |
20 | Collections.sort(products);
21 | //sort (списък от текстове) -> в нарастващ (азбучен) ред (a -> z)
22 |
23 | int number = 1;
24 | for (String product : products) {
25 | System.out.println(number + "." + product);
26 | number++;
27 | }
28 |
29 |
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/Basic Syntax, Conditional Statements and Loops - Exercise/Solutions/PrintAndSum_04.java:
--------------------------------------------------------------------------------
1 | package BasicSyntax;
2 |
3 | import java.util.Scanner;
4 |
5 | public class PrintAndSum_04 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 |
9 | int startNumber = Integer.parseInt(scanner.nextLine()); // начало на интервал
10 | int endNumber = Integer.parseInt(scanner.nextLine()); // край на интервал
11 |
12 | //FOR цикъл
13 | //начало: startNumber
14 | //край: endNumber
15 | //повтаряме: отпечатваме числото
16 | //промяна: +1
17 |
18 | int sum = 0; //сума на числата
19 | for (int number = startNumber; number <= endNumber; number++) {
20 | System.out.print(number + " ");
21 | sum = sum + number; //sum += number;
22 | }
23 | //System.out.printf("%nSum: %d", sum);
24 | System.out.println(); //сваляме курсора на нов ред
25 | System.out.println("Sum: " + sum);
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/Methods - Exercise/Solutions/AddAndSubtract_05.java:
--------------------------------------------------------------------------------
1 | package Methods;
2 |
3 | import java.util.Scanner;
4 |
5 | public class AddAndSubtract_05 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 | //входни данни -> 3 цели числа
9 | int number1 = Integer.parseInt(scanner.nextLine());
10 | int number2 = Integer.parseInt(scanner.nextLine());
11 | int number3 = Integer.parseInt(scanner.nextLine());
12 | //(number1 + number2) - number3
13 |
14 | int sumOfNumbers = sum(number1, number2);
15 | int subtractOfNumbers = subtract(sumOfNumbers, number3);
16 |
17 | System.out.println(subtractOfNumbers);
18 | }
19 |
20 | //метод, който приема 2 цели числа -> получаваме сбора
21 | public static int sum (int n1, int n2) {
22 | return n1 + n2;
23 | }
24 |
25 | //метод, който приема 2 цели числа -> получаваме разлика
26 | public static int subtract (int n1, int n2) {
27 | return n1 - n2;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/Lists - Lab/GaussTrick_02.java:
--------------------------------------------------------------------------------
1 | package Lists_Lab;
2 | import java.util.Arrays;
3 | import java.util.List;
4 | import java.util.Scanner;
5 | import java.util.stream.Collectors;
6 | public class GaussTrick_02 {
7 | public static void main(String[] args) {
8 | Scanner scanner = new Scanner(System.in);
9 |
10 | List numList = Arrays.stream(scanner.nextLine().split(" "))
11 | .map(Integer::parseInt)
12 | .collect(Collectors.toList());
13 |
14 | int sizeList = numList.size();
15 |
16 | for (int i = 0; i < sizeList / 2; i++) {
17 | int firstNum = numList.get(i);
18 | int secondNum = numList.get(numList.size() - 1);
19 |
20 | numList.set(i, firstNum + secondNum);
21 |
22 | numList.remove(numList.size() - 1);
23 | }
24 |
25 | //System.out.println(numList.toString().replaceAll("[\\[\\],]", ""));
26 |
27 | for (int element: numList) {
28 | System.out.print(element + " ");
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/Basic Syntax, Conditional Statements and Loops - Exercise/Solutions/Ages_01.java:
--------------------------------------------------------------------------------
1 | package BasicSyntax;
2 |
3 | import java.util.Scanner;
4 |
5 | public class Ages_01 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 |
9 | //1. възраст - цяло число
10 | //2. проверка на възрастта
11 | //• 0-2 – baby; - ok
12 | //• 3-13 – child; - ok
13 | //• 14-19 – teenager; - ok
14 | //• 20-65 – adult;
15 | //• >=66 – elder;
16 |
17 | int age = Integer.parseInt(scanner.nextLine());
18 | if (age >= 0 && age <= 2) {
19 | System.out.println("baby");
20 | } else if (age >= 3 && age <= 13) {
21 | System.out.println("child");
22 | } else if (age >= 14 && age <= 19) {
23 | System.out.println("teenager");
24 | } else if (age >= 20 && age <= 65) {
25 | System.out.println("adult");
26 | } else if (age >= 66) {
27 | System.out.println("elder");
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/Methods - Exercise/Solutions/SmallestOfThreeNumbers_01.java:
--------------------------------------------------------------------------------
1 | package Methods;
2 |
3 | import java.util.Scanner;
4 |
5 | public class SmallestOfThreeNumbers_01 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 | int number1 = Integer.parseInt(scanner.nextLine());
9 | int number2 = Integer.parseInt(scanner.nextLine());
10 | int number3 = Integer.parseInt(scanner.nextLine());
11 |
12 | //метод, който да принтира най-малкото измежду 3 числа
13 | printSmallestNumber(number1, number2, number3);
14 | }
15 |
16 | public static void printSmallestNumber (int n1, int n2, int n3) {
17 | //първото число да е най-малко
18 | if (n1 < n2 && n1 < n3) {
19 | System.out.println(n1);
20 | }
21 | //второто число да е най-малко
22 | else if (n2 < n1 && n2 < n3) {
23 | System.out.println(n2);
24 | }
25 | //третото число да е най-малко
26 | else {
27 | System.out.println(n3);
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/Text Procressing - Exercise/Solutions/MultiplyBigNumbers_05.java:
--------------------------------------------------------------------------------
1 | package TextProcessing;
2 |
3 | import java.math.BigInteger;
4 | import java.util.Scanner;
5 |
6 | public class MultiplyBigNumbers_05 {
7 | public static void main(String[] args) {
8 | Scanner scanner = new Scanner(System.in);
9 |
10 | BigInteger firstNumber = new BigInteger(scanner.nextLine());//"923847238931983192462832102"
11 | BigInteger secondNumber = new BigInteger(scanner.nextLine()); // "2"
12 |
13 | System.out.println(firstNumber.multiply(secondNumber)); //умножение
14 |
15 | //int -> BigInteger
16 | //int number = 3; //String.valueOf(number) => "3"
17 | //BigInteger big = new BigInteger(String.valueOf(number));
18 | //new BigInteger(int + "")
19 |
20 | //Аритметични операции
21 | //System.out.println(firstNumber.add(secondNumber)); //събиране
22 | //System.out.println(firstNumber.subtract(secondNumber)); //изваждане
23 | //System.out.println(firstNumber.divide(secondNumber)); // деление
24 |
25 |
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/Arrays - Exercise/Solutions/MaxSequenceEqualElements_07.java:
--------------------------------------------------------------------------------
1 | package Arrays;
2 |
3 | import java.util.Scanner;
4 | import java.util.Arrays;
5 |
6 | public class MaxSequenceEqualElements_07 {
7 | public static void main(String[] args) {
8 | Scanner scanner = new Scanner(System.in);
9 |
10 | int [] array = Arrays.stream(scanner.nextLine().split(" ")).mapToInt(e -> Integer.parseInt(e)).toArray();
11 | int maxLength = 0;
12 | int length = 1;
13 |
14 | int startIndex = 0;
15 | int bestStart = 0;
16 |
17 | for (int i = 1; i < array.length; i++) {
18 | if(array[i] == array[i - 1]) {
19 | length++;
20 | } else {
21 | length = 1;
22 | startIndex = i;
23 | }
24 |
25 | if(length > maxLength) {
26 | maxLength = length;
27 | bestStart = startIndex;
28 | }
29 | }
30 |
31 | for (int i = bestStart; i < bestStart + maxLength; i++) {
32 | System.out.print(array[i] + " ");
33 | }
34 |
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/Data Types and Variables - Exercise/Solutions/SpiceMustFlow_09.java:
--------------------------------------------------------------------------------
1 | package DataTypes;
2 |
3 | import java.util.Scanner;
4 |
5 | public class SpiceMustFlow_09 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 | int source = Integer.parseInt(scanner.nextLine()); //бр. подправки в полето
9 | //повтаряме всеки ден -> добив = yield - 26; намалям силата на полето с 10
10 | //стоп: бр. подправки в полето < 100
11 | //продължаваме: бр. подправки в полето >= 100
12 |
13 | int days = 0; //бр дни добив
14 | int totalAmountSpices = 0; //общо количество добити подправки
15 | while (source >= 100) {
16 | int spices = source - 26; //добив
17 | totalAmountSpices += spices;
18 | days++;
19 | source = source - 10;
20 | }
21 |
22 | System.out.println(days);
23 | //изяждат 26 подправки при пътуването до другата нива
24 | if (totalAmountSpices >= 26) {
25 | totalAmountSpices -= 26;
26 | }
27 | System.out.println(totalAmountSpices);
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/Lists - Exercise/Solutions/BombNumbers_05.java:
--------------------------------------------------------------------------------
1 | package Lists_Exercise;
2 |
3 | import java.util.Arrays;
4 | import java.util.List;
5 | import java.util.Scanner;
6 | import java.util.stream.Collectors;
7 |
8 | public class BombNumbers_05 {
9 | public static void main(String[] args) {
10 | Scanner scanner = new Scanner(System.in);
11 |
12 | List elements = Arrays.stream(scanner.nextLine()
13 | .split("\\s+"))
14 | .collect(Collectors.toList());
15 |
16 | String[] data = scanner.nextLine().split("\\s+");
17 | String bombNumber = data[0];
18 | int power = Integer.parseInt(data[1]);
19 |
20 | while (elements.contains(bombNumber)) {
21 | int elementIndex = elements.indexOf(bombNumber);
22 |
23 | int left = Math.max(0, elementIndex - power);
24 | int right = Math.min(elementIndex + power, elements.size() - 1);
25 |
26 | for (int i = right; i >= left; i--) {
27 | elements.remove(i);
28 |
29 | }
30 | }
31 | System.out.println(elements.stream().mapToInt(Integer::parseInt).sum());
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/Objects and Classes - Exercise/Solutions/OpinionPoll_03/Main.java:
--------------------------------------------------------------------------------
1 | package OpinionPoll_03;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.Scanner;
6 |
7 | public class Main {
8 | public static void main(String[] args) {
9 | Scanner scanner = new Scanner(System.in);
10 |
11 | List peopleList = new ArrayList<>();
12 |
13 | int n = Integer.parseInt(scanner.nextLine()); //брой на хората
14 | for (int p = 1; p <= n; p++) {
15 | String data = scanner.nextLine(); //"Peter 12".split(" ") -> ["Peter", "12"]
16 | String name = data.split("\\s+")[0]; //име на човека
17 | int age = Integer.parseInt(data.split("\\s+")[1]); //възраст на човека
18 |
19 | if (age > 30) {
20 | Person person = new Person(name, age); //човек
21 | peopleList.add(person);
22 | }
23 | }
24 |
25 | for (Person person : peopleList) {
26 | //човек
27 | //име на човека (name) - възраст на човека (age)
28 | System.out.println(person.getName() + " - " + person.getAge());
29 | }
30 |
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/Data Types and Variables - Exercise/Solutions/BeerKegs_08.java:
--------------------------------------------------------------------------------
1 | package DataTypes;
2 |
3 | import java.util.Scanner;
4 |
5 | public class BeerKegs_08 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 |
9 | int n = Integer.parseInt(scanner.nextLine()); //брой на кегове с бира
10 |
11 | double maxVolume = Double.MIN_VALUE; //максималния обем = 0
12 | String maxModel = ""; // модел на кега с най-голям обем
13 | for (int keg = 1; keg <= n; keg++) {
14 | //въвеждаме информация
15 | String model = scanner.nextLine(); //модел / вид на кега
16 | double radius = Double.parseDouble(scanner.nextLine()); //радиус
17 | int height = Integer.parseInt(scanner.nextLine()); //височина
18 | //намираме обем = π * r^2 * h
19 | double volume = Math.PI * Math.pow(radius, 2) * height;
20 | //проверка дали обема е максимален
21 | if (volume > maxVolume) {
22 | maxVolume = volume;
23 | maxModel = model;
24 | }
25 | }
26 |
27 | System.out.println(maxModel);
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/Methods - Exercise/Solutions/VowelsCount_02.java:
--------------------------------------------------------------------------------
1 | package Methods;
2 |
3 | import java.util.Scanner;
4 |
5 | public class VowelsCount_02 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 | String text = scanner.nextLine();
9 |
10 | //метод, който принтира брой на гласните букви в текст
11 | printVowelsCount(text);
12 |
13 | }
14 |
15 | public static void printVowelsCount (String text) {
16 | //гласни букви: a, e, i, o, u, A, E, I, O, U
17 | //text = "Desislava"
18 | //.toLowerCase() -> "desislava"
19 | // .toCharArray() -> ['d', 'e', 's', 'i', ...]
20 |
21 | //"DeSiSlava".toLowerCase() -> "desislava"
22 | //"desilava".toUpperCase() -> "DESISLAVA"
23 |
24 | int count = 0; //брой на гласните букви
25 | for (char symbol : text.toLowerCase().toCharArray()) {
26 | //проверка дали е гласна буква
27 | if (symbol == 'a'|| symbol == 'e' || symbol == 'i' || symbol == 'o' || symbol == 'u') {
28 | count++;
29 | }
30 | }
31 |
32 | System.out.println(count);
33 |
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/Text Procressing - Exercise/Solutions/StringExplosion_07.java:
--------------------------------------------------------------------------------
1 | package TextProcessing;
2 | import java.util.Scanner;
3 | public class StringExplosion_07 {
4 | public static void main(String[] args) {
5 | Scanner scanner = new Scanner(System.in);
6 | String input = scanner.nextLine();
7 | //"abv>1>1>2>2asdasd"
8 | StringBuilder text = new StringBuilder(input);
9 |
10 | int totalStrength = 0; //сила
11 | for (int position = 0; position < text.length() ; position++) {
12 | char currentSymbol = text.charAt(position);
13 | if (currentSymbol == '>') {
14 | //char ('1') -> string ("1") -> int (1)
15 | //атака
16 | int attackStrength = Integer.parseInt(text.charAt(position + 1) + ""); //сила на атаката
17 | totalStrength += attackStrength;
18 | } else if (currentSymbol != '>' && totalStrength > 0) {
19 | //премахване
20 | text.deleteCharAt(position);
21 | totalStrength--;
22 | position--;
23 |
24 | }
25 | }
26 | System.out.println(text);
27 |
28 |
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/Basic Web Project/phonebook/src/main/java/phonebook/controller/ContactController.java:
--------------------------------------------------------------------------------
1 | package phonebook.controller;
2 |
3 | import org.springframework.stereotype.Controller;
4 | import org.springframework.web.bind.annotation.GetMapping;
5 | import org.springframework.web.bind.annotation.PostMapping;
6 | import org.springframework.web.servlet.ModelAndView;
7 | import phonebook.entity.Contact;
8 |
9 | import java.util.ArrayList;
10 | import java.util.List;
11 |
12 | @Controller
13 | public class ContactController {
14 | private List contacts;
15 |
16 | public ContactController() {
17 | this.contacts = new ArrayList<>();
18 | }
19 |
20 | @GetMapping("/")
21 | public ModelAndView index (ModelAndView modelAndView) {
22 | this.contacts.add(new Contact("Desi", "1234"));
23 | this.contacts.add(new Contact("Pesho", "123"));
24 | modelAndView.setViewName("index");
25 | modelAndView.addObject("contacts", contacts);
26 | return modelAndView;
27 | }
28 |
29 |
30 | @PostMapping("/")
31 | public String add (Contact contact) {
32 | this.contacts.add(contact);
33 | return "redirect:/";
34 | }
35 |
36 | }
37 |
--------------------------------------------------------------------------------
/Methods - Exercise/Solutions/CharactersInRange_03.java:
--------------------------------------------------------------------------------
1 | package Methods;
2 |
3 | import java.util.Scanner;
4 |
5 | public class CharactersInRange_03 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 | //входни данни: 2 символа
9 | char symbol1 = scanner.nextLine().charAt(0);
10 | char symbol2 = scanner.nextLine().charAt(0);
11 |
12 | printCharactersInRange(symbol1, symbol2);
13 | }
14 |
15 | public static void printCharactersInRange(char symbol1, char symbol2) {
16 | //проверка кой е по-малкия символ -> започвам от по-малкия
17 | if (symbol1 < symbol2) {
18 | //започваме от symbol1 -> символите в (symbol1, symbol2)
19 | for (char symbol = (char)(symbol1 + 1); symbol < symbol2 ; symbol++) {
20 | System.out.print(symbol + " ");
21 | }
22 | } else { //symbol1 >= symbol2
23 | //започваме от symbol2 -> символите в (symbol2, symbol1)
24 | for (char symbol = (char)(symbol2 + 1); symbol < symbol1 ; symbol++) {
25 | System.out.print(symbol + " ");
26 | }
27 | }
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/Maps - Exercise/Solutions/CompanyUsers_08.java:
--------------------------------------------------------------------------------
1 | package Maps;
2 | import java.util.*;
3 |
4 | public class CompanyUsers_08 {
5 | public static void main(String[] args) {
6 | Scanner scanner = new Scanner(System.in);
7 |
8 | Map> listOfEmployees = new LinkedHashMap<>();
9 |
10 | String input = scanner.nextLine();
11 | while (!input.equals("End")) {
12 | String[] info = input.split(" -> ");
13 |
14 | List currentCompanyEmployees = listOfEmployees.get(info[0]);
15 | boolean containsId = currentCompanyEmployees != null && currentCompanyEmployees.contains(info[1]);
16 |
17 | if (!containsId) {
18 | listOfEmployees.putIfAbsent(info[0], new ArrayList<>());
19 | listOfEmployees.get(info[0]).add(info[1]);
20 | }
21 |
22 |
23 | input = scanner.nextLine();
24 | }
25 |
26 | listOfEmployees.entrySet().stream()
27 | .forEach(c -> {
28 | System.out.printf("%s%n", c.getKey());
29 | c.getValue().forEach(e -> System.out.printf("-- %s%n", e));
30 | });
31 |
32 |
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/Arrays - Exercise/Solutions/MagicSum_08.java:
--------------------------------------------------------------------------------
1 | package Arrays;
2 |
3 | import java.util.Arrays;
4 | import java.util.Scanner;
5 |
6 | public class MagicSum_08 {
7 | public static void main(String[] args) {
8 | Scanner scanner = new Scanner(System.in);
9 | int [] numbers = Arrays.stream(scanner.nextLine() //"1 7 6 2 19 23"
10 | .split(" ")) //["1", "7", "6", "2", "19", "23"]
11 | .mapToInt(e -> Integer.parseInt(e)) //[1, 7, 6, 2, 19, 23]
12 | .toArray();
13 |
14 | int targetSum = Integer.parseInt(scanner.nextLine());
15 |
16 | //обхождаме всички елементи в масива
17 | for (int index = 0; index < numbers.length - 1; index++) {
18 | int currentNumber = numbers[index]; //числото от масива на текущия индекс
19 | //обходя всички числа след моето
20 | for (int i = index + 1; i <= numbers.length - 1; i++) {
21 | int nextNumber = numbers[i]; //число, което е след моето
22 |
23 | if (currentNumber + nextNumber == targetSum) {
24 | System.out.println(currentNumber + " " + nextNumber);
25 | }
26 | }
27 | }
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/Objects and Classes - Exercise/Solutions/groomingSalon/Main.java:
--------------------------------------------------------------------------------
1 | package groomingSalon;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | public class Main {
7 | public static void main(String[] args) {
8 | // Initialize the repository
9 | GroomingSalon salon = new GroomingSalon(20);
10 |
11 | // Initialize entity
12 | Pet dog = new Pet("Ellias", 5, "Tim");
13 |
14 | // Print Pet
15 | System.out.println(dog); // Ellias 5 - (Tim)
16 |
17 | // Add Pet
18 | salon.add(dog);
19 |
20 | // Remove Pet
21 | System.out.println(salon.remove("Ellias")); // true
22 | System.out.println(salon.remove("Pufa")); // false
23 |
24 | Pet cat = new Pet("Bella", 2, "Mia");
25 | Pet bunny = new Pet("Zak", 4, "Jon");
26 |
27 | salon.add(cat);
28 | salon.add(bunny);
29 |
30 | // Get Pet
31 | Pet pet = salon.getPet("Bella", "Mia");
32 | System.out.println(pet); // Bella 2 - (Mia)
33 |
34 | // Count
35 | System.out.println(salon.getCount()); // 2
36 |
37 | // Get Statistics
38 | System.out.println(salon.getStatistics());
39 | // The grooming salon has the following clients:
40 | //Bella Mia
41 | //Zak Jon
42 |
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/Data Types and Variables - Exercise/Solutions/SumDigits_02.java:
--------------------------------------------------------------------------------
1 | package DataTypes;
2 |
3 | import java.util.Scanner;
4 |
5 | public class SumDigits_02 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 |
9 | //1. входни данни
10 | int number = Integer.parseInt(scanner.nextLine());
11 |
12 | //2. намерим сумата от цифрите на числото
13 |
14 | int sumDigits = 0;//сума от цифрите
15 | //алгоритъм за взимане на цифрите на едно число
16 | //стоп: число <= 0
17 | //продължаваме: число > 0
18 | //повтаряме:
19 | //1. взимам последната цифра
20 | //2. сумирам цифрата
21 | //3. премахвам взетата цифра от числото
22 |
23 | while (number > 0) {
24 | //1. взимам последната цифра
25 | int lastDigit = number % 10;
26 | //2. сумирам цифрата
27 | sumDigits += lastDigit; //sumDigits = sumDigits + lastDigit;
28 | //3. премахвам взетата цифра от числото
29 | number = number / 10; //number /= 10;
30 | }
31 |
32 | //сумирали сме всички цифри
33 | System.out.println(sumDigits);
34 |
35 |
36 |
37 |
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/Lists - Exercise/Solutions/AppendArrays_07.java:
--------------------------------------------------------------------------------
1 | package Lists_Exercise;
2 |
3 | import java.util.Arrays;
4 | import java.util.Collections;
5 | import java.util.List;
6 | import java.util.Scanner;
7 | import java.util.stream.Collectors;
8 |
9 | public class AppendArrays_07 {
10 | public static void main(String[] args) {
11 | Scanner scanner = new Scanner(System.in);
12 | String input = scanner.nextLine(); //"1 2 3 |4 5 6 | 7 8"
13 | List listSeparatedByPipe = Arrays.stream(input.split("\\|")).collect(Collectors.toList());
14 | //"1 2 3 |4 5 6 | 7 8" -> split -> ["1 2 3 ", "4 5 6 ", " 7 8"] -> {"1 2 3 ", "4 5 6 ", " 7 8"}
15 | Collections.reverse(listSeparatedByPipe);
16 | // reverse -> {" 7 8", "4 5 6 ", "1 2 3 "}
17 |
18 | //list.toString() -> "7 8 4 5 6 1 2 3"
19 | System.out.println(listSeparatedByPipe.toString() //"[ 7 8, 4 5 6 , 1 2 3 ]"
20 | .replace("[", "") //" 7 8, 4 5 6 , 1 2 3 ]"
21 | .replace("]", "") //" 7 8, 4 5 6 , 1 2 3 "
22 | .trim() //"7 8, 4 5 6 , 1 2 3"
23 | .replaceAll(",", "") //"7 8 4 5 6 1 2 3"
24 | .replaceAll("\\s+", " ")); //"7 8 4 5 6 1 2 3"
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/Methods - Exercise/Solutions/FactorialDivision_08.java:
--------------------------------------------------------------------------------
1 | package Methods;
2 |
3 | import java.util.Scanner;
4 |
5 | public class FactorialDivision_08 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 |
9 | //1. входни данни -> 2 цели числа
10 | int number1 = Integer.parseInt(scanner.nextLine());
11 | int number2 = Integer.parseInt(scanner.nextLine());
12 |
13 | //2. факториел на първото число
14 | long fact1 = calculateFactorial(number1); //факториел на първото число
15 |
16 | //3. факториел на второто число
17 | long fact2 = calculateFactorial(number2); //факториел на второто число
18 |
19 | //4. ф1 / ф2 -> принт резултата
20 | double divisionFactorials = fact1 * 1.0 / fact2;
21 | System.out.printf("%.2f", divisionFactorials);
22 |
23 | }
24 |
25 | //метод, който връща резултат (факториел на дадено число)
26 |
27 | public static long calculateFactorial (int number) {
28 | //number = 5
29 | //5! = 1 * 2 * 3 * 4 * 5
30 | long fact = 1; //стойността на факториел
31 | for (int i = 1; i <= number; i++) {
32 | fact = fact * i;
33 | }
34 |
35 | return fact;
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/Objects and Classes - Exercise/Solutions/AdvertisementMessage_01/Message.java:
--------------------------------------------------------------------------------
1 | package AdvertisementMessage_01;
2 |
3 | import java.util.Random;
4 |
5 | public class Message {
6 |
7 | private Random random = new Random();
8 |
9 | private String[] phrases = {"Excellent product.", "Such a great product.",
10 | "I always use that product.", "Best product of its category."
11 | , "Exceptional product.", "I can’t live without this product."};
12 | private String[] events = {"Now I feel good.", "I have succeeded with this product.",
13 | "Makes miracles. I am happy of the results!",
14 | "I cannot believe but now I feel awesome.",
15 | "Try it yourself, I am very satisfied.", "I feel great!"};
16 | private String[] author = {"Diana", "Petya", "Stella", "Elena", "Katya", "Iva", "Annie", "Eva"};
17 | private String[] town = {"Burgas", "Sofia", "Plovdiv", "Varna", "Ruse"};
18 |
19 | public String randomMessage() {
20 |
21 | return String.format("%s %s %s - %s",
22 | phrases[random.nextInt(phrases.length)],
23 | events[random.nextInt(events.length)],
24 | author[random.nextInt(author.length)],
25 | town[random.nextInt(town.length)]);
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/Arrays - Exercise/Solutions/CommonElements_02.java:
--------------------------------------------------------------------------------
1 | package Arrays;
2 |
3 | import java.util.Scanner;
4 |
5 | public class CommonElements_02 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 |
9 | String firstRow = scanner.nextLine(); //"Hey hello 2 4"
10 | String secondRow = scanner.nextLine(); //"10 hey 4 hello"
11 |
12 | String[] firstArray = firstRow.split(" "); //["Hey", "hello", "2", "4"]
13 | String [] secondArray = secondRow.split(" "); //["10", "hey", "4", "hello"]
14 |
15 | //обхождам всички елементи на втория масив
16 | for (String secondElement : secondArray) {
17 | //какво повтарям за всеки елемент от втория масив: обхождам първия масив
18 | for (String firstElement : firstArray) {
19 | if (secondElement.equals(firstElement)) {
20 | //общ елемент в двата масива
21 | System.out.print(firstElement + " ");
22 | break;
23 | }
24 | }
25 | }
26 |
27 | //for loop -> трябва да работим с индексите на масива и да достъпваме елементите по индекс
28 | //foreach loop -> достъпваме всички елементи без значение от техния индекс
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/Maps - Exercise/Solutions/MinerTask_02.java:
--------------------------------------------------------------------------------
1 | package Maps;
2 | import java.util.*;
3 |
4 | public class MinerTask_02 {
5 | public static void main(String[] args) {
6 | Scanner scanner = new Scanner(System.in);
7 | Map resourcesQuantity = new LinkedHashMap<>();
8 | //ресурс -> сума от количество
9 | String resource = scanner.nextLine(); //ресурс или "stop"
10 | while(!resource.equals("stop")) {
11 | //ресурс
12 | int quantity = Integer.parseInt(scanner.nextLine());
13 | //проверка имам ли такъв ресурс
14 | //ако нямам такъв ресурс
15 | if(!resourcesQuantity.containsKey(resource)) {
16 | resourcesQuantity.put(resource, quantity);
17 | }
18 | //ако имам такъв ресурс
19 | else {
20 | int currentQuantity = resourcesQuantity.get(resource);
21 | resourcesQuantity.put(resource, currentQuantity + quantity);
22 | }
23 | resource = scanner.nextLine();
24 | }
25 |
26 | //resourcesQuantity.forEach((key, value) -> System.out.println(key + " -> " + value));
27 | resourcesQuantity.entrySet().forEach(entry -> System.out.println(entry.getKey() + " -> " + entry.getValue()));
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/Basic Syntax, Conditional Statements and Loops - Exercise/Solutions/Division_02.java:
--------------------------------------------------------------------------------
1 | package BasicSyntax;
2 |
3 | import java.util.Scanner;
4 |
5 | public class Division_02 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 |
9 | //1. входни данни -> цяло число
10 | int number = Integer.parseInt(scanner.nextLine());
11 |
12 | //2. проверка дали се дели на: 10, 7, 6, 3, 2
13 | if (number % 10 == 0) {
14 | //10 e делител на моето число
15 | System.out.println("The number is divisible by 10");
16 | } else if (number % 7 == 0) {
17 | //7 e делител на моето число
18 | System.out.println("The number is divisible by 7");
19 | } else if (number % 6 == 0) {
20 | //6 е делител на моето число
21 | System.out.println("The number is divisible by 6");
22 | } else if (number % 3 == 0) {
23 | //3 e делител на моето число
24 | System.out.println("The number is divisible by 3");
25 | } else if (number % 2 == 0) {
26 | //2 е делител на моето число
27 | System.out.println("The number is divisible by 2");
28 | } else {
29 | System.out.println("Not divisible");
30 | }
31 |
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/Data Types and Variables - Exercise/Solutions/Snowballs_11.java:
--------------------------------------------------------------------------------
1 | package DataTypes;
2 |
3 |
4 | import java.util.*;
5 |
6 | public class Snowballs_11 {
7 | public static void main(String[] args) {
8 | Scanner scanner = new Scanner(System.in);
9 | int n = Integer.parseInt(scanner.nextLine());
10 | double maxValue = Double.MIN_VALUE;
11 | int snowballSnowBiggest = 0;
12 | int snowballTTimeBiggest = 0;
13 | int snowballQualityBiggest = 0;
14 |
15 |
16 | for (int snowBall = 1; snowBall <= n; snowBall++) {
17 | int snowBallSnow = Integer.parseInt(scanner.nextLine());
18 | int snowBallTime = Integer.parseInt(scanner.nextLine());
19 | int snowBallQuality = Integer.parseInt(scanner.nextLine());
20 | double snowBallValue = Math.pow(snowBallSnow / snowBallTime, snowBallQuality);
21 |
22 | if (snowBallValue > maxValue){
23 | maxValue = snowBallValue;
24 | snowballSnowBiggest = snowBallSnow;
25 | snowballTTimeBiggest = snowBallTime;
26 | snowballQualityBiggest = snowBallQuality;
27 | }
28 |
29 | }
30 | System.out.printf("%d : %d = %.0f (%d) ",snowballSnowBiggest, snowballTTimeBiggest, maxValue ,snowballQualityBiggest );
31 |
32 |
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/Arrays - Exercise/Solutions/ArrayRotation_04.java:
--------------------------------------------------------------------------------
1 | package Arrays;
2 |
3 | import java.util.Scanner;
4 |
5 | public class ArrayRotation_04 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 | String [] array = scanner.nextLine().split(" ");
9 | //"51 47 32 61 21".split(" ") -> ["51", "47", "32", "61", "21"]
10 | int countRotations = Integer.parseInt(scanner.nextLine());
11 |
12 | for (int rotation = 1; rotation <= countRotations; rotation++) {
13 | //ротация на масива
14 | //1. взимам първия елемент
15 | String firstElement = array[0]; //"51"
16 |
17 | //2. преместваме елементите наляво
18 | //["51", "47", "32", "61", "21"] -> ["47", "32", "61", "21", "21"]
19 | for (int index = 0; index < array.length - 1 ; index++) {
20 | array[index] = array[index + 1];
21 | }
22 |
23 | //3. поставям първия елемент на последно място
24 | //["47", "32", "61", "21", "51"]
25 | array[array.length - 1] = firstElement;
26 | }
27 |
28 | //приключваме с ротациите -> принтираме всички елементи на масива
29 | for (String element : array) {
30 | System.out.print(element + " ");
31 | }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/Arrays - Exercise/Solutions/Train_01.java:
--------------------------------------------------------------------------------
1 | package Arrays;
2 |
3 | import java.util.Arrays;
4 | import java.util.Scanner;
5 |
6 | public class Train_01 {
7 | public static void main(String[] args) {
8 | Scanner scanner = new Scanner(System.in);
9 | int countWagons = Integer.parseInt(scanner.nextLine());
10 | //1. съхраним хората, които се качват
11 | int [] wagons = new int[countWagons];
12 | for (int wagon = 0; wagon < countWagons; wagon++) {
13 | int countPeople = Integer.parseInt(scanner.nextLine());
14 | wagons[wagon] = countPeople;
15 | }
16 | //[13, 24, 8]
17 | //2. отпечатаме
18 | //2.1. for -> индексите
19 | /*for (int index = 0; index <= wagons.length - 1; index++) {
20 | int currentElement = wagons[index];
21 | System.out.print(currentElement + " ");
22 | }
23 | System.out.println();*/
24 |
25 | //2.2. foreach -> елементите
26 | int sum = 0;
27 | for (int number : wagons) {
28 | //кодът, който искаме да повтаряме
29 | System.out.print(number + " ");
30 | sum += number;
31 | }
32 | System.out.println();
33 | System.out.println(sum);
34 | //3. сумираме хората
35 | //System.out.println(Arrays.stream(wagons).sum());
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/Objects and Classes - Exercise/Solutions/groomingSalon/Pet.java:
--------------------------------------------------------------------------------
1 | package groomingSalon;
2 |
3 | public class Pet {
4 | //полета -> характеристики (name, age, owner)
5 | private String name;
6 | private int age;
7 | private String owner;
8 |
9 | //конструктор, който създава обект по зададени всички полета
10 | //alt+insert
11 | public Pet (String name, int age, String owner) {
12 | //нов празен обект
13 | this.name = name;
14 | this.age = age;
15 | this.owner = owner;
16 | }
17 |
18 | //getters and setters
19 |
20 | //field name
21 | public String getName() {
22 | return this.name;
23 | }
24 |
25 | public void setName(String name) {
26 | this.name = name;
27 | }
28 |
29 | //field age
30 | public int getAge() {
31 | return this.age;
32 | }
33 |
34 | public void setAge(int age) {
35 | this.age = age;
36 | }
37 |
38 | //field owner
39 | public String getOwner() {
40 | return this.owner;
41 | }
42 |
43 | public void setOwner(String owner) {
44 | this.owner = owner;
45 | }
46 |
47 | //default -> "{package}.{class}@{address}"
48 | @Override //пренапишем
49 | public String toString() {
50 | //"{name} {age} - ({owner})"
51 | return this.name + " " + this.age + " - (" + this.owner + ")";
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/Objects and Classes - Exercise/Solutions/Articles_02/Article.java:
--------------------------------------------------------------------------------
1 | package Articles_02;
2 |
3 | public class Article {
4 | //полета -> характеристики
5 | private String title; //заглавие
6 | private String content; //съдържание
7 | private String author; //автор
8 |
9 | //конструктор -> създава нови обекти
10 | //alt + insert -> Constructor
11 | public Article(String title, String content, String author) {
12 | //нов обект
13 | this.title = title;
14 | this.content = content;
15 | this.author = author;
16 | }
17 |
18 | //методи -> поведение
19 | public void edit (String newContent){
20 | this.content = newContent;
21 | }
22 |
23 | public void changeAuthor (String newAuthor) {
24 | this.author = newAuthor;
25 | }
26 |
27 | public void rename (String newTitle) {
28 | this.title = newTitle;
29 | }
30 |
31 | //вграден метод toString -> превърне обекта в текст -> "{packageName}.{className}@{address}"
32 | @Override // пренаписва default method
33 | public String toString() {
34 | //{title} - {съдържание}: {автора}
35 | //return this.title + " - " + this.content + ": " + this.author;
36 | return String.format("%s - %s: %s", this.title, this.content, this.author);
37 | //вграден метод toString -> превърне обекта в текст -> "{title} - {съдържание}: {автора}"
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/Lists - Lab/SumAdjacentEqualNumbers_01.java:
--------------------------------------------------------------------------------
1 | package Lists_Lab;
2 |
3 | import java.text.DecimalFormat;
4 | import java.util.Arrays;
5 | import java.util.List;
6 | import java.util.Scanner;
7 |
8 | public class SumAdjacentEqualNumbers_01 {
9 | public static void main(String[] args) {
10 | Scanner scanner = new Scanner(System.in);
11 |
12 | List numbersList = new java.util.ArrayList<>(Arrays.stream(scanner.nextLine().split(" "))
13 | .map(Double::parseDouble).toList());
14 |
15 | for (int i = 0; i < numbersList.size() - 1; i++) {
16 | double firstEl = numbersList.get(i);
17 | double secondEl = numbersList.get(i + 1);
18 |
19 | if (firstEl == secondEl) {
20 | numbersList.set(i, numbersList.get(i) + numbersList.get(i + 1));
21 | numbersList.remove(i + 1);
22 |
23 | i = -1;
24 | }
25 | }
26 |
27 | System.out.println(joinElementsByDelimiter(numbersList, " "));
28 | }
29 |
30 | public static String joinElementsByDelimiter(List list, String delimiter) {
31 | String result = "";
32 | for (Double num : list) {
33 | DecimalFormat df = new DecimalFormat("0.#");
34 |
35 | String numFormat = df.format(num) + delimiter;
36 |
37 | result += numFormat;
38 | }
39 |
40 | return result;
41 | }
42 | }
--------------------------------------------------------------------------------
/Methods - Exercise/Solutions/MiddleCharacters_06.java:
--------------------------------------------------------------------------------
1 | package Methods;
2 |
3 | import java.util.Scanner;
4 |
5 | public class MiddleCharacters_06 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 |
9 | String text = scanner.nextLine();
10 | printMiddleCharacters(text); //text -> аргумент
11 |
12 | }
13 |
14 | //метод, който принтира средния символ на даден текст
15 | public static void printMiddleCharacters (String text) { //String text e параметър
16 | //нечетна дължина -> 1 среден символ
17 | //"aString" -> ['a', 'S', 't', 'r', 'i', 'n', 'g']
18 | if (text.length() % 2 != 0) {
19 | int indexOfMiddleCharacter = text.length() / 2;
20 | System.out.println(text.charAt(indexOfMiddleCharacter));
21 | }
22 | //четна дължина -> 2 средни символа
23 | //"someText" -> 8 символа (index: 3 и 4)
24 | //"dogs" -> 4 символа (index: 1 и 2)
25 | //['s', 'o', 'm', 'e', 'T', 'e', 'x', 't'] -> eT
26 | else {
27 | int indexOfFirstMiddleCharacter = text.length() / 2 - 1;
28 | int indexOfSecondMiddleCharacter = text.length() / 2; //indexOfFirstMiddleCharacter + 1
29 |
30 | System.out.print(text.charAt(indexOfFirstMiddleCharacter));
31 | System.out.print(text.charAt(indexOfSecondMiddleCharacter));
32 | }
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/Objects and Classes - Exercise/Solutions/OrderByAge_06/Main.java:
--------------------------------------------------------------------------------
1 | package OrderByAge_06;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Comparator;
5 | import java.util.List;
6 | import java.util.Scanner;
7 |
8 | public class Main {
9 | public static void main(String[] args) {
10 | Scanner scanner = new Scanner(System.in);
11 |
12 | List peopleList = new ArrayList<>();
13 | String data = scanner.nextLine();
14 |
15 | while (!data.equals("End")) {
16 | //data = "{name} {ID} {age}".split("\\s+") -> ["{name}", "{ID}", "{age}"]
17 | String name = data.split("\\s+")[0]; //име
18 | String id = data.split("\\s+")[1]; //ID
19 | int age = Integer.parseInt(data.split("\\s+")[2]); //"10" -> 10
20 |
21 | Person person = new Person(name, id, age);
22 | peopleList.add(person);
23 |
24 | data = scanner.nextLine();
25 | }
26 |
27 | //списък с хората
28 | //1. сортирам по възраст (ascending order)
29 | peopleList.sort(Comparator.comparing(Person::getAge));
30 |
31 | //2. принтираме данните за всеки човек
32 | for (Person person : peopleList) {
33 | //"Stephan with ID: 524244 is 10 years old."
34 | System.out.println(person.getName() + " with ID: " + person.getId() + " is " + person.getAge() + " years old.");
35 | }
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/Methods - Exercise/Solutions/PalindromeIntegers_09.java:
--------------------------------------------------------------------------------
1 | package Methods;
2 |
3 | import java.util.Scanner;
4 |
5 | public class PalindromeIntegers_09 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 |
9 | String command = scanner.nextLine(); //"323"
10 |
11 | //входни данни -> число под формата на текст или "END"
12 | while (!command.equals("END")) {
13 | //проверка дали е палиндром
14 | if (isPalindrome(command)) {
15 | System.out.println("true");
16 | } else {
17 | System.out.println("false");
18 | }
19 |
20 | //System.out.println(isPalindrome(command));
21 |
22 |
23 | command = scanner.nextLine();
24 | }
25 | }
26 |
27 | //метод, който проверява дали даден тескт е палиндром
28 | //true -> ако текстът е палиндром
29 | //false -> ако текстът не е палиндром
30 |
31 | public static boolean isPalindrome (String text) {
32 | //text = "Desi"
33 | //reversedText = "iseD"
34 | //палиндром е текст, който е еднакъв с обърнатия си на обратно
35 | String reversedText = ""; //текстът, обърнат на обратно
36 | for (int index = text.length() - 1; index >= 0 ; index--) {
37 | reversedText += text.charAt(index);
38 | }
39 |
40 | return text.equals(reversedText);
41 |
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/Lists - Lab/RemoveNegativesAndReverse_07.java:
--------------------------------------------------------------------------------
1 | package Lists_Lab;
2 |
3 | import java.util.*;
4 | import java.util.stream.Collectors;
5 |
6 | public class RemoveNegativesAndReverse_07 {
7 | public static void main(String[] args) {
8 | Scanner scanner = new Scanner(System.in);
9 |
10 | //1. прочитаме лист от цели числа
11 | List numbers = Arrays.stream(scanner.nextLine().split(" "))
12 | .map(Integer::parseInt).collect(Collectors.toList());
13 | //{10 -5 7 9 -33 50} -> {10 7 9 50}
14 |
15 | //numbers.removeIf(number -> number < 0); премахва всички отрицателни числа в списъка
16 |
17 | List positiveNumbers = new ArrayList<>(); //списък, в който ще има само положителни числа
18 |
19 | for (int number : numbers ) {
20 | if (number >= 0) {
21 | positiveNumbers.add(number);
22 | }
23 | }
24 |
25 | Collections.reverse(positiveNumbers);
26 | if (positiveNumbers.size() == 0) {
27 | System.out.println("empty");
28 | } else {
29 | /*System.out.println(positiveNumbers.toString()
30 | .replace("[", "")
31 | .replace("]", "")
32 | .replaceAll(",", ""));*/
33 | for (int number : positiveNumbers) {
34 | System.out.print(number + " ");
35 | }
36 |
37 | }
38 |
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/Lists - Lab/MergingLists_03.java:
--------------------------------------------------------------------------------
1 | package Lists_Lab;
2 | import java.util.ArrayList;
3 | import java.util.Arrays;
4 | import java.util.List;
5 | import java.util.Scanner;
6 | import java.util.stream.Collectors;
7 | public class MergingLists_03 {
8 | public static void main(String[] args) {
9 | Scanner scanner = new Scanner(System.in);
10 |
11 | List firstList = Arrays.stream(scanner.nextLine().split(" "))
12 | .map(Integer::parseInt)
13 | .collect(Collectors.toList());
14 |
15 | List secondList = Arrays.stream(scanner.nextLine().split(" "))
16 | .map(Integer::parseInt)
17 | .collect(Collectors.toList());
18 |
19 | List resultList = new ArrayList<>();
20 | int minSize = Math.min(firstList.size(), secondList.size());
21 | for (int i = 0; i < minSize; i++) {
22 | int firstItem = firstList.get(i);
23 | int secondItem = secondList.get(i);
24 |
25 | resultList.add(firstItem);
26 | resultList.add(secondItem);
27 | }
28 |
29 | if (firstList.size() > secondList.size()) {
30 | resultList.addAll(firstList.subList(minSize, firstList.size()));
31 | } else {
32 | resultList.addAll(secondList.subList(minSize, secondList.size()));
33 | }
34 |
35 | System.out.println(resultList.toString().replaceAll("[\\[\\],]", ""));
36 | }
37 | }
38 |
39 |
40 |
--------------------------------------------------------------------------------
/Basic Syntax, Conditional Statements and Loops - Exercise/Solutions/RageExpenses_11.java:
--------------------------------------------------------------------------------
1 | package BasicSyntax;
2 |
3 | import java.util.Scanner;
4 |
5 | public class RageExpenses_11 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 | //1. входни данни
9 | int lostGames = Integer.parseInt(scanner.nextLine());
10 | double headsetPrice = Double.parseDouble(scanner.nextLine());
11 | double mousePrice = Double.parseDouble(scanner.nextLine());
12 | double keyboardPrice = Double.parseDouble(scanner.nextLine());
13 | double displayPrice = Double.parseDouble(scanner.nextLine());
14 |
15 | //2. крайна сума = (бр. слушалки * headsetPrice)
16 | // + (бр. мишки * mousePrice)
17 | // + (бр. клавиатури * keyboardPrice)
18 | // + (бр. монитори * displayPrice)
19 |
20 | int countHeadset = lostGames / 2; //бр. слушалки
21 | int countMouse = lostGames / 3; //бр. мишки
22 | int countKeyboards = lostGames / 6; //бр. клавиатури
23 | int countDisplays = lostGames / 12; //бр. монитор
24 |
25 | double finalSum = (countHeadset * headsetPrice)
26 | + (countMouse * mousePrice)
27 | + (countKeyboards * keyboardPrice)
28 | + (countDisplays * displayPrice);
29 |
30 | System.out.printf("Rage expenses: %.2f lv.", finalSum);
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/Basic Syntax, Conditional Statements and Loops - Exercise/Solutions/StrongNumber_06.java:
--------------------------------------------------------------------------------
1 | package BasicSyntax;
2 |
3 | import java.util.Scanner;
4 |
5 | public class StrongNumber_06 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 |
9 | //1. входни данни -> цяло число
10 | int number = Integer.parseInt(scanner.nextLine());
11 | int startNumber = number; //първоначално въведенета стойност на числото
12 | //2. проверка дали числото е strong
13 | //ако е strong -> yes
14 | //ако не е string -> no
15 |
16 | //за всяка цифра
17 | //1. цифра - OK
18 | //2. факториел на цифра
19 | //3. сумирам факториел
20 |
21 | int sumFact = 0; //сума на факториели
22 | while (number > 0) { //стоп: number <= 0
23 | int lastDigit = number % 10;//взимаме последната цифра
24 | //намирам факториел на lastDigit
25 | int fact = 1; //факториела на текущата цифра
26 | for (int i = 1; i <= lastDigit; i++) {
27 | fact = fact * i;
28 | }
29 | //сумирам получения факториел на цифрата
30 | sumFact += fact;
31 | //премахвам последната цифра
32 | number = number / 10;
33 | }
34 |
35 | //сумата от факториелите на цифрите на числото
36 | if (sumFact == startNumber) {
37 | System.out.println("yes");
38 | } else {
39 | System.out.println("no");
40 | }
41 |
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/Data Types and Variables - Exercise/Solutions/Pokemon_10.java:
--------------------------------------------------------------------------------
1 | package DataTypes;
2 |
3 | import java.util.Scanner;
4 |
5 | public class Pokemon_10 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 | //1. входни данни
9 | int power = Integer.parseInt(scanner.nextLine()); //текуща сила
10 | int distance = Integer.parseInt(scanner.nextLine()); //разстояние между цели за удряне
11 | int factor = Integer.parseInt(scanner.nextLine()); //фактор на изтощение
12 |
13 | int startPower = power; //първоначална сила
14 | //повтаряме:
15 | //1. power - distance -> стигаме до целта си
16 | //2. удряме цел
17 | //stop: power < distance
18 | //продължавам: power >= distance
19 |
20 | int countTarget = 0; //брой ударени цели
21 | while (power >= distance) {
22 | //1. отивам до целта -> намаляме силата с изминатото разстояние
23 | power -= distance; //power = power - distance;
24 | //2. удряме цел
25 | countTarget++;
26 |
27 | //проверка за умора
28 | if (power == startPower / 2) {
29 | //сила / фактор
30 | if (factor != 0) {
31 | //позволена аритметична операция (деление)
32 | power = power / factor; // power /= factor;
33 | }
34 | }
35 | }
36 |
37 | System.out.println(power);
38 | System.out.println(countTarget);
39 |
40 |
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/Arrays - Exercise/Solutions/TopIntegers_05.java:
--------------------------------------------------------------------------------
1 | package Arrays;
2 |
3 | import java.util.Scanner;
4 | import java.util.Arrays;
5 |
6 | public class TopIntegers_05 {
7 | public static void main(String[] args) {
8 | Scanner scanner = new Scanner(System.in);
9 | int [] numbers = Arrays.stream(scanner.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
10 | //"1 4 3 2".split(" ") -> ["1", "4", "3", "2"].map -> [1, 4, 3, 2]
11 |
12 | //за всеки един елемент от масива -> проверка дали е топ
13 | for (int index = 0; index <= numbers.length - 1; index++) {
14 | int currentNumber = numbers[index];
15 | //винаги елементът на последния индекс ни е топ
16 | if(index == numbers.length - 1) {
17 | System.out.print(currentNumber + " ");
18 | break;
19 | }
20 | //обхождам всички индекси след моя
21 | //следващото число -> index + 1
22 | boolean isTop = false; //
23 | for (int i = index + 1; i <= numbers.length - 1; i++) { //обходя всички числа след моето
24 | int nextNumber = numbers[i];
25 | if (currentNumber > nextNumber) {
26 | isTop = true;
27 | } else {
28 | isTop = false;
29 | break;
30 | }
31 | }
32 | //проверка дали моето число е топ
33 | if (isTop) {
34 | System.out.print(currentNumber + " ");
35 | }
36 | }
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/Objects and Classes - Exercise/Solutions/VehicleCatalogue_05/Vehicle.java:
--------------------------------------------------------------------------------
1 | package VehicleCatalogue_05;
2 |
3 | public class Vehicle {
4 | //{typeOfVehicle} {model} {color} {horsepower}
5 | private String type;
6 | private String model;
7 |
8 | public void setType(String type) {
9 | this.type = type;
10 | }
11 |
12 | public void setModel(String model) {
13 | this.model = model;
14 | }
15 |
16 | public void setColor(String color) {
17 | this.color = color;
18 | }
19 |
20 | public void setHorsePower(int horsePower) {
21 | this.horsePower = horsePower;
22 | }
23 |
24 | public String getType() {
25 | return type;
26 | }
27 |
28 | public String getModel() {
29 | return model;
30 | }
31 |
32 | public String getColor() {
33 | return color;
34 | }
35 |
36 | public int getHorsePower() {
37 | return horsePower;
38 | }
39 |
40 | private String color;
41 | private int horsePower;
42 |
43 | public Vehicle(String type, String model, String color, int horsePower) {
44 | this.type = type;
45 | this.model = model;
46 | this.color = color;
47 | this.horsePower = horsePower;
48 | }
49 |
50 | @Override
51 | public String toString() {
52 | String typeVeh = type.equals("car") ? "Car" : "Truck";
53 | return "Type: " + typeVeh + "\n" +
54 | "Model: " + model + "\n" +
55 | "Color: " + color + "\n" +
56 | "Horsepower: " + horsePower;
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/Objects and Classes - Exercise/Solutions/Students_04/Main.java:
--------------------------------------------------------------------------------
1 | package Students_04;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Comparator;
5 | import java.util.List;
6 | import java.util.Scanner;
7 |
8 | public class Main {
9 | public static void main(String[] args) {
10 | Scanner scanner = new Scanner(System.in);
11 | List studentList = new ArrayList<>();
12 |
13 | int countStudents = Integer.parseInt(scanner.nextLine());
14 | for (int s = 1; s <= countStudents; s++) {
15 | String data = scanner.nextLine();
16 | //"Lakia Eason 3.90".split(" ") => ["Lakia", "Eason", "3.90"]
17 | String firstName = data.split("\\s+")[0]; //"Lakia"
18 | String lastName = data.split("\\s+")[1]; //"Eason"
19 | double grade = Double.parseDouble(data.split("\\s+")[2]); //"3.90" -> 3.90
20 |
21 | Student student = new Student(firstName, lastName, grade);
22 | studentList.add(student);
23 |
24 | }
25 |
26 | //списък със студенти
27 | //1. orders them by grade (in descending)
28 | studentList.sort(Comparator.comparing(Student::getGrade).reversed());
29 |
30 | //2. print students
31 | for (Student student : studentList) {
32 | //име фамилия: оценка
33 | //System.out.println(student.getFirstName() + " " + student.getLastName() + ": " + student.getGrade());
34 | System.out.printf("%s %s: %.2f%n", student.getFirstName(), student.getLastName(), student.getGrade());
35 | }
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/Arrays - Exercise/Solutions/ZigZagArrays_3.java:
--------------------------------------------------------------------------------
1 | package Arrays;
2 |
3 | import java.util.Scanner;
4 |
5 | public class ZigZagArrays_3 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in); //sc
8 |
9 | int n = Integer.parseInt(scanner.nextLine()); //брой редове
10 | int [] firstArray = new int[n];
11 | int [] secondArray = new int[n];
12 |
13 | for (int row = 1; row <= n; row++) {
14 | String numbers = scanner.nextLine(); //"1 5".split(" ") -> ["1", "5"]
15 | int firstNumber = Integer.parseInt(numbers.split(" ")[0]); //"1" -> 1
16 | int secondNumber = Integer.parseInt(numbers.split(" ")[1]); //"5" -> 5
17 |
18 | if (row % 2 == 0) {
19 | //четен ред -> първото число (втори масив); второто число (първи масив)
20 | firstArray[row - 1] = secondNumber;
21 | secondArray[row - 1] = firstNumber;
22 | } else {
23 | //нечетен ред -> първото число (първи масив); второто число (втори масив)
24 | firstArray[row - 1] = firstNumber;
25 | secondArray[row - 1] = secondNumber;
26 | }
27 | }
28 |
29 | //отпечатваме елементите на първия масив
30 | for (int number : firstArray) {
31 | System.out.print(number + " ");
32 | }
33 |
34 | System.out.println();
35 |
36 | //отпечатваме елементите на втория масив
37 | for (int number : secondArray) {
38 | System.out.print(number + " ");
39 | }
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/RegEx - Exercise/SoftuniBarIncome_03.java:
--------------------------------------------------------------------------------
1 | package RegEx;
2 |
3 | import java.util.Scanner;
4 | import java.util.regex.Matcher;
5 | import java.util.regex.Pattern;
6 |
7 | public class SoftuniBarIncome_03 {
8 | public static void main(String[] args) {
9 | Scanner scanner = new Scanner(System.in);
10 | String input = scanner.nextLine();
11 |
12 | String regex = "%(?[A-Z][a-z]*)%[^|$%.]*<(?\\w+)>[^|$%.]*\\|(?[0-9]+)\\|[^|$%.]*?(?[0-9]+\\.?[0-9]*)\\$";
13 | Pattern pattern = Pattern.compile(regex);
14 |
15 | double totalIncome = 0; //приход от всички продукти
16 | while (!input.equals("end of shift")) {
17 | //input = "%George%|2|10.3$"
18 | Matcher matcher = pattern.matcher(input);
19 | if (matcher.find()) {
20 | //валидна поръчка
21 | String customer = matcher.group("customerName"); //име на клиента
22 | String product = matcher.group("product"); //име на продукта
23 | int count = Integer.parseInt(matcher.group("count")); //брой на продукта
24 | double price = Double.parseDouble(matcher.group("price")); //ед. цена на продукта
25 |
26 | double totalPrice = count * price; //приход от текущия продукт
27 | totalIncome += totalPrice;
28 | System.out.printf("%s: %s - %.2f%n", customer, product, totalPrice);
29 | }
30 | input = scanner.nextLine();
31 | }
32 |
33 | System.out.printf("Total income: %.2f", totalIncome);
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/Mid-Exam-Preparation/BlackFlag_01.java:
--------------------------------------------------------------------------------
1 | package ExamPreparation;
2 |
3 | import java.util.Scanner;
4 |
5 | public class BlackFlag_01 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 |
9 | int days = Integer.parseInt(scanner.nextLine()); //общ брой дни за грабежи
10 | int plundersPerDay = Integer.parseInt(scanner.nextLine()); // грабежи за ден
11 | double targetCountPlunders = Double.parseDouble(scanner.nextLine()); //брой кражби, които са цел за постигане
12 |
13 | double totalPlunders = 0; //общ брой на грабеж
14 | for (int day = 1; day <= days; day++) {
15 | totalPlunders += plundersPerDay;
16 |
17 | if (day % 3 == 0) {
18 | double extraPlunders = 0.5 * plundersPerDay;
19 | totalPlunders += extraPlunders;
20 | }
21 |
22 | if (day % 5 == 0) {
23 | totalPlunders = totalPlunders - 0.3 * totalPlunders;
24 | //totalPlunders = 0.7 * totalPlunders
25 | //totalPlunders *= 0.70
26 | }
27 | }
28 | //какъв е общият брой на грабежите
29 | //проверка дали сме достигнали целта си
30 | if (totalPlunders >= targetCountPlunders) {
31 | System.out.printf("Ahoy! %.2f plunder gained.", totalPlunders);
32 | } else {
33 | //не сме успяли да постигнем целта
34 | double percent = (totalPlunders / targetCountPlunders) * 100;
35 | System.out.printf("Collected only %.2f%% of the plunder.", percent);
36 | }
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/Basic Syntax, Conditional Statements and Loops - Exercise/Solutions/PadawanEquipment_10.java:
--------------------------------------------------------------------------------
1 | package BasicSyntax;
2 |
3 | import java.util.Scanner;
4 |
5 | public class PadawanEquipment_10 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 | //обща сума = сума за мечове + сума за одежди + сума за колани
9 | //1. сума за мечове = бр. мечове(ученици + 10%) * цена за мечовете(вход)
10 | //2. сума за одежди = бр. одежди = бр. ученици * цена за одеждите(вход)
11 | //3. сума за колани = бр. коланите (ученици - ученици / 6) * цена за коланите(вход)
12 | double budget = Double.parseDouble(scanner.nextLine());
13 | int studentsCount = Integer.parseInt(scanner.nextLine());
14 | double priceLight = Double.parseDouble(scanner.nextLine());
15 | double priceRobe = Double.parseDouble(scanner.nextLine());
16 | double priceBelt = Double.parseDouble(scanner.nextLine());
17 |
18 | double sumLight = Math.ceil(studentsCount + 0.10 * studentsCount) * priceLight; //1.1 * studentsCount
19 | double sumRobes = studentsCount * priceRobe;
20 | double sumBelts = (studentsCount - studentsCount / 6) * priceBelt;
21 |
22 | double totalSum = sumLight + sumRobes + sumBelts; //крайната сума за плащане
23 |
24 | if(totalSum <= budget) {
25 | System.out.printf("The money is enough - it would cost %.2flv.", totalSum);
26 | } else {
27 | double needMoney = totalSum - budget;
28 | System.out.printf("George Lucas will need %.2flv more.", needMoney);
29 | }
30 |
31 |
32 | }
33 | }
--------------------------------------------------------------------------------
/Maps - Exercise/Solutions/Courses_05.java:
--------------------------------------------------------------------------------
1 | package Maps;
2 | import java.util.*;
3 | public class Courses_05 {
4 | public static void main(String[] args) {
5 | Scanner scanner = new Scanner(System.in);
6 | String input = scanner.nextLine();
7 | //име на курс -> списък с имената на студенти
8 | Map> courses = new LinkedHashMap<>();
9 | while(!input.equals("end")) {
10 | //"{име на курс} : {име на човек}" -> split (" : ") -> ["{courseName}", "{personName}"]
11 | String courseName = input.split(" : ")[0];
12 | String personName = input.split(" : ")[1];
13 | //прверка имам ли такъв курс
14 | //ако нямам такъв курс
15 | if(!courses.containsKey(courseName)) {
16 | courses.put(courseName, new ArrayList<>());
17 | }
18 |
19 | //ако курсът е нов -> връща празен списък
20 | //ако курсът е стар -> връща моментния списък с хора
21 | courses.get(courseName).add(personName);
22 |
23 | input = scanner.nextLine();
24 | }
25 | //courseName -> List
26 | courses.entrySet()
27 | .forEach(entry -> {
28 | //key: име на курса
29 | //value: списък с хората
30 | //име на курса -> бр. хората
31 | System.out.println(entry.getKey() + ": " + entry.getValue().size());
32 | entry.getValue().forEach(studentName -> System.out.println("-- " + studentName));
33 | //ascending order / нарастващ ред
34 | });
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/Text Procressing - Exercise/Solutions/MultiplyBigNumbers2_05.java:
--------------------------------------------------------------------------------
1 | package TextProcessing;
2 |
3 | import java.util.Scanner;
4 |
5 | public class MultiplyBigNumbers2_05 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 | String first = scanner.nextLine();
9 | int second = Integer.parseInt(scanner.nextLine());
10 | StringBuilder sb = new StringBuilder();
11 | int remain = 0;
12 | int printable = 0;
13 | for (int i = first.length() - 1; i >= 0; i--) {
14 | int digit = Integer.parseInt(first.substring(i, i + 1));
15 | int current = digit * second;
16 | current += remain;
17 | sb.append((current % 10));
18 | remain = current / 10;
19 | }
20 | if (remain != 0) {
21 | sb.append(remain);
22 | }
23 | boolean zero = true;
24 | for (int i = 0; i < sb.length(); i++) {
25 | if (Integer.parseInt(sb.substring(i, i + 1)) != 0) {
26 | zero = false;
27 | }
28 | }
29 | if (zero) {
30 | System.out.println(0);
31 | } else {
32 | StringBuilder output = new StringBuilder();
33 | boolean trailing = true;
34 | for (int i = sb.length() - 1; i >= 0; i--) {
35 | if (Integer.parseInt(sb.substring(i, i + 1)) == 0 && trailing) {
36 |
37 | } else {
38 | trailing = false;
39 | output.append(sb.charAt(i));
40 | }
41 | }
42 | System.out.println(output.toString());
43 | }
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/Maps - Exercise/Solutions/CountCharsInAString_01.java:
--------------------------------------------------------------------------------
1 | package Maps;
2 |
3 | import java.util.LinkedHashMap;
4 | import java.util.Map;
5 | import java.util.Scanner;
6 |
7 | public class CountCharsInAString_01 {
8 | public static void main(String[] args) {
9 | Scanner scanner = new Scanner(System.in);
10 |
11 | String text = scanner.nextLine();
12 |
13 | //символ -> бр. срещания
14 | Map characterCounts = new LinkedHashMap<>();
15 | //HashMap - нямаме конкретна подредба на записите
16 | //LinkedHashMap - записите се подреждат спрямо реда на добавяне
17 | //TreeMap - записите се сортират по ключ
18 |
19 | //"Desislava" -> ['D', 'e', 's', 'i', 's', 'l', 'a', 'v', 'a']
20 | for (char symbol : text.toCharArray()) {
21 | if (symbol == ' ') {
22 | continue;
23 | }
24 | //да сме го срещали
25 | if (characterCounts.containsKey(symbol)) {
26 | int currentCount = characterCounts.get(symbol);
27 | characterCounts.put(symbol, currentCount + 1);
28 | }
29 | //да не сме го срещали
30 | else {
31 | characterCounts.put(symbol, 1);
32 | }
33 | }
34 |
35 | //map: символ(key) -> бр. срещания(value)
36 | //entry (key: char -> value: int)
37 | // characterCounts.forEach((key, value)-> System.out.println(key + " -> " + value));
38 |
39 | for(Map.Entry entry : characterCounts.entrySet()) {
40 | System.out.println(entry.getKey() + " -> " + entry.getValue());
41 | }
42 |
43 |
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/RegEx - Exercise/NetherRealms_05.java:
--------------------------------------------------------------------------------
1 | package RegEx;
2 |
3 | import java.util.*;
4 | import java.util.regex.Matcher;
5 | import java.util.regex.Pattern;
6 | import java.util.stream.Collectors;
7 | public class NetherRealms_05 {
8 | public static void main(String[] args) {
9 | Scanner scanner = new Scanner(System.in);
10 |
11 | List namesList = Arrays.stream(scanner.nextLine().split("\\s*,\\s*")).collect(Collectors.toList());
12 | String regexHealth = "[^0-9+*-\\/.]";
13 | Pattern patternHealth = Pattern.compile(regexHealth);
14 | String regexDamage = "\\+?\\-?\\d+\\.?\\d*";
15 | Pattern patternDamage = Pattern.compile(regexDamage);
16 |
17 | for (String name : namesList) {
18 | Matcher matcherHealth = patternHealth.matcher(name);
19 | int health = 0;
20 | while (matcherHealth.find()) {
21 | char symbol = matcherHealth.group().charAt(0);
22 | health += symbol;
23 | }
24 |
25 | Matcher matcherDamage = patternDamage.matcher(name);
26 | double damage = 0;
27 | while (matcherDamage.find()) {
28 | double currentDamage = Double.parseDouble(matcherDamage.group());
29 | damage += currentDamage;
30 | }
31 | for (Character symbol : name.toCharArray()) {
32 | if (symbol == '/') {
33 | damage /= 2;
34 | } else if (symbol == '*') {
35 | damage *= 2;
36 | }
37 | }
38 |
39 | System.out.printf("%s - %d health, %.2f damage%n", name, health, damage);
40 |
41 | }
42 |
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/Mid-Exam-Preparation/TheFlag_02.java:
--------------------------------------------------------------------------------
1 | package ExamPreparation;
2 |
3 | import java.util.Arrays;
4 | import java.util.Scanner;
5 |
6 | public class TheFlag_02 {
7 | public static void main(String[] args) {
8 | Scanner scanner = new Scanner(System.in);
9 |
10 | int peopleWait = Integer.parseInt(scanner.nextLine()); //15
11 | int [] wagons = Arrays.stream(scanner.nextLine().split("\\s+"))
12 | .mapToInt(Integer::parseInt).toArray();
13 | //[0, 0, 0 , 0]
14 |
15 |
16 | for (int wagon = 0; wagon <= wagons.length - 1; wagon++) {
17 | if (peopleWait > 0) {
18 | int currentCountPeople = wagons[wagon]; //текущ брой на хората
19 | while (currentCountPeople < 4) {
20 | //добавям човек във вагона ако има чакащи
21 | if (peopleWait <= 0) {
22 | break;
23 | }
24 | currentCountPeople++;
25 | wagons[wagon] = currentCountPeople;
26 | peopleWait--;
27 | }
28 | }
29 | }
30 |
31 | if (peopleWait <= 0 && wagons[wagons.length - 1] < 4) {
32 | //имаме останало място
33 | System.out.println("The lift has empty spots!");
34 | } else if (peopleWait > 0 && wagons[wagons.length - 1] >= 4) {
35 | //нямаме повече място
36 | System.out.printf("There isn't enough space! %d people in a queue!%n", peopleWait);
37 | }
38 |
39 |
40 |
41 | //отпечатваме вагоните
42 | for (int wagon : wagons) {
43 | System.out.print(wagon + " ");
44 | }
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/Text Procressing - Exercise/Solutions/ValidUsernames_01.java:
--------------------------------------------------------------------------------
1 | package TextProcessing;
2 |
3 | import java.util.Scanner;
4 |
5 | public class ValidUsernames_01 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 |
9 | //1. входни данни
10 | String input = scanner.nextLine(); // "sh, too_long_username, !lleg@l ch@rs, jeffbutt"
11 | String[] usernames = input.split(", "); // ["sh", "too_long_username", "!lleg@l ch@rs", "jeffbutt"]
12 |
13 | //2. обходя usernames -> правя проверка дали е валиден -> принтирам
14 | for (String username : usernames) {
15 | //ако username e валиден
16 | if (isValidUsername(username)) {
17 | System.out.println(username);
18 | }
19 | }
20 | }
21 | //метод, който проверява дали username е валиден
22 | //true -> ако username е валиден
23 | //false -> ако username не е валиден
24 | private static boolean isValidUsername (String username) {
25 | //1. валидна дължина
26 | // [3; 16] -> валидна
27 | if (username.length() < 3 || username.length() > 16) {
28 | //невалидна дължина -> невалиден username
29 | return false;
30 | }
31 | //дължина е [3; 16] => валидна дължина
32 |
33 | //2. валидно съдържание -> букви, цифри, -, _
34 | //username = "Test№ser".toCharArray() -> ['T', 'e', 's', ....]
35 | for (char symbol : username.toCharArray()) {
36 | if (!Character.isLetterOrDigit(symbol) && symbol != '-' && symbol != '_') {
37 | //невалиден символ -> невалиден username
38 | return false;
39 | }
40 | }
41 | //валидно съдържание и валидна дължина
42 | return true;
43 | }
44 |
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/Arrays - Exercise/Solutions/EqualSums_06.java:
--------------------------------------------------------------------------------
1 | package Arrays;
2 |
3 |
4 | import java.util.Arrays;
5 | import java.util.Scanner;
6 |
7 | public class EqualSums_06 {
8 | public static void main(String[] args) {
9 | Scanner scanner = new Scanner(System.in);
10 |
11 | int [] numbers = Arrays.stream(scanner.nextLine().split(" "))
12 | .mapToInt(Integer::parseInt).toArray();
13 |
14 | for (int index = 0; index <= numbers.length - 1; index++) {
15 | int currentElement = numbers[index];
16 |
17 | int leftSum = 0; //сума от елементите в ляво
18 | int rightSum = 0; //сума от елементите в дясно
19 |
20 | //1. да си намеря сумата на елементите в ляво от моето число
21 | //[3, 6, 9, 23, 12, 5, 6]
22 | //лява сума: всички елементи от първия индекс(0) до моя (не вкл)
23 | //leftIndex -> всички индекси на числа, които са от ляво на моето
24 | for (int leftIndex = 0; leftIndex < index; leftIndex++) {
25 | leftSum += numbers[leftIndex];
26 | }
27 |
28 | //2. да си намеря сумата от елементите в дясно от моето число
29 | //[3, 6, 9, 23, 12, 5, 6]
30 | //дясна сума: всички елементи след моя до последния (дължина - 1)
31 | for (int rightIndex = index + 1; rightIndex <= numbers.length - 1; rightIndex++) {
32 | rightSum += numbers[rightIndex];
33 | }
34 |
35 | //3. проверка дали са равни двете суми
36 | if (leftSum == rightSum) {
37 | System.out.println(index);
38 | return; //прекъсвам цялата програма
39 | }
40 | }
41 |
42 | //обходила всички числа в масива и за никое не ми е било вярно условието
43 | System.out.println("no");
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/Lists - Exercise/Solutions/HouseParty_03.java:
--------------------------------------------------------------------------------
1 | package Lists_Exercise;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.Scanner;
6 |
7 | public class HouseParty_03 {
8 | public static void main(String[] args) {
9 | Scanner scanner = new Scanner(System.in);
10 | int countCommands = Integer.parseInt(scanner.nextLine()); //брой на команди
11 |
12 | List guests = new ArrayList<>(); //списък с имена на гости
13 |
14 | for (int countCommand = 1; countCommand <= countCommands; countCommand++) {
15 | String command = scanner.nextLine();
16 | String name = command.split("\\s+")[0];
17 |
18 | if (command.contains("is going!")) {
19 | //command = "Desi is going!".split(" ") -> ["Desi", "is", "going!"][0] -> "Desi"
20 | //1. да го има вече в списъка
21 | if (guests.contains(name)) {
22 | System.out.println(name + " is already in the list!");
23 | }
24 | //2. да го няма в списъка
25 | else {
26 | guests.add(name);
27 | }
28 | } else if (command.contains("is not going!")){
29 | //command = "Ivan is not going!".split(" ") -> ["Ivan", "is", "not", "going!"]
30 | //1. ако го има в списъка -> премахвам
31 | if (guests.contains(name)) {
32 | guests.remove(name);
33 | }
34 | //2. ако го няма в списъка
35 | else {
36 | System.out.println(name + " is not in the list!");
37 | }
38 | }
39 | }
40 |
41 | //пълния списък с гостите
42 | for (String name : guests) {
43 | System.out.println(name);
44 | }
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/Lists - Exercise/Solutions/Train_01.java:
--------------------------------------------------------------------------------
1 | package Lists_Exercise;
2 | import java.util.ArrayList;
3 | import java.util.Arrays;
4 | import java.util.List;
5 | import java.util.Scanner;
6 | import java.util.stream.Collectors;
7 | public class Train_01 {
8 | public static void main(String[] args) {
9 | Scanner scanner = new Scanner(System.in);
10 | //"32 54 21 12 4 0 23" -> ["32", "54", "21", "12", "4", "0", "23"]
11 | List wagons = Arrays.stream(scanner.nextLine().split(" ")).map(Integer::parseInt).collect(Collectors.toList());
12 | int maxCapacity = Integer.parseInt(scanner.nextLine()); //макс брой пасажери във всеки един вагон
13 |
14 | String command = scanner.nextLine();
15 | while(!command.equals("end")) {
16 | //"Add {passengers}" -> ["Add", "5"]
17 | //"{passengers}" -> ["45"]
18 | String[] commandData = command.split(" ");//["Add", "5"] или ["45"]
19 | if (commandData[0].equals("Add")) {
20 | //команда Add
21 | int passengers = Integer.parseInt(commandData[1]);
22 | wagons.add(passengers);
23 | } else {
24 | //команда -> число
25 | int passengersToAdd = Integer.parseInt(commandData[0]);
26 | for(int index = 0; index < wagons.size(); index++) {
27 | int currentWagon = wagons.get(index);
28 | if(currentWagon + passengersToAdd <= maxCapacity) {
29 | wagons.set(index, currentWagon + passengersToAdd);
30 | break;
31 | }
32 | }
33 | }
34 |
35 | command = scanner.nextLine();
36 | }
37 |
38 | for (int wagon : wagons) {
39 | System.out.print(wagon + " ");
40 | }
41 |
42 | //wagons.forEach(wagon -> System.out.print(wagon + " "));
43 |
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/Basic Syntax, Conditional Statements and Loops - Exercise/Solutions/Login_05.java:
--------------------------------------------------------------------------------
1 | package BasicSyntax;
2 |
3 | import java.util.Scanner;
4 |
5 | public class Login_05 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 |
9 | //1. входни данни -> username
10 | String username = scanner.nextLine();
11 | //2. password -> username наобратно
12 | String password = ""; //парола
13 |
14 | //username: "Acer" -> password: "recA"
15 | //първия символ -> 0 позиция
16 | //последния символ -> дължина - 1 позиция
17 |
18 | //последната позиция -> първата
19 | for (int position = username.length() - 1; position >= 0; position--) {
20 | //1. взимаме символът на съответната позиция
21 | char currentSymbol = username.charAt(position);
22 | //2. добавяме към паролата
23 | password += currentSymbol;
24 | }
25 |
26 | //повтарящо действие: въвеждаме някаква парола
27 | //стоп: въведената парола == password
28 | //продължаваме: въведената парола != password
29 |
30 | String enteredPassword = scanner.nextLine(); //ВЪВЕДЕНАТА ПАРОЛА
31 | int countFailedTries = 0; //брой неуспешни опита
32 | while (!enteredPassword.equals(password)) {
33 | //грешно въведена парола
34 | countFailedTries++;
35 | //1. проверяваме за блокиране
36 | if (countFailedTries == 4) {
37 | System.out.printf("User %s blocked!", username);
38 | break;
39 | }
40 | //2. опитай отново
41 | System.out.println("Incorrect password. Try again.");
42 | enteredPassword = scanner.nextLine();
43 | }
44 |
45 | //вярна парола
46 | if (enteredPassword.equals(password)) {
47 | System.out.printf("User %s logged in.", username);
48 | }
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/Basic Syntax, Conditional Statements and Loops - Exercise/Solutions/Vacation_03.java:
--------------------------------------------------------------------------------
1 | package BasicSyntax;
2 |
3 | import java.util.Scanner;
4 |
5 | public class Vacation_03 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 |
9 | int countStudents = Integer.parseInt(scanner.nextLine());
10 | String typeGroup = scanner.nextLine();
11 | String day = scanner.nextLine();
12 | double price = 0;
13 |
14 | if (typeGroup.equals("Students")) {
15 | if (day.equals("Friday")) {
16 | price = 8.45;
17 |
18 | } else if (day.equals("Saturday")) {
19 | price = 9.80;
20 | } else if (day.equals("Sunday")) {
21 | price = 10.46;
22 | }
23 |
24 | if (countStudents >= 30) {
25 | price = price * 0.85;
26 | }
27 |
28 | } else if (typeGroup.equals("Business")) {
29 | if (day.equals("Friday")) {
30 | price = 10.90;
31 | } else if (day.equals("Saturday")) {
32 | price = 15.60;
33 | } else if (day.equals("Sunday")) {
34 | price = 16;
35 | }
36 | if (countStudents >= 100) {
37 | countStudents = countStudents - 10;
38 | }
39 |
40 | } else if (typeGroup.equals("Regular")) {
41 |
42 | if (day.equals("Friday")) {
43 | price = 15;
44 | } else if (day.equals("Saturday")) {
45 | price = 20;
46 | } else if (day.equals("Sunday")) {
47 | price = 22.50;
48 | }
49 | if (countStudents >= 10 && countStudents <= 20) {
50 | price = price * 0.95;
51 |
52 | }
53 | }
54 | double totalPrice = countStudents * price;
55 | System.out.printf("Total price: %.2f", totalPrice);
56 | }
57 | }
58 |
59 |
--------------------------------------------------------------------------------
/Maps - Exercise/Solutions/SoftUniParking_04.java:
--------------------------------------------------------------------------------
1 | package Maps;
2 | import java.util.*;
3 | public class SoftUniParking_04 {
4 | public static void main(String[] args) {
5 | Scanner scanner = new Scanner(System.in);
6 |
7 | int n = Integer.parseInt(scanner.nextLine());
8 |
9 | Map registeredStudents = new LinkedHashMap<>();
10 |
11 | for (int i = 0; i < n; i++){
12 |
13 | String[] data = scanner.nextLine().split("\\s+");
14 |
15 | String command = data[0];
16 |
17 | switch (command) {
18 | case "register":
19 |
20 | String studentName = data[1];
21 | String plateNumber = data[2];
22 |
23 | if(registeredStudents.containsKey(studentName)) {
24 | System.out.println(String.format("ERROR: already registered with plate number %s",
25 | plateNumber));
26 | } else {
27 | registeredStudents.put(studentName, plateNumber);
28 | System.out.println(String.format("%s registered %s successfully", studentName, plateNumber));
29 | }
30 |
31 | break;
32 | case "unregister":
33 |
34 | String userName = data[1];
35 |
36 | if(!registeredStudents.containsKey(userName)) {
37 | System.out.println(String.format("ERROR: user %s not found", userName));
38 | } else {
39 | registeredStudents.remove(userName);
40 | System.out.println(String.format("%s unregistered successfully", userName));
41 | }
42 |
43 | break;
44 | }
45 | }
46 |
47 | registeredStudents.forEach((key, value) ->
48 | System.out.println(String.format("%s => %s", key, value)));
49 |
50 |
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/Objects and Classes - Exercise/Solutions/VehicleCatalogue_05/Main.java:
--------------------------------------------------------------------------------
1 | package VehicleCatalogue_05;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.Scanner;
6 |
7 | public class Main {
8 | public static void main(String[] args) {
9 | Scanner scanner = new Scanner(System.in);
10 | String input = scanner.nextLine();
11 | List vehicles = new ArrayList<>();
12 |
13 | while (!input.equals("End")) {
14 | String[] tokens = input.split("\\s+");
15 | vehicles.add(new Vehicle(tokens[0], tokens[1], tokens[2], Integer.parseInt(tokens[3])));
16 | input = scanner.nextLine();
17 | }
18 |
19 | String model = scanner.nextLine();
20 | double sumCar = 0;
21 | double sumTruck = 0;
22 | int countCar = 0;
23 | int countTruck = 0;
24 | while (!model.equals("Close the Catalogue")) {
25 | for (Vehicle vehicle : vehicles) {
26 | if (vehicle.getModel().equals(model)) {
27 | System.out.println(vehicle);
28 |
29 | }
30 | }
31 | model = scanner.nextLine();
32 | }
33 |
34 | for (Vehicle vehicle : vehicles) {
35 | if (vehicle.getType().equals("car")) {
36 | sumCar += vehicle.getHorsePower();
37 | countCar++;
38 | } else if (vehicle.getType().equals("truck")) {
39 | sumTruck += vehicle.getHorsePower();
40 | countTruck++;
41 | }
42 | }
43 |
44 | double averageCars = sumCar / countCar;
45 | if(countCar == 0) {averageCars = 0;}
46 | System.out.printf("Cars have average horsepower of: %.2f.%n", averageCars);
47 | double averageTrucks = sumTruck / countTruck;
48 | if(countTruck == 0) {averageTrucks = 0;}
49 | System.out.printf("Trucks have average horsepower of: %.2f.%n", averageTrucks);
50 |
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/RegEx - Exercise/Furniture_01.java:
--------------------------------------------------------------------------------
1 | package RegEx;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.Scanner;
6 | import java.util.regex.Matcher;
7 | import java.util.regex.Pattern;
8 |
9 | public class Furniture_01 {
10 | public static void main(String[] args) {
11 | Scanner scanner = new Scanner(System.in);
12 | List furniture = new ArrayList<>(); //списък със закупени мебели
13 | double totalSum = 0; //общо изхарчена сума за всички закупени мебели
14 |
15 | String regex = ">>(?[A-Za-z]+)<<(?[0-9]+\\.?[0-9]*)!(?[0-9]+)";
16 | Pattern pattern = Pattern.compile(regex);
17 |
18 | String input = scanner.nextLine();
19 | //">>{furniture name}<<{price}!{quantity}"
20 | while(!input.equals("Purchase")) {
21 | //input = ">>Sofa<<312.23!3"
22 | Matcher matcher = pattern.matcher(input);
23 | //matcher = ">>(?Sofa)<<(?312.23)!(?3)"
24 | //find
25 | //true -> input отговаря на regex
26 | //false -> input не отговаря на regex
27 | if (matcher.find()) {
28 | //input отговаря на regex -> купуваме мебели
29 | String furnitureName = matcher.group("furnitureName"); //мебел
30 | double price = Double.parseDouble(matcher.group("price")); //ед. цена
31 | int quantity = Integer.parseInt(matcher.group("quantity")); //количество
32 |
33 | furniture.add(furnitureName);
34 | double currentFurniturePrice = quantity * price; //платено за текушата мебел
35 | totalSum += currentFurniturePrice;
36 | }
37 | input = scanner.nextLine();
38 | }
39 |
40 | System.out.println("Bought furniture:");
41 | furniture.forEach(System.out::println);
42 |
43 | System.out.printf("Total money spend: %.2f", totalSum);
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/Maps - Exercise/Solutions/SoftUniExamResults_10.java:
--------------------------------------------------------------------------------
1 | package Maps;
2 | import java.util.*;
3 | public class SoftUniExamResults_10 {
4 | public static void main(String[] args) {
5 | Scanner scanner = new Scanner(System.in);
6 |
7 | Map userAndPoints = new LinkedHashMap<>();
8 | Map languageCount = new LinkedHashMap<>();
9 |
10 | String input = scanner.nextLine();
11 |
12 | while (!input.equals("exam finished")){
13 | String[] inputArr = input.split("-");
14 | String username = inputArr[0];
15 |
16 | if (input.contains("banned")){
17 | userAndPoints.remove(username);
18 |
19 | }else{
20 | String language = inputArr[1];
21 | int points = Integer.parseInt(inputArr[2]);
22 |
23 | if (!userAndPoints.containsKey(username)){
24 | userAndPoints.put(username, points);
25 | }else{
26 | int currentPoints = userAndPoints.get(username);
27 | if (points > currentPoints){
28 | userAndPoints.put(username, points);
29 | }
30 | }
31 |
32 | if (!languageCount.containsKey(language)){
33 | languageCount.put(language, 1);
34 | }else{
35 | int currentCount = languageCount.get(language);
36 | languageCount.put(language, currentCount + 1);
37 | }
38 |
39 | }
40 |
41 | input = scanner.nextLine();
42 | }
43 | System.out.println("Results:");
44 | userAndPoints.entrySet().forEach(entry -> System.out.println(entry.getKey() + " | " + entry.getValue()));
45 | System.out.println("Submissions:");
46 | for (Map.Entry entry : languageCount.entrySet()) {
47 | System.out.println(entry.getKey() + " - " + entry.getValue());
48 | }
49 |
50 |
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/Maps - Exercise/Solutions/StudentAcademy_06.java:
--------------------------------------------------------------------------------
1 | package Maps;
2 | import java.util.*;
3 | public class StudentAcademy_06 {
4 | public static void main(String[] args) {
5 | Scanner scanner = new Scanner(System.in);
6 | int countStudents = Integer.parseInt(scanner.nextLine());
7 | //студент -> списък с оценки
8 | Map> studentGrades = new LinkedHashMap<>();
9 | for (int i = 0; i < countStudents; i++) {
10 | String studentName = scanner.nextLine();
11 | double grade = Double.parseDouble(scanner.nextLine());
12 | //студентът да го нямаме в списъка
13 | if (!studentGrades.containsKey(studentName)) {
14 | studentGrades.put(studentName, new ArrayList<>());
15 | }
16 | studentGrades.get(studentName).add(grade);
17 | }
18 |
19 | //студент -> ср. оценка
20 | Map studentAverageGrade = new LinkedHashMap<>(); //студентите ср. оценка >= 4.50
21 | //търсим среданата оценка на всички студенти
22 | for (Map.Entry> entry : studentGrades.entrySet()) {
23 | //entry -> име (String) + списък с оценки (list)
24 | String studentName = entry.getKey();
25 | List grades = entry.getValue();
26 | double averageGrade = getAverageGrade (grades);
27 | if(averageGrade >= 4.50) {
28 | studentAverageGrade.put(studentName, averageGrade);
29 | }
30 | }
31 | //разменяме записите ако на втория оценката > оценката на първия
32 | studentAverageGrade.entrySet()
33 | .forEach(entry -> System.out.printf("%s -> %.2f%n", entry.getKey(), entry.getValue()));
34 |
35 | }
36 |
37 | private static double getAverageGrade(List grades) {
38 | double sumGrades = 0;
39 | for (double grade : grades) {
40 | sumGrades += grade;
41 | }
42 | return sumGrades / grades.size();
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/Text Procressing - Exercise/Solutions/CharacterMultiplier_02.java:
--------------------------------------------------------------------------------
1 | package TextProcessing;
2 |
3 | import java.util.Scanner;
4 |
5 | public class CharacterMultiplier_02 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 |
9 | String input = scanner.nextLine(); //"George Peter"
10 | String [] names = input.split("\\s+"); //["George", "Peter"]
11 |
12 | String firstText = names[0]; //"George" -> 6
13 | String secondText = names[1]; //"Peter" -> 5
14 |
15 | int minLength = Math.min(firstText.length(), secondText.length()); //дължина на по-късия текст -> 5
16 | int maxLength = Math.max(firstText.length(), secondText.length()); //дължина на по-дългия текст -> 6
17 |
18 | int sum = 0;
19 | for (int index = 0; index < minLength; index++) {
20 | sum += (firstText.charAt(index) * secondText.charAt(index));
21 | }
22 |
23 | //еднакви дължини на текстовете
24 | if (maxLength == minLength) {
25 | System.out.println(sum);
26 | return;
27 | }
28 |
29 | sum = getLeftSymbols(firstText, secondText, minLength, maxLength, sum);
30 |
31 | System.out.println(sum);
32 |
33 | }
34 |
35 | private static int getLeftSymbols(String firstText, String secondText, int minLength, int maxLength, int sum) {
36 | //кой е по-дългия текст -> останалите букви, които не са участвали в умножението
37 | if (maxLength == firstText.length()) {
38 | //първия текст ми е по-дълъг -> взимам останалите символи
39 | for (int index = minLength; index < firstText.length(); index++) {
40 | sum += firstText.charAt(index);
41 | }
42 | } else {
43 | //втория текст ми е по-дълъг -> взимам останали символи
44 | for (int index = minLength; index < secondText.length(); index++) {
45 | sum += secondText.charAt(index);
46 | }
47 | }
48 | return sum;
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/Maps - Exercise/Solutions/Orders_03.java:
--------------------------------------------------------------------------------
1 | package Maps;
2 |
3 | import java.util.LinkedHashMap;
4 | import java.util.Map;
5 | import java.util.Scanner;
6 |
7 | public class Orders_03 {
8 | public static void main(String[] args) {
9 | Scanner scanner = new Scanner(System.in);
10 |
11 | String data = scanner.nextLine();
12 | Map productsQuantity = new LinkedHashMap<>(); //product -> quantity
13 | Map productsPrice = new LinkedHashMap<>(); //product -> price
14 |
15 | //Map>: продукт -> {количество, цена}
16 |
17 | while (!data.equals("buy")) {
18 | //data = "{name} {price} {quantity}".split(" ") -> ["{name}", "{price}", "{quantity}"]
19 | String product = data.split("\\s+")[0]; //име на продукта
20 | double price = Double.parseDouble(data.split("\\s+")[1]); //цена на продукта
21 | int quantity = Integer.parseInt(data.split("\\s+")[2]); //количество на продукта
22 |
23 | //за количество -> не сме срещали такъв продукт
24 | if (!productsQuantity.containsKey(product)) {
25 | productsQuantity.put(product, quantity);
26 | } else {
27 | int currentQuantity = productsQuantity.get(product);
28 | productsQuantity.put(product, currentQuantity + quantity);
29 | }
30 |
31 | //за цена -> всеки път да добавяме срещу продукта въведената
32 | productsPrice.put(product, price);
33 |
34 | data = scanner.nextLine();
35 | }
36 |
37 | //продукт -> количество
38 | //продукт -> ед. цена
39 |
40 |
41 | //продукт -> колко е платено за него (количество * ед. цена)
42 | for (Map.Entry entry : productsQuantity.entrySet()) {
43 | //entry
44 | //key (име на продукта)
45 | //value (брой)
46 | String productName = entry.getKey();
47 | double finalSum = productsQuantity.get(productName) * productsPrice.get(productName);
48 | System.out.printf("%s -> %.2f%n", productName, finalSum);
49 | }
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/Objects and Classes - Exercise/Solutions/groomingSalon/GroomingSalon.java:
--------------------------------------------------------------------------------
1 | package groomingSalon;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | public class GroomingSalon {
7 | //полета -> характеристики (списък с дом. животни, капацитет)
8 | private List data;
9 | private int capacity;
10 |
11 | //конструктор
12 | public GroomingSalon(int capacity) {
13 | //нов празен обект {capacity = 0, data = null}
14 | this.capacity = capacity;
15 | this.data = new ArrayList<>();
16 | }
17 |
18 | //методи -> действия
19 |
20 | //Add
21 | public void add(Pet pet) {
22 | if (this.data.size() < this.capacity) {
23 | this.data.add(pet);
24 | }
25 | }
26 |
27 | //Remove
28 | public boolean remove(String name) {
29 | //true -> ако има такова животно с даденото име и го премахна
30 | //false -> ако няма такова животно с даденото име
31 |
32 | for (Pet pet : this.data) {
33 | if (pet.getName().equals(name)) {
34 | this.data.remove(pet);
35 | return true;
36 | }
37 | }
38 | //обходила всички животни в списъка
39 | return false;
40 | }
41 |
42 | //getPet
43 | public Pet getPet(String name, String owner) {
44 | //ако има животно с дадените параметри -> връщаме го
45 | //няма животно с дадените параметри -> връщаме null
46 | for (Pet pet : this.data) {
47 | if (pet.getName().equals(name) && pet.getOwner().equals(owner)) {
48 | return pet;
49 | }
50 | }
51 | //обходила всички животни в списъка
52 | return null;
53 | }
54 |
55 | //getCount
56 | public int getCount() {
57 | return this.data.size();
58 | }
59 |
60 | //getStatistics
61 | public String getStatistics() {
62 | String output = "";
63 |
64 | output += "The grooming salon has the following clients:\n";
65 |
66 | for (Pet pet : this.data) {
67 | output += pet.getName() + " " + pet.getOwner() + "\n";
68 | }
69 |
70 | return output;
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/Objects and Classes - Exercise/Solutions/Articles_02/Main.java:
--------------------------------------------------------------------------------
1 | package Articles_02;
2 |
3 | import java.util.Scanner;
4 |
5 | public class Main {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 |
9 | String articleData = scanner.nextLine();
10 | //"Holy Ghost, content, John Sandford"
11 | String[] articleParts = articleData.split(", ");
12 | // ["Holy Ghost", "content", "John Sandford"]
13 | String title = articleParts[0];
14 | String content = articleParts[1];
15 | String author = articleParts[2];
16 |
17 | Article article = new Article(title, content, author);
18 |
19 | int n = Integer.parseInt(scanner.nextLine()); //брой на командите
20 | for (int commandCount = 1; commandCount <= n; commandCount++) {
21 | String command = scanner.nextLine();
22 | //"Edit: {ново съдържание}"
23 | //"Rename: {ново заглавие}"
24 | //"ChangeAuthor"
25 | if (command.contains("Edit")) {
26 | //променя съдържанието на моята статия с даденото
27 | //command = "Edit: test is good".split(": ") -> ["Edit", "test is good"]
28 | String newContent = command.split(": ")[1]; //ново съдържание
29 | article.edit(newContent);
30 | } else if (command.contains("Rename")) {
31 | //променя заглавието на моята статия с даденото
32 | //command = "Rename: TestTitle".split(": ") -> ["Rename", "TestTitle"]
33 | String newTitle = command.split(": ")[1]; //ново заглавие
34 | article.rename(newTitle);
35 | } else if (command.contains("ChangeAuthor")) {
36 | //променя автора на моята статия с дадения
37 | //command = "ChangeAuthor: Test Testov".split(": ") -> ["ChangeAuthor", "Test Testov"]
38 | String newAuthor = command.split(": ")[1]; //новия автор
39 | article.changeAuthor(newAuthor);
40 | }
41 | }
42 |
43 | //{title} - {съдържание}: {автора}
44 | System.out.println(article.toString());
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/Lists - Exercise/Solutions/ChangeList_02.java:
--------------------------------------------------------------------------------
1 | package Lists_Exercise;
2 | import java.util.Arrays;
3 | import java.util.List;
4 | import java.util.Scanner;
5 | import java.util.stream.Collectors;
6 | public class ChangeList_02 {
7 | public static void main(String[] args) {
8 | Scanner scanner = new Scanner(System.in);
9 | //1. списък с числа -> входни данни
10 | //2. получаваме команди -> "end"
11 | //"Delete {element}" -> "Delete 3"
12 | //"Insert {element} {position}" -> "Insert 3 1"
13 |
14 | List numbers = Arrays.stream(scanner.nextLine() //"1 2 3 4 5 5 5 6"
15 | .split(" ")) //["1", "2", "3", "4", "5", "5", "5", "6"] -> масив от текстове
16 | .map(Integer::parseInt) //[1, 2, 3, 4, 5, 5, 5, 6] -> масив от цели числа
17 | .collect(Collectors.toList()); //{1, 2, 3, 4, 5, 5, 5, 6} -> списък от цели числа
18 |
19 | String command = scanner.nextLine(); //команди
20 | //stop: command == "end"
21 | //continue: command != "end"
22 | while (!command.equals("end")) {
23 | //команда
24 | //1. command = "Delete 3"
25 | if (command.contains("Delete")) {
26 | //"Delete 3".split(" ") -> ["Delete", "3"]
27 | int numberForRemove = Integer.parseInt(command.split(" ")[1]);
28 | //премахваме всички стойности от списъка равни на numberForRemove
29 | numbers.removeAll(Arrays.asList(numberForRemove));
30 | }
31 | //2. command = "Insert 3 1"
32 | else if (command.contains("Insert")) {
33 | //"Insert 3 1".split(" ") -> ["Insert", "3", "1"]
34 | //вмъкна element на index
35 | int element = Integer.parseInt(command.split(" ")[1]);
36 | int index = Integer.parseInt(command.split(" ")[2]);
37 | numbers.add(index, element);
38 | }
39 | command = scanner.nextLine();
40 | }
41 |
42 | //списък с числа -> {3, 4, 5, 6}
43 | for (int number : numbers) {
44 | System.out.print(number + " ");
45 | }
46 |
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/Basic Web Project/phonebook/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | Phonebook
7 | phonebook
8 | 0.0.1-SNAPSHOT
9 | jar
10 |
11 | phonebook
12 | Demo project for Technology Fundamentals Course @SoftUni
13 |
14 |
15 | org.springframework.boot
16 | spring-boot-starter-parent
17 | 2.0.4.RELEASE
18 |
19 |
20 |
21 |
22 | UTF-8
23 | UTF-8
24 | 11
25 |
26 |
27 |
28 |
29 | org.springframework.boot
30 | spring-boot-starter-thymeleaf
31 |
32 |
33 | org.springframework.boot
34 | spring-boot-starter-web
35 |
36 |
37 |
38 | org.springframework.boot
39 | spring-boot-devtools
40 | runtime
41 |
42 |
43 | org.springframework.boot
44 | spring-boot-starter-test
45 | test
46 |
47 |
48 |
49 |
50 |
51 |
52 | org.springframework.boot
53 | spring-boot-maven-plugin
54 |
55 |
56 |
57 |
58 |
59 |
60 |
--------------------------------------------------------------------------------
/Arrays - Exercise/Solutions/TreasureHunt_10.java:
--------------------------------------------------------------------------------
1 | package Arrays;
2 |
3 | import java.util.Scanner;
4 |
5 | public class TreasureHunt_10 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 | String [] loots = scanner.nextLine().split("\\|");
9 | //"Gold|Silver|Bronze|Medallion|Cup".split("|") -> ["Gold", "Silver", "Bronze", "Medallion", "Cup"]
10 |
11 | String command = scanner.nextLine(); //цялата команда, въведена от конзолата
12 |
13 | while (!command.equals("Yohoho!")) {
14 | //command = "Loot {item1} {item2}…{itemn}".split -> ["Loot", "itrem1", "item2", ...]
15 |
16 | //command = "Steal 2".split -> ["Steal", "2"]
17 | String[] commandParts = command.split(" "); //частите на командата
18 | String commandName = commandParts[0]; //име на команда: Loot, Drop, Steal
19 |
20 | switch (commandName) {
21 | case "Loot":
22 | break;
23 | case "Drop":
24 | //command = "Drop 4".split -> commandParts = ["Drop", "4"]
25 | int dropIndex = Integer.parseInt(commandParts[1]); //"4" -> 4
26 | //проверка на индекс
27 | if(dropIndex < 0 || dropIndex >= loots.length - 1) {
28 | //невалиден индекс -> индекс, на който нямаме елемент
29 | break;
30 | } else{
31 | //валиден индекс
32 | //1. взимаме елемента за преместване
33 | String currentLoot = loots[dropIndex];
34 | //2. премествам на ляво всички елементи след моя
35 | for (int leftIndex = dropIndex; leftIndex < loots.length - 1; leftIndex++) {
36 | loots[leftIndex] = loots[leftIndex + 1];
37 | }
38 | //3. слагаме накрая елемента за преместване
39 | loots[loots.length - 1] = currentLoot;
40 | }
41 | break;
42 | case "Steal":
43 | break;
44 | }
45 |
46 | command = scanner.nextLine();
47 | }
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/Final-Exam-Preparation-1/TheImitationGame_01.java:
--------------------------------------------------------------------------------
1 | package ExamPreparation1;
2 |
3 | import java.util.Scanner;
4 |
5 | public class TheImitationGame_01 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 |
9 | String encryptedMessage = scanner.nextLine(); //криптирано съобщение
10 | StringBuilder modifyMessage = new StringBuilder(encryptedMessage); //модифицирам криптираното съобщение
11 |
12 | String input = scanner.nextLine();
13 |
14 | while (!input.equals("Decode")){
15 |
16 | if (input.contains("Move")) {
17 | //input = "Move|5".split("|") -> ["Move", "5"]
18 | int lettersCount = Integer.parseInt(input.split("\\|")[1]);
19 | //"owyouh" -> първите 5 букви "owyou" -> "howyou"
20 | String firstLetters = modifyMessage.substring(0, lettersCount); //буквите за местене ("owyou")
21 | modifyMessage.replace(0, lettersCount, ""); //заместваме с нищо
22 | //modifyMessage.delete(0, lettersCount); //изтриваме буквите
23 | modifyMessage.append(firstLetters);
24 | } else if (input.contains("Insert")) {
25 | //input = "Insert|2|abc".split("|") -> ["Insert", "2", "abc"]
26 | int index = Integer.parseInt(input.split("\\|")[1]); //индекс, на който ще вмъкваме
27 | String textToInsert = input.split("\\|")[2]; //текста, който трябва да вмъкнем
28 | modifyMessage.insert(index, textToInsert);
29 | } else if (input.contains("ChangeAll")) {
30 | //input = "ChangeAll|abc|wqe".split("|") -> ["ChangeAll", "abc", "wqa"]
31 | String textForChange = input.split("\\|")[1]; //текст, който трябва да се променя
32 | String replacement = input.split("\\|")[2]; //текст, който ще замества
33 |
34 | String currentMessage = modifyMessage.toString(); //моментното съобщение
35 | currentMessage = currentMessage.replace(textForChange, replacement);
36 | modifyMessage = new StringBuilder(currentMessage);
37 | }
38 | input = scanner.nextLine();
39 | }
40 |
41 | System.out.println("The decrypted message is: " + modifyMessage);
42 |
43 |
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/Final-Exam-Preparation-1/EmojiDetector_02.java:
--------------------------------------------------------------------------------
1 | package ExamPreparation1;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.Scanner;
6 | import java.util.regex.Matcher;
7 | import java.util.regex.Pattern;
8 |
9 | public class EmojiDetector_02 {
10 | public static void main(String[] args) {
11 | Scanner scanner = new Scanner(System.in);
12 | String input = scanner.nextLine(); //първоначален текст
13 |
14 | long coolThreshold = 1; //праг на готиност = стойност, която трябва да постигнем
15 | //умножим всички цифри в първоначалния текст
16 |
17 | for (char symbol : input.toCharArray()) {
18 | if (Character.isDigit(symbol)) {
19 | //'1'-> "1" -> 1
20 | int number = Integer.parseInt(symbol + "");
21 | coolThreshold *= number;
22 | }
23 | }
24 | System.out.println("Cool threshold: " + coolThreshold);
25 |
26 | String regex = "([:]{2}|[*]{2})(?[A-Z][a-z]{2,})(\\1)";
27 | Pattern pattern = Pattern.compile(regex);
28 | Matcher matcher = pattern.matcher(input);
29 | //съвкупност от текстовете, които отговарят на шаблон = валидните емоджита
30 | //matcher = ["::Smiley::", "**Tigers**", "::Mooning::"]
31 |
32 | int countValidEmojis = 0; //брой на въведените валидни емоджита
33 | List coolEmojis = new ArrayList<>(); //най-готини емоджита
34 |
35 | while (matcher.find()) { //true -> намерено валидно емоджи
36 | //1. емоджи -> валидно -> броим
37 | countValidEmojis++;
38 | //2. намирам колко е готино
39 | int coolLevelCurrentEmoji = 0; //ниво на готиност на текущото емоджи
40 | String emoji = matcher.group("emoji");
41 | for (char symbol : emoji.toCharArray()) {
42 | coolLevelCurrentEmoji += (int) symbol;
43 | }
44 | //3. поверявам дали е достатъчно готино (coolest >= coolThreshold)
45 | if (coolLevelCurrentEmoji >= coolThreshold) {
46 | coolEmojis.add(matcher.group());
47 | }
48 | }
49 |
50 | System.out.printf("%d emojis found in the text. The cool ones are:%n", countValidEmojis);
51 | coolEmojis.forEach(System.out::println);
52 |
53 |
54 |
55 |
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/Methods - Exercise/Solutions/TopNumber_10.java:
--------------------------------------------------------------------------------
1 | package Methods;
2 |
3 | import java.util.Scanner;
4 |
5 | public class TopNumber_10 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 |
9 | int n = Integer.parseInt(scanner.nextLine());
10 | for (int number = 1; number <= n; number++) {
11 | //проверка дали е топ число
12 | //1. сумата от цифрите да се дели на 8
13 | //2. съдържа поне една нечетна цифра
14 | boolean isSum = isSumOfDigitsIsDivisibleBy8(number);
15 | boolean isContains = isContainsOddDigit(number);
16 | if (isSum && isContains) {
17 | //отпечатваме числото
18 | System.out.println(number);
19 | }
20 |
21 |
22 | }
23 | }
24 |
25 | //метод, който да проверява дали сумата от цифрите на числото се дели на 8
26 | //true -> ако сумата се дели на 8
27 | //false -> ако сумата не се дели на 8
28 | public static boolean isSumOfDigitsIsDivisibleBy8 (int number) {
29 | //1. сума от цифирите на числото
30 | int sum = 0; //сума от цифрите
31 | while (number > 0) {
32 | int lastDigit = number % 10; //последната цифра
33 | sum += lastDigit; //сумираме последната цифра
34 | number = number / 10; //премахваме последната цифра
35 | }
36 | //2. проверка дали сумата от цифрите се дели на 8
37 | return sum % 8 == 0;
38 |
39 | /*if (sum % 8 == 0) {
40 | return true;
41 | } else {
42 | return false;
43 | }*/
44 | }
45 |
46 | //метод, който проверява дали имаме поне една нечетна цифра в числото
47 | //true -> ако имаме поне една нечетна цифра
48 | //false -> ако нямаме нито една нечетна цифра
49 | public static boolean isContainsOddDigit (int number) {
50 | //6382
51 | while (number > 0) {
52 | int lastDigit = number % 10; //взимаме последната цифра
53 | //проверявам дали цифрата е нечетна
54 | if (lastDigit % 2 != 0) {
55 | //нечетна цифра -> поне една нечетна
56 | return true;
57 | } else {
58 | //четна цифра -> премахваме
59 | number /= 10;
60 | }
61 | }
62 | //проверили всички цифри и никоя не е била нечетна
63 | return false;
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/Final-Exam-Preparation-2/MirrorWords_02.java:
--------------------------------------------------------------------------------
1 | package ExamPreparation2;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.Scanner;
6 | import java.util.regex.Matcher;
7 | import java.util.regex.Pattern;
8 |
9 | public class MirrorWords_02 {
10 | public static void main(String[] args) {
11 | Scanner scanner = new Scanner(System.in);
12 | String text = scanner.nextLine();
13 | //"@mix#tix3dj#poOl##loOp#wl@@bong&song%4very$long@thong#Part##traP##@@leveL@@Level@##car#rac##tu@pack@@ckap@#rr#sAw##wAs#r#@w1r"
14 | //1. намираме двойките думи
15 | String regex = "(#|@)(?[A-Za-z]{3,})\\1\\1(?[A-Za-z]{3,})\\1";
16 | Pattern pattern = Pattern.compile(regex);
17 | Matcher matcher = pattern.matcher(text);
18 | //matcher -> съвкупност от всички двойки думи, които отговарят на условието
19 | //matcher = ["#poOl##loOp#", "#Part##traP#", "@leveL@@Level@"]
20 |
21 |
22 | List validPairs = new ArrayList<>(); //списък с валидни двойки
23 | int countAllPairs = 0; //брой на всички двойки
24 |
25 | //2. проверка коя двойка думи е валидна
26 | while (matcher.find()) {
27 | //matcher.find -> "#(?poOl)##(?loOp)#"
28 | String firstWord = matcher.group("first");
29 | String secondWord = matcher.group("second");
30 | countAllPairs++; //броя всяка намерена двойка думи
31 |
32 | //първата дума = втората дума обърната на обратно
33 | String secondWordReversed = new StringBuilder(secondWord).reverse().toString();
34 | if (firstWord.equals(secondWordReversed)) {
35 | //валидна двойка: {първа дума} <=> {втора дума}
36 | validPairs.add(firstWord + " <=> " + secondWord);
37 |
38 | }
39 |
40 | }
41 |
42 | //ако нямаме намерени двойки думи
43 | if (countAllPairs == 0) {
44 | System.out.println("No word pairs found!");
45 | } else {
46 | //намерили сме двойки думи
47 | System.out.println(countAllPairs + " word pairs found!");
48 | }
49 |
50 | //отпечатваме само ВАЛИДНИТЕ ДВОЙКИ
51 | if (validPairs.size() == 0) {
52 | //нямаме валидни двойки
53 | System.out.println("No mirror words!");
54 | } else {
55 | //имаме валидни двойки
56 | System.out.println("The mirror words are:");
57 | System.out.println(String.join(", ", validPairs));
58 | }
59 |
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/Lists - Exercise/Solutions/CardsGame_06.java:
--------------------------------------------------------------------------------
1 | package Lists_Exercise;
2 | import java.util.Arrays;
3 | import java.util.List;
4 | import java.util.Scanner;
5 | import java.util.stream.Collectors;
6 |
7 | public class CardsGame_06 {
8 | public static void main(String[] args) {
9 | Scanner scanner = new Scanner(System.in);
10 | List firstPlayerCards = Arrays.stream(scanner.nextLine().split(" "))
11 | .map(Integer::parseInt).collect(Collectors.toList());
12 | //{20 30 40 50}
13 | List secondPlayerCards = Arrays.stream(scanner.nextLine().split(" "))
14 | .map(Integer::parseInt).collect(Collectors.toList());
15 | //{10 20 30 40}
16 |
17 | //1. взимам първата карта от ръката
18 | //2. премахвам картата от ръката
19 | //3. проверка кой печели:
20 | // карта 1 > карта 2 -> слагам накрая на ръката на първия -> карта 1 -> карта 2
21 | //карта 2 > карта 1 -> слагам накрая на ръката на втория -> карта 2 -> карта 1
22 | //карта 1 == карта 2 -> не ги добавяме никъде
23 |
24 | //играта продължава когато и двамата имат карти
25 | //играта спира, когато някой остане без карти
26 |
27 | while (firstPlayerCards.size() != 0 && secondPlayerCards.size() != 0) {
28 | int firstPlayerCard = firstPlayerCards.get(0);
29 | int secondPlayerCard = secondPlayerCards.get(0);
30 | firstPlayerCards.remove(0);
31 | secondPlayerCards.remove(0);
32 |
33 | if (firstPlayerCard > secondPlayerCard) {
34 | firstPlayerCards.add(firstPlayerCard);
35 | firstPlayerCards.add(secondPlayerCard);
36 | } else if (secondPlayerCard > firstPlayerCard) {
37 | secondPlayerCards.add(secondPlayerCard);
38 | secondPlayerCards.add(firstPlayerCard);
39 | }
40 | }
41 |
42 | //1. ако на първия му свършат картите
43 | if (firstPlayerCards.size() == 0) {
44 | //втория печели -> сума от картите на втория
45 | System.out.printf("Second player wins! Sum: %d", getCardsSum(secondPlayerCards));
46 | }
47 | //2. ако на втория му свършат картите
48 | else if (secondPlayerCards.size() == 0) {
49 | //първия печели
50 | System.out.printf("First player wins! Sum: %d", getCardsSum(firstPlayerCards));
51 | }
52 | }
53 |
54 | private static int getCardsSum(List listCards) {
55 | int sum = 0;
56 | for (int card : listCards) {
57 | sum += card;
58 | }
59 |
60 | return sum;
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/Lists - Lab/ListManipulationsBasics_04.java:
--------------------------------------------------------------------------------
1 | package Lists_Lab;
2 |
3 | import java.util.Arrays;
4 | import java.util.List;
5 | import java.util.Scanner;
6 | import java.util.stream.Collectors;
7 |
8 | public class ListManipulationsBasics_04 {
9 | public static void main(String[] args) {
10 | Scanner scanner = new Scanner(System.in);
11 |
12 | //1. прочитаме лист от цели числа
13 | List numbers = Arrays.stream(scanner.nextLine() // "4 19 2 53 6 43"
14 | .split(" ")) // ["4", "19", "2", "53", "6", "43"]
15 | .map(Integer::parseInt) // [4, 19, 2, 53, 6, 43]
16 | .collect(Collectors.toList()); // {4, 19, 2, 53, 6, 43}
17 |
18 | //2. въвеждаме команди, докато не получим end
19 | String command = scanner.nextLine(); //"end" или команда
20 |
21 | while (!command.equals("end")) {
22 | //валидна команда
23 | if (command.contains("Add")) { //проверява дали в текста има думата
24 | //command = "Add {number}" -> "Add 4".split(" ") -> ["Add", "4"]
25 | //[1] -> "4" parse int -> 4
26 | int elementToAdd = Integer.parseInt(command.split(" ")[1]); //кой е елементът, който трябва да добавя накрая на списъка
27 | numbers.add(elementToAdd);
28 | } else if (command.contains("RemoveAt")) {
29 | //command = "RemoveAt {index}" -> "RemoveAt 3".split(" ") -> ["RemoveAt", "3"]
30 | //[1] -> "3" parse int -> 3
31 | int indexToRemove = Integer.parseInt(command.split(" ")[1]);
32 | numbers.remove(indexToRemove); //премахвам елемента на дадения индекс
33 | } else if (command.contains("Remove")) {
34 | //command = "Remove {number}" -> "Remove 5".split(" ") -> ["Remove", "5"]
35 | //[1] -> "5" parse int -> 5
36 | int elementToRemove = Integer.parseInt(command.split(" ")[1]);
37 | numbers.remove(Integer.valueOf(elementToRemove)); //показвам, че искам да премахна елемента
38 | } else if (command.contains("Insert")) {
39 | //command = "Insert {number} {index}"
40 | String [] commandParts = command.split(" "); //"Insert 2 3".split(" ") -> ["Insert", "2", "3"]
41 | int number = Integer.parseInt(commandParts[1]); //"2" -> 2
42 | int index = Integer.parseInt(commandParts[2]); //"3" -> 3
43 | numbers.add(index, number);
44 | }
45 | command = scanner.nextLine();
46 | }
47 |
48 | //numbers = {4, 53, 6, 8, 43, 3}
49 | for (int number : numbers) {
50 | System.out.print(number + " ");
51 | }
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/Mid-Exam-Preparation/Numbers_03.java:
--------------------------------------------------------------------------------
1 | package ExamPreparation;
2 |
3 | import java.util.*;
4 | import java.util.stream.Collectors;
5 |
6 | public class Numbers_03 {
7 | public static void main(String[] args) {
8 | Scanner scanner = new Scanner(System.in);
9 |
10 | //входни данни
11 | List numbers = Arrays.stream(scanner.nextLine() // "10 20 30 40 50"
12 | .split("\\s+")) //["10", "20", "30", "40", "50"]
13 | .map(Integer::parseInt) // [10, 20, 30, 40, 50]
14 | .collect(Collectors.toList()); //{10, 20 , 30, 40, 50}
15 |
16 |
17 | int sum = 0; //сума от елементите в списъка
18 | for (int number : numbers) {
19 | sum += number;
20 | }
21 |
22 | //средно аритмечтината стойност в списъка = сума от стойности / бр. стойности
23 | double average = sum * 1.0 / numbers.size();
24 |
25 | List greaterElements = new ArrayList<>(); //числа, по-големи от средното число (average)
26 | for (int number : numbers) {
27 | if (number > average) {
28 | greaterElements.add(number);
29 | }
30 | }
31 |
32 | //greaterElements -> всички числа по-големи от средното число в пърчоначалния списък
33 | Collections.sort(greaterElements); //ascending order
34 | Collections.reverse(greaterElements); //descending order
35 |
36 |
37 |
38 | //имаме ВСИЧКИ числа в списъка greaterElements наредени по големина
39 | if (greaterElements.size() > 0) {
40 | if (greaterElements.size() < 5) {
41 | //I начин за отпечатване на всички числа в списъка
42 | System.out.println(greaterElements.toString() //"[2, 4, 5, 6]"
43 | .replace("[", "") //"2, 4, 5, 6]"
44 | .replace("]", "") //"2, 4, 5, 6"
45 | .replace(",", "") //"2 4 5 6"
46 | );
47 |
48 | //II начин за отпечатване на всички числа в списъка
49 | /*for (int number : greaterElements) {
50 | System.out.print(number + " ");
51 | }*/
52 | } else {
53 | //greaterElements = {98, 76, 65, 54, 43, 32, 31, 28, 26}
54 | List top5Numbers = greaterElements.subList(0, 5); //първите 5 числа: {98, 76, 65, 54, 43}
55 | for (int number : top5Numbers) {
56 | System.out.print(number + " ");
57 | }
58 | }
59 |
60 | } else {
61 | //нямаме числа в списъка greaterElements
62 | System.out.println("No");
63 | }
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/Text Procressing - Exercise/Demos/DemoStrings.java:
--------------------------------------------------------------------------------
1 | public class DemoStrings {
2 | public static void main(String[] args) {
3 | String name = "Desislava";
4 |
5 | //1. дължина на текст = брой символи
6 | System.out.println(name.length());
7 |
8 | //2. само главни букви
9 | System.out.println(name.toUpperCase());
10 |
11 | //3. само с малки букви
12 | System.out.println(name.toLowerCase());
13 |
14 | //4. в масив от символи: "Desislava" -> ['D', 'e', 's', 'i', 's', 'l', 'a', 'v', 'a']
15 | char [] symbols = name.toCharArray();
16 |
17 | //5. сравняване на текстове -> true, false
18 | System.out.println("Desislava".equals(name));
19 | System.out.println("DeSIslava".equalsIgnoreCase(name)); //не прави разлика между малки и главни букви
20 |
21 | //6. достъпваме символ от текста
22 | //позиция (индекс) = 0 -> първия символ
23 | //позиция (индекс) = дължина на текст - 1 -> последния символ
24 | System.out.println(name.charAt(0));
25 | System.out.println(name.charAt(name.length() - 1));
26 |
27 | //7. съдържа определен текст -> true (ако се съдържа), false (ако не се съдържа)
28 | System.out.println(name.contains("Des"));
29 |
30 | //8. започва с опеределен текст -> true (ако започва), false (ако не започва)
31 | System.out.println(name.startsWith("De"));
32 |
33 | //9. завършва на определен текст -> true (ако завършва), false (ако не завършва)
34 | System.out.println(name.endsWith("lava"));
35 |
36 | //10. премахва интервалите в началото и края на текста
37 | System.out.println(" Desislava ".trim());
38 |
39 | //11. заменя първото срещане на даден текст / символ
40 | name.replace("va", "ta"); //"Desislava" -> "Desislata"
41 | name.replace('v', 'r'); //"Desislava" -> "Desislara"
42 |
43 | //12. заменя всички срещания на текста
44 | name.replaceAll("a", "b"); //"Desislava" -> "Desislbvb"
45 |
46 | //13. повтаряме текста даден брой пъти
47 | System.out.println(name.repeat(5)); //"DesislavaDesislavaDesislavaDesislavaDesislava"
48 |
49 | //14. текст, който е част от друг текст
50 | //"Desislava" -> "sislava"
51 | System.out.println(name.substring(2));
52 | //"Desislava" -> "esis"
53 | System.out.println(name.substring(1, 5));
54 |
55 | //EXAMPLE
56 | String test = "I am enjoying programming";
57 | System.out.println(test.substring(5, 13));
58 | String text = "enjoying";
59 | int index = test.indexOf(text); //индексът на първата буква на текста = 5
60 | System.out.println(test.substring(index, index + text.length()));
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 | }
69 | }
--------------------------------------------------------------------------------
/Basic Web Project/phonebook/target/classes/templates/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Phonebook
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 | | Name |
35 | Number |
36 |
37 |
38 |
39 |
40 | |
41 | |
42 |
43 |
44 |
45 |
46 |
70 |
71 |
72 |
73 |
76 |
77 |
78 |
79 |
--------------------------------------------------------------------------------
/Basic Web Project/phonebook/src/main/resources/templates/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Phonebook
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 | | Name |
35 | Number |
36 |
37 |
38 |
39 |
40 | |
41 | |
42 |
43 |
44 |
45 |
46 |
70 |
71 |
72 |
73 |
76 |
77 |
78 |
79 |
--------------------------------------------------------------------------------
/Arrays - Exercise/Solutions/ArrayModifier_09.java:
--------------------------------------------------------------------------------
1 | package Arrays;
2 |
3 | import java.util.Scanner;
4 | import java.util.Arrays;
5 |
6 | public class ArrayModifier_09 {
7 | public static void main(String[] args) {
8 | Scanner scanner = new Scanner(System.in);
9 | int [] numbers = Arrays.stream(scanner.nextLine() //"23 -2 321 87 42 90 -123"
10 | .split(" ")) //["23", "-2", "321", "87", "42", "90", "-123"]
11 | .mapToInt(Integer::parseInt) //[23, -2, 321, 87, 42, 90, -123]
12 | .toArray();
13 |
14 | String command = scanner.nextLine();
15 | //"swap {index1} {index2}".split(" ") ->
16 | //"multiply {index1} {index2}".split(" ") -> ["multiply", "3", "4"]
17 | //"decrease".split(" ") -> ["decrease"]
18 |
19 | while (!command.equals("end")) {
20 | String[] commandParts = command.split(" ");
21 | String commandType = commandParts[0]; //"swap", "multiply", "decrease"
22 | switch (commandType) {
23 | case "swap":
24 | //commandParts: ["swap", "3", "4"]
25 | int index1 = Integer.parseInt(commandParts[1]);
26 | int element1 = numbers[index1];
27 | int index2 = Integer.parseInt(commandParts[2]);
28 | int element2 = numbers[index2];
29 |
30 | //swap
31 | numbers[index1] = element2;
32 | numbers[index2] = element1;
33 | break;
34 | case "multiply":
35 | //изпълнявам командата multiply
36 | int multiplyElementIndex1 = Integer.parseInt(commandParts[1]);
37 | int multiplyElement1 = numbers[multiplyElementIndex1];
38 | int multiplyElementIndex2 = Integer.parseInt(commandParts[2]);
39 | int multiplyElement2 = numbers[multiplyElementIndex2];
40 |
41 | int product = multiplyElement1 * multiplyElement2;
42 | numbers[multiplyElementIndex1] = product;
43 | break;
44 | case "decrease":
45 | //всички елементи в масива -1
46 | for (int index = 0; index <= numbers.length - 1; index++) {
47 | numbers[index] = numbers[index] - 1;
48 | }
49 | break;
50 | }
51 | command = scanner.nextLine();
52 | }
53 |
54 | //отпечатваме масива (", ")
55 | /*for (int index = 0; index <= numbers.length - 1; index++) {
56 | if (index != numbers.length - 1) {
57 | System.out.print(numbers[index] + ", ");
58 | } else {
59 | System.out.print(numbers[index]);
60 | }
61 | }*/
62 |
63 | System.out.println(Arrays.toString(numbers).replace("[", "").replace("]", ""));
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/Text Procressing - Exercise/Solutions/LettersChangeNumbers_08.java:
--------------------------------------------------------------------------------
1 | package TextProcessing;
2 |
3 | import java.util.Scanner;
4 |
5 | public class LettersChangeNumbers_08 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 | //код: {буква}{число}{буква}
9 | String input = scanner.nextLine(); //"A12b s17G"
10 | String [] codes = input.split("\\s+");
11 |
12 | double totalSum = 0; //сума от модифицираните числа на всички кодове
13 | for (String code : codes) {
14 | //code: "{буква}{число}{буква}" => "A23C"
15 | //модификация на нашето число в кода -> сумираме
16 | double modifiedNumber = getModifiedNumber(code);
17 | totalSum += modifiedNumber;
18 | }
19 |
20 | System.out.printf("%.2f", totalSum);
21 | }
22 | //метод, който приема кода и връща модифицираното число
23 | private static double getModifiedNumber (String code) {
24 | //код: {буква}{число}{буква} => "A12b"
25 | char letterBefore = code.charAt(0); //'A'
26 | char letterAfter = code.charAt(code.length() - 1); // 'b'
27 |
28 | double number = Double.parseDouble(code.replace(letterBefore, ' ') //" 12b"
29 | .replace(letterAfter, ' ') //" 12 "
30 | .trim()); //"12" -> 12
31 |
32 | number = modifyByLetterBefore(letterBefore, number); //модифицира спрямо буквата преди числото
33 | number = modifyByLetterAfter(letterAfter, number); //модифицира спрямо буквата след числото
34 | return number;
35 | }
36 |
37 | private static double modifyByLetterAfter(char letterAfter, double number) {
38 | //проверка за буквата след -> letterAfter
39 | if (Character.isUpperCase(letterAfter)) {
40 | //главна буква -> [65;90]
41 | int positionUpperLetter = (int) letterAfter - 64;
42 | number = number - positionUpperLetter;
43 | //number -= positionUpperLetter;
44 | } else {
45 | //малка буква -> [97, 122]
46 | int positionLowerLetter = (int) letterAfter - 96;
47 | number = number + positionLowerLetter;
48 | //number += positionLowerLetter;
49 | }
50 | return number;
51 | }
52 |
53 | private static double modifyByLetterBefore(char letterBefore, double number) {
54 | //проверка за буквата преди -> letterBefore
55 | if (Character.isUpperCase(letterBefore)) {
56 | //главна буква -> [65; 90]
57 | int positionUpperLetter = (int) letterBefore - 64;
58 | number = number / positionUpperLetter;
59 | //number /= positionUpperLetter;
60 | } else {
61 | //малка буква -> [97, 122]
62 | int positionLowerCase = (int) letterBefore - 96;
63 | number = number * positionLowerCase;
64 | //number *= positionLowerCase;
65 | }
66 | return number;
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/Final-Exam-Preparation-2/WorldTour_01.java:
--------------------------------------------------------------------------------
1 | package ExamPreparation2;
2 |
3 | import java.util.Scanner;
4 |
5 | public class WorldTour_01 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 |
9 | String allStops = scanner.nextLine(); //всички спирки: "Hawai::Cyprys-Greece"
10 | StringBuilder stopsBuilder = new StringBuilder(allStops);
11 |
12 | String command = scanner.nextLine();
13 | while(!command.equals("Travel")) {
14 | //команда
15 | if (command.contains("Add Stop")) {
16 | //command = "Add Stop:2:Italy".split(":") -> ["Add Stop", "2", "Italy"]
17 | int index = Integer.parseInt(command.split(":")[1]); //индекс, на който трябва да вмъкнем спирка
18 | String stopName = command.split(":")[2]; //спирка, която трябва да вмъкнем
19 |
20 | //валидирам индекса
21 | //първия (0) до последния индекс (дължина - 1)
22 | if (isValidIndex(index, stopsBuilder)) {
23 | stopsBuilder.insert(index, stopName);
24 | }
25 |
26 | } else if (command.contains("Remove Stop")) {
27 | //command = "Remove Stop:2:9".split(":") -> ["Remove Stop", "2", "9"]
28 | int startIndex = Integer.parseInt(command.split(":")[1]);
29 | int endIndex = Integer.parseInt(command.split(":")[2]);
30 |
31 | //валидираме индексите
32 | if (isValidIndex(startIndex, stopsBuilder) && isValidIndex(endIndex, stopsBuilder)) {
33 | stopsBuilder.delete(startIndex, endIndex + 1);
34 | }
35 |
36 | } else if (command.contains("Switch")) {
37 | //command = "Switch:Italy:Spain".split(":") -> ["Switch", "Italy", "Spain"]
38 | String oldText = command.split(":")[1];
39 | String newText = command.split(":")[2];
40 |
41 | //!!! правим замяната на стария с новия, само ако стария съществува
42 | if (stopsBuilder.toString().contains(oldText)) {
43 | String updatedText = stopsBuilder.toString().replace(oldText, newText); //текст след заместването
44 | stopsBuilder = new StringBuilder(updatedText);
45 | }
46 | }
47 |
48 | System.out.println(stopsBuilder);
49 | command = scanner.nextLine();
50 | }
51 |
52 | System.out.println("Ready for world tour! Planned stops: " + stopsBuilder);
53 |
54 |
55 | }
56 |
57 | //метод, който валидира индекс в текст stopsBuilder
58 | //true -> ако индексът е валиден
59 | //false -> ако индексът не е валиден
60 | public static boolean isValidIndex (int index, StringBuilder builder) {
61 | //първия (0) до последния индекс (дължина - 1)
62 | return index >= 0 && index <= builder.length() - 1;
63 | //return index >= 0 && index < builder.length();
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/RegEx - Exercise/Race_02.java:
--------------------------------------------------------------------------------
1 | package RegEx;
2 |
3 | import java.util.*;
4 | import java.util.regex.Matcher;
5 | import java.util.regex.Pattern;
6 | import java.util.stream.Collectors;
7 |
8 | public class Race_02 {
9 | public static void main(String[] args) {
10 | Scanner scanner = new Scanner(System.in);
11 | String names = scanner.nextLine(); //"George, Peter, Bill, Tom"
12 | List racersNames = Arrays.stream(names.split(", ")) //["George", "Peter", "Bill", "Tom"]
13 | .collect(Collectors.toList()); //{"George", "Peter", "Bill", "Tom"} -> списък с имената на състезателите в състезанието
14 |
15 | Map racersDistances = new LinkedHashMap<>();
16 | //име на състезател -> дистанция
17 | racersNames.forEach(racer -> racersDistances.put(racer, 0));
18 |
19 | //Regex
20 | String lettersRegex = "[A-Za-z]";
21 | Pattern patternLetter = Pattern.compile(lettersRegex);
22 |
23 | String digitsRegex = "[0-9]";
24 | Pattern patternDigit = Pattern.compile(digitsRegex);
25 |
26 | String input = scanner.nextLine();
27 | while (!input.equals("end of race")) {
28 | //input = "G!32e%o7r#32g$235@!2e"
29 |
30 | //име на състезателя -> само буквите
31 | StringBuilder nameBuilder = new StringBuilder(); //конструираме името на състезателя
32 | Matcher matcherLetter = patternLetter.matcher(input); //всички букви -> ["G", "e", "o", "r", "g", "e"]
33 | while (matcherLetter.find()) {
34 | nameBuilder.append(matcherLetter.group());
35 | }
36 |
37 | //дистанция на състезателя -> сума от цифрите
38 | int distance = 0; //сумирам всички цифри
39 | Matcher matcherDigit = patternDigit.matcher(input); //всички цифри -> ["3", "2", "7", "3", "2", "2", "3", "5"]
40 | while (matcherDigit.find()) {
41 | distance += Integer.parseInt(matcherDigit.group());
42 | }
43 |
44 | //? има ли такъв състезател -> добавя дистанцията към съответния състезател
45 | String racerName = nameBuilder.toString(); //име на състезателя
46 | if (racersNames.contains(racerName)) {
47 | //име на състезател -> дистанция
48 | int currentDistance = racersDistances.get(racerName);
49 | racersDistances.put(racerName, currentDistance + distance);
50 | }
51 |
52 |
53 | input = scanner.nextLine();
54 | }
55 |
56 | //{"George", "Peter", "Bill", "Tom"}
57 | for (int index = 0; index <= 2; index++) {
58 | String racer = racersNames.get(index);
59 | if (index == 0) {
60 | System.out.println("1st place: " + racer);
61 | } else if (index == 1) {
62 | System.out.println("2nd place: " + racer);
63 | } else if (index == 2) {
64 | System.out.println("3rd place: " + racer);
65 | }
66 | }
67 |
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/Basic Syntax, Conditional Statements and Loops - Exercise/Solutions/VendingMachine_07.java:
--------------------------------------------------------------------------------
1 | package BasicSyntax;
2 |
3 | import java.util.Scanner;
4 |
5 | public class VendingMachine_07 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 | String command = scanner.nextLine();
9 | double sum = 0;
10 | //with 0.1, 0.2, 0.5, 1, and 2
11 | while(!command.equals("Start")) {
12 | double coin = Double.parseDouble(command);
13 | if(coin != 0.1 && coin != 0.2 && coin != 0.5 && coin != 1 && coin != 2) {
14 | System.out.printf("Cannot accept %.2f%n", coin);
15 | } else {
16 | sum += coin;
17 | }
18 |
19 | command = scanner.nextLine();
20 | }
21 |
22 | String product = scanner.nextLine();
23 |
24 | //"Nuts", "Water", "Crisps", "Soda", "Coke". The prices are: 2.0, 0.7, 1.5, 0.8, 1.0
25 | while(!product.equals("End")) {
26 | boolean hasMoney = true;
27 | switch(product) {
28 | case "Nuts":
29 | if(sum < 2) {
30 | System.out.println("Sorry, not enough money");
31 | hasMoney = false;
32 | } else {
33 | sum -= 2;
34 | }
35 | break;
36 | case "Water":
37 | if(sum < 0.7) {
38 | System.out.println("Sorry, not enough money");
39 | hasMoney = false;
40 | } else {
41 | sum -= 0.7;
42 | }
43 | break;
44 | case "Crisps":
45 | if(sum < 1.5) {
46 | System.out.println("Sorry, not enough money");
47 | hasMoney = false;
48 | } else {
49 | sum -= 1.5;
50 | }
51 | break;
52 | case "Soda":
53 | if(sum < 0.8) {
54 | System.out.println("Sorry, not enough money");
55 | hasMoney = false;
56 | } else {
57 | sum -= 0.8;
58 | }
59 |
60 | break;
61 | case "Coke":
62 | if(sum < 1) {
63 | System.out.println("Sorry, not enough money");
64 | hasMoney = false;
65 | } else {
66 | sum -= 1;
67 | }
68 | break;
69 | default:
70 | System.out.println("Invalid product");
71 | hasMoney = false;
72 | break;
73 | }
74 | if(!hasMoney) {
75 | product = scanner.nextLine();
76 | continue;
77 | }
78 | System.out.printf("Purchased %s%n", product);
79 |
80 |
81 | product = scanner.nextLine();
82 | }
83 |
84 | System.out.printf("Change: %.2f", sum);
85 | }
86 | }
87 |
--------------------------------------------------------------------------------
/Maps - Exercise/Solutions/Forcebook_09.java:
--------------------------------------------------------------------------------
1 | package Maps;
2 |
3 | import java.util.*;
4 |
5 | public class Forcebook_09 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 |
9 | String input = scanner.nextLine();
10 |
11 | //отбор -> списък с играчите
12 | Map> teams = new LinkedHashMap<>();
13 |
14 | while (!input.equals("Lumpawaroo")) {
15 | if (input.contains("|")) {
16 | //input = "{force_side} | {force_user}" .split -> ["team", "player"]
17 | String team = input.split(" \\| ")[0]; //отбор
18 | String player = input.split(" \\| ")[1];// играча
19 |
20 | //нямаме такъв отбор -> създаваме
21 | if (!teams.containsKey(team)) {
22 | teams.put(team, new ArrayList<>());
23 | }
24 |
25 | //имаме такъв отбор -> добавяме играча към отбора, само ако го няма в НИКОЙ друг отбор
26 | boolean isExist = false; //играча го има в някой друг отбор
27 | for (List list : teams.values()) {
28 | if (list.contains(player)) {
29 | isExist = true;
30 | }
31 | }
32 | //isExist = true => играчът го има в някой отбор
33 | //isExist = false => играчът го няма в никой отбор
34 | if (!isExist) {
35 | teams.get(team).add(player);
36 | }
37 |
38 |
39 | }
40 | else if (input.contains("->")) {
41 | //input = "{force_user} -> {force_side}".split -> ["player", "team"]
42 | String player = input.split(" -> ")[0];
43 | String team = input.split(" -> ")[1];
44 |
45 | //1. премахваме играча от текущия отбор
46 | teams.entrySet().forEach(entry -> entry.getValue().remove(player));
47 |
48 | //2. отборът, в който отива дали съществува
49 | if (teams.containsKey(team)) {
50 | List currentPlayers = teams.get(team); //текущия списък на играчите
51 | currentPlayers.add(player); //добавяме играча към новия му отбор
52 | } else {
53 | //отборът, в който отива да не съществува
54 | teams.put(team, new ArrayList<>());
55 | teams.get(team).add(player);
56 | }
57 |
58 | System.out.printf("%s joins the %s side!%n", player, team);
59 |
60 | }
61 | input = scanner.nextLine();
62 | }
63 |
64 | //премахваме отборите без играчи
65 | //entry: team (key) -> list of players (value)
66 | //filter -> оставя записите, които отговарят на условието
67 | //премахваме всички, които entry.getValue().size() <= 0
68 | teams.entrySet() //всички записи: team (key) -> list of players (value)
69 | .stream().filter(entry -> entry.getValue().size() > 0) //оставяме само отбори с играчи
70 | .forEach(entry -> {
71 | System.out.println("Side: " + entry.getKey() + ", Members: " + entry.getValue().size());
72 | entry.getValue().forEach(player -> System.out.println("! " + player));
73 | });
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/Lists - Exercise/Solutions/PokemonDontGo_09.java:
--------------------------------------------------------------------------------
1 | package Lists_Exercise;
2 |
3 | import java.util.Arrays;
4 | import java.util.List;
5 | import java.util.Scanner;
6 | import java.util.stream.Collectors;
7 |
8 | public class PokemonDontGo_09 {
9 | public static void main(String[] args) {
10 | Scanner scanner = new Scanner(System.in);
11 |
12 | List numbers = Arrays.stream(scanner.nextLine()
13 | .split("\\s+"))
14 | .map(Integer::parseInt)
15 | .collect(Collectors.toList()); // {4, 5, 3}
16 |
17 | //повтаряме: въвеждаме индекс
18 | //стоп: нямаме елементи в списъка (size <= 0)
19 | //продължаваме: имаме елементи в списъка (size > 0)
20 |
21 | int sum = 0; //сума на премахнатите елементи
22 |
23 | while (numbers.size() > 0) {
24 | int index = Integer.parseInt(scanner.nextLine());
25 | //1. index < 0
26 | if (index < 0) {
27 | // {8, 5, 3, 6, 7, 8}
28 | //1. взимам кой ми е първия елемент в списъка
29 | int firstElement = numbers.get(0);
30 | //2. премахваме елемента от първото място -> сумиране
31 | numbers.remove(0);
32 | sum += firstElement;
33 | //3. взимам кой ми е последния елемент в списъка
34 | int lastElement = numbers.get(numbers.size() - 1);
35 | //4. сложим последния елемент на първо място
36 | numbers.add(0, lastElement);
37 | //5. модифицирам списъка спрямо премахнатия елемент
38 | modifyList(numbers, firstElement);
39 | }
40 | //2. index > последния индекс в списъка
41 | else if (index > numbers.size() - 1) {
42 | //1. взимаме последния елемент
43 | int lastElement = numbers.get(numbers.size() - 1);
44 | //2. премахваме последния елемент
45 | numbers.remove(numbers.size() - 1);
46 | sum += lastElement;
47 | //3. взимаме първия елемент
48 | int firstElement = numbers.get(0);
49 | //4. вмъкнем първия елемент на последно място
50 | numbers.add(firstElement);
51 | //5. модифицираме списъка спрямо премахнатия елемент
52 | modifyList(numbers, lastElement);
53 | }
54 | //3. index да е валиден -> index >= 0 и index <= последния
55 | else if (index >= 0 && index <= numbers.size() - 1) {
56 | //1. взимам кой е елемента на дадения индекс
57 | int removedNumber = numbers.get(index);
58 | sum += removedNumber;
59 | //2. премахваме елемента на дадения индекс
60 | numbers.remove(index);
61 | //3. модифицирам списъка спрямо премахнатото число
62 | modifyList(numbers, removedNumber);
63 | }
64 | }
65 |
66 | System.out.println(sum);
67 | }
68 |
69 | public static void modifyList(List numbers, int removedNumber) {
70 | for (int index = 0; index <= numbers.size() - 1; index++) {
71 | int currentElement = numbers.get(index); //текущ елемент
72 | if (currentElement <= removedNumber) {
73 | currentElement += removedNumber;
74 | } else {
75 | currentElement -= removedNumber;
76 | }
77 |
78 | numbers.set(index, currentElement);
79 | }
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/Methods - Exercise/Solutions/PasswordValidator_04.java:
--------------------------------------------------------------------------------
1 | package Methods;
2 |
3 | import java.util.Scanner;
4 |
5 | public class PasswordValidator_04 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 | String password = scanner.nextLine();
9 |
10 | //1. проверим дали дължината на паролата е валидна
11 | boolean isValidLength = isValidLength(password);
12 | //isValidLength = true -> валидна парола
13 | //isValidLength = false -> невалидна парола
14 | if (!isValidLength) {
15 | //паролата не е валидна
16 | System.out.println("Password must be between 6 and 10 characters");
17 | }
18 |
19 | //2. проверим дали съдържанието е валидно
20 | boolean isValidContent = isValidContent(password);
21 | //isValidContent = true -> валидно съдържание
22 | //isValidContent = false -> невалидно съдържание
23 | if (!isValidContent) {
24 | System.out.println("Password must consist only of letters and digits");
25 | }
26 |
27 | //3. проверим дали брой на цифрите е валиден
28 | boolean isValidCount = isValidCountDigits(password);
29 | //isValidCount = true -> валиден брой
30 | //isValidCount = false -> невалиден брой
31 | if (!isValidCount) {
32 | System.out.println("Password must have at least 2 digits");
33 | }
34 |
35 | //4. проверяваме дали цялостно е валидна паролата
36 | if (isValidLength && isValidContent && isValidCount) {
37 | System.out.println("Password is valid");
38 | }
39 |
40 | }
41 |
42 | //метод, който проверява дали ми е валидна дължината на паролата
43 | //true -> ако дължината на паролата е валидна
44 | //false -> ако дължината на паролата не е валидна
45 | public static boolean isValidLength (String password) {
46 | //валидна дължина: [6; 10]
47 | //невалидна дължина: < 6 или > 10
48 | return password.length() >= 6 && password.length() <= 10;
49 | }
50 |
51 | //метод, който проверява дали ми е валидно съдържанието на паролата
52 | //true -> ако съдържанието е валидно
53 | //false -> ако съдържанието не е валидно
54 | public static boolean isValidContent (String password) {
55 | //password = "logIn".toCharArray() -> ['l', 'o', 'g', 'I', 'n']
56 | //валидно съдържание: букви или цифри
57 | //невалидно съдържание: нещо различно от буква или цифра
58 | for (char symbol : password.toCharArray()) {
59 | if (!Character.isLetterOrDigit(symbol)) {
60 | //isLetterOrDigit
61 | //true ако символа е буква или цифра
62 | //false ако символа не е нито буква, нито цифра
63 | return false;
64 | }
65 | }
66 | //обходили всички символи
67 | return true;
68 | }
69 |
70 | //метод, който проверява дали е валиден броя на цифрите в паролата
71 | //true -> ако броят е валиден >= 2
72 | //false -> ако броят е невалиден < 2
73 | public static boolean isValidCountDigits (String password) {
74 | int countDigits = 0; //брой на цифрите в паролата
75 | //password = "Pesho123".toCharArray()
76 | for (char symbol : password.toCharArray()) {
77 | if (Character.isDigit(symbol)) {
78 | //isDigit
79 | //true -> ако символа е цифра
80 | //false -> ако символа не е цифра
81 | countDigits++;
82 | }
83 | }
84 | //true -> брой >= 2
85 | //false -> брой < 2
86 | return countDigits >= 2;
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/Maps - Exercise/Solutions/LegendaryFarming_07.java:
--------------------------------------------------------------------------------
1 | package Maps;
2 |
3 | import java.util.LinkedHashMap;
4 | import java.util.Map;
5 | import java.util.Scanner;
6 |
7 | public class LegendaryFarming_07 {
8 | public static void main(String[] args) {
9 | Scanner scanner = new Scanner(System.in);
10 |
11 | //Shards -> количество
12 | //Fragments -> количество
13 | //Motes -> количество
14 |
15 | //запис: материал -> количество
16 | Map materials = new LinkedHashMap<>(); //нужни материали
17 | materials.put("shards", 0);
18 | materials.put("fragments", 0);
19 | materials.put("motes", 0);
20 |
21 | //запис: боклук -> количество
22 | Map junks = new LinkedHashMap<>(); //боклуци
23 |
24 |
25 | boolean isWin = false;
26 | //true -> ако сме спечелили
27 | //false -> ако не сме спечелили
28 |
29 | //стоп: ако спечелим
30 | //продължаваме: ако не сме спечелили
31 | while (!isWin) {
32 | String input = scanner.nextLine();
33 | //input = "6 leathers 255 fragments 7 Shards"
34 | String [] inputData = input.split("\\s+");
35 | //inputData = ["6", "leathers", "255", "fragments", "7", "Shards", ...]
36 |
37 | for (int index = 0; index <= inputData.length - 1; index += 2) {
38 | int quantity = Integer.parseInt(inputData[index]); //количество
39 | String material = inputData[index + 1].toLowerCase(); //вид на събрания материал с малки букви
40 |
41 | //проверка какъв материал сме събрали -> събираме
42 | if (material.equals("shards") || material.equals("fragments") || material.equals("motes")) {
43 | //валиден материал
44 | int currentQuantity = materials.get(material);
45 | materials.put(material, currentQuantity + quantity);
46 | } else {
47 | //материалът е боклук
48 | if(!junks.containsKey(material)) {
49 | junks.put(material, quantity);
50 | } else {
51 | int currentQuantity = junks.get(material);
52 | junks.put(material, currentQuantity + quantity);
53 | }
54 | }
55 |
56 | //проверка дали сме спечелили легендарния предмет
57 | if (materials.get("shards") >= 250) {
58 | System.out.println("Shadowmourne obtained!");
59 | materials.put("shards", materials.get("shards") - 250);
60 | isWin = true;
61 | break;
62 | } else if (materials.get("fragments") >= 250) {
63 | System.out.println("Valanyr obtained!");
64 | materials.put("fragments", materials.get("fragments") - 250);
65 | isWin = true;
66 | break;
67 | } else if (materials.get("motes") >= 250) {
68 | System.out.println("Dragonwrath obtained!");
69 | materials.put("motes", materials.get("motes") - 250);
70 | isWin = true;
71 | break;
72 | }
73 |
74 | }
75 |
76 | if (isWin) {
77 | break;
78 | }
79 | }
80 |
81 | //всички валидни материали -> materials
82 | //entry: материал (key): количество (value)
83 | materials.entrySet().forEach(entry -> System.out.println(entry.getKey() + ": " + entry.getValue()));
84 |
85 | //всички боклуци -> junks
86 | //entry: материал (key): количество (value)
87 | junks.entrySet().forEach(entry -> System.out.println(entry.getKey() + ": " + entry.getValue()));
88 | }
89 | }
90 |
--------------------------------------------------------------------------------
/RegEx - Exercise/StarEnigma_04.java:
--------------------------------------------------------------------------------
1 | package RegEx;
2 |
3 | import java.util.*;
4 | import java.util.regex.Matcher;
5 | import java.util.regex.Pattern;
6 |
7 | public class StarEnigma_04 {
8 | public static void main(String[] args) {
9 | Scanner scanner = new Scanner(System.in);
10 | int countMessages = Integer.parseInt(scanner.nextLine());
11 | String regex = "@(?[A-Za-z]+)[^@!:>-]*:(?[0-9]+)[^@!:>-]*!(?[AD])![^@!:>-]*->(?[0-9]+)";
12 | Pattern pattern = Pattern.compile(regex);
13 |
14 | List attackersPlanets = new ArrayList<>(); //атакуващи планети (attackType е "А")
15 | List destroyedPlanets = new ArrayList<>(); //унищожени планети (attackType е "D")
16 |
17 | for (int messageCount = 1; messageCount <= countMessages; messageCount++) {
18 | String encryptedMessage = scanner.nextLine(); //криптираното съобщение
19 | String decryptedMessage = getDecryptedMessage(encryptedMessage); //декриптирано съобщение
20 | //декриптирано: "PQ@Alderaa1:30000!A!->20000"
21 | Matcher matcher = pattern.matcher(decryptedMessage);
22 | //matcher: "@(?Alderaa)[^@!:>-]*:(?30000)[^@!:>-]*!(?A)![^@!:>-]*->(?20000)";
23 | if (matcher.find()) {
24 | String planetName = matcher.group("planetName");
25 | //int population = Integer.parseInt(matcher.group("population"));
26 | String attackType = matcher.group("attackType");
27 | //int soldiersCount = Integer.parseInt(matcher.group("soldiersCount"));
28 |
29 | if (attackType.equals("A")) {
30 | //атакуваща планета
31 | attackersPlanets.add(planetName);
32 | } else if (attackType.equals("D")) {
33 | //унищожена планета
34 | destroyedPlanets.add(planetName);
35 | }
36 | }
37 | }
38 |
39 | System.out.println("Attacked planets: " + attackersPlanets.size());
40 | Collections.sort(attackersPlanets); //сортирам планетите по име
41 | attackersPlanets.forEach(planet -> System.out.println("-> " + planet));
42 |
43 | System.out.println("Destroyed planets: " + destroyedPlanets.size());
44 | Collections.sort(destroyedPlanets); //сортирам планетите по име
45 | destroyedPlanets.forEach(planet -> System.out.println("-> " + planet));
46 | }
47 |
48 | //върне декриптираното съобщение
49 | private static String getDecryptedMessage(String encryptedMessage) {
50 | //1. брой на символите [s, t, a, r, S, T, A, R]
51 | //криптирано съобщение: STCDoghudd4=63333$D$0A53333 -> 3 специални букви
52 | int countLetters = getSpecialLettersCount(encryptedMessage);
53 |
54 | //декриптиране -> контруираме ново съобщение
55 | StringBuilder decryptedMessage = new StringBuilder();
56 | //1. всеки символ от критпираното съобщение
57 | //2. нов символ -> ascii на нов символ = ascii на текущия символ - countLetters
58 | //3. добавяме нов символ
59 | for (char symbol : encryptedMessage.toCharArray()) {
60 | char newSymbol = (char)(symbol - countLetters);
61 | decryptedMessage.append(newSymbol);
62 | }
63 |
64 | return decryptedMessage.toString();
65 | }
66 |
67 | //върне общия брой на буквите: [s, t, a, r, S, T, A, R]
68 | private static int getSpecialLettersCount(String encryptedMessage) {
69 | //криптирано съобщение: STCDoghudd4=63333$D$0A53333 -> 3 специални букви
70 | int count = 0;
71 | for (char symbol : encryptedMessage.toCharArray()) {
72 | switch (symbol) {
73 | case 's':
74 | case 't':
75 | case 'a':
76 | case 'r':
77 | case 'S':
78 | case 'T':
79 | case 'A':
80 | case 'R':
81 | count++;
82 | break;
83 | }
84 | }
85 |
86 | return count;
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/Lists - Exercise/Solutions/AnonymousThreat_08.java:
--------------------------------------------------------------------------------
1 | package Lists_Exercise;
2 |
3 | import java.util.Arrays;
4 | import java.util.List;
5 | import java.util.Scanner;
6 | import java.util.stream.Collectors;
7 |
8 | public class AnonymousThreat_08 {
9 | public static void main(String[] args) {
10 | Scanner scanner = new Scanner(System.in);
11 |
12 | List texts = Arrays.stream(scanner.nextLine().split("\\s+")) //["Ivo", "Johny", "Tony", "Bony", "Mony"]
13 | .collect(Collectors.toList()); //{"Ivo", "Johny", "Tony", "Bony", "Mony"}
14 |
15 | String command = scanner.nextLine();
16 |
17 | while (!command.equals("3:1")) {
18 | if (command.contains("merge")) {
19 | //command = "merge {startIndex} {endIndex}"
20 | int startIndex = Integer.parseInt(command.split(" ")[1]);
21 | int endIndex = Integer.parseInt(command.split(" ")[2]);
22 |
23 | //проверка startIndex
24 | if (startIndex < 0) {
25 | startIndex = 0;
26 | }
27 |
28 | //проверка за endIndex
29 | if (endIndex > texts.size() - 1) {
30 | endIndex = texts.size() - 1;
31 | }
32 |
33 | //валидиране на индексите -> [0, дълж - 1]
34 | if (startIndex >= 0 && startIndex <= texts.size() - 1 && endIndex >= 0 && endIndex <= texts.size() - 1) {
35 | //валидни индекси -> преминем към изпълняване на командата
36 | //{"Ivo", "Johny", "Tony", "Bony", "Mony"}
37 | //merge 1 3
38 | //взимаме елементите и ги обединяваме
39 | String resultMerge = ""; //резултат от обединението на елементите
40 | for (int index = startIndex; index <= endIndex; index++) {
41 | String current = texts.get(index);
42 | resultMerge += current;
43 | }
44 |
45 | //resulMerge = "JohnyTonyBony"
46 | //премахваме обединените елементи
47 | for (int index = startIndex; index <= endIndex; index++) {
48 | texts.remove(startIndex);
49 | }
50 | //{"Ivo", "Mony"}
51 |
52 | //добавяме обединението на startIndex
53 | texts.add(startIndex, resultMerge);
54 | //{"Ivo", "JohnyTonyBony", "Mony"}
55 | }
56 | } else if (command.contains("divide")) {
57 | //command = "divide {index} {partitions}"
58 | int index = Integer.parseInt(command.split(" ")[1]);
59 | int parts = Integer.parseInt(command.split(" ")[2]); //брой на частите
60 |
61 | //валидираме индекса, от който ще взимаме текст
62 | if (index >= 0 && index <= texts.size() - 1) {
63 | //{"abcdef", "ghi", "jkl"}
64 | //divide 0 3
65 | String textForDivide = texts.get(index); //"abcdef"
66 | texts.remove(index);
67 | //{"ghi", "jkl"}
68 |
69 | //1. колко символа ще има всяка част
70 | int countSymbolsPerPart = textForDivide.length() / parts;
71 |
72 | //всички равни части без последната
73 | int beginIndex = 0; //index в текста за деление
74 | for (int part = 1; part < parts; part++) {
75 | String textPerPart = textForDivide.substring(beginIndex, beginIndex + countSymbolsPerPart);
76 | texts.add(index, textPerPart);
77 | index++; //място на поставяне на разбитата част в главния списък
78 | beginIndex += countSymbolsPerPart;
79 | }
80 |
81 | //последната част
82 | String textLastParts = textForDivide.substring(beginIndex, textForDivide.length());
83 | texts.add(index, textLastParts);
84 | }
85 |
86 | }
87 |
88 |
89 | command = scanner.nextLine();
90 | }
91 |
92 | //!!!!отпчетваме списък с тесктовете -> String.join!!!
93 | System.out.println(String.join(" ", texts));
94 |
95 | /*for (String text : texts) {
96 | System.out.print(text + " ");
97 | }*/
98 | }
99 | }
100 |
--------------------------------------------------------------------------------
/Lists - Exercise/Solutions/SoftuniCoursePlaning_10.java:
--------------------------------------------------------------------------------
1 | package Lists_Exercise;
2 | import java.util.*;
3 | import java.util.stream.Collectors;
4 | public class SoftuniCoursePlaning_10 {
5 | public static void main(String[] args) {
6 | Scanner scanner = new Scanner(System.in);
7 | List schedule = Arrays.stream(scanner.nextLine().split(", ")).collect(Collectors.toList());
8 |
9 | String input = scanner.nextLine();
10 |
11 | while(!input.equals("course start")) {
12 | String [] tokens = input.split(":");
13 | String command = tokens[0];
14 | String lessonTitle = tokens[1];
15 | switch(command) {
16 | case "Add":
17 | //"Add:Databases" -> ["Add", "Databases"]
18 | if(!schedule.contains(lessonTitle)) {
19 | schedule.add(lessonTitle);
20 | }
21 | break;
22 | case "Insert":
23 | //Insert:Arrays:0 -> ["Insert", "Arrays", "0"]
24 | int index = Integer.parseInt(tokens[2]);
25 | if(!schedule.contains(lessonTitle)) {
26 | schedule.add(index, lessonTitle);
27 | }
28 | break;
29 | case "Remove":
30 | if(schedule.contains(lessonTitle)) {
31 | schedule.remove(lessonTitle);
32 | }
33 | int indexLesson = schedule.indexOf(lessonTitle);
34 | if(schedule.get(indexLesson + 1).equals(lessonTitle+"-Exercise")) {
35 | schedule.remove(indexLesson + 1);
36 | }
37 | break;
38 | case "Swap":
39 | //Arrays, Lists, Methods, Databases, Databases-Exercise
40 | //Swap:Lists:Databases
41 | String lessonTitle2 = input.split(":")[2];
42 | if (schedule.contains(lessonTitle) && schedule.contains(lessonTitle2)) {
43 | int lesson1Index = schedule.indexOf(lessonTitle);
44 | int lesson2Index = schedule.indexOf(lessonTitle2);
45 | schedule.set(lesson1Index, lessonTitle2);
46 | schedule.set(lesson2Index, lessonTitle);
47 |
48 | String exOne = lessonTitle + "-Exercise";
49 | String exTwo = lessonTitle2 + "-Exercise";
50 | if (schedule.contains(exOne)) {
51 | schedule.remove(schedule.indexOf(exOne));
52 | schedule.add(schedule.indexOf(lessonTitle + 1), exOne);
53 | }
54 | if (schedule.contains(exTwo)) {
55 | schedule.remove(schedule.indexOf(exTwo));
56 | schedule.add(schedule.indexOf(lessonTitle2) + 1, exTwo);
57 | }
58 | }
59 | break;
60 | case "Exercise":
61 | //упражнение -> Objects-Exercise
62 | //[Data Types, Objects, Lists]
63 | String exercise = lessonTitle + "-Exercise";
64 | //слагаме упражнение ако има лекция и го няма
65 | int indexLessonTitle = schedule.indexOf(lessonTitle);
66 | if(schedule.contains(lessonTitle)) {
67 | //има ли упражнение
68 | if(indexLessonTitle == schedule.size() - 1) {
69 | schedule.add(indexLessonTitle + 1, exercise);
70 | } else if(!schedule.get(indexLessonTitle + 1).equals(exercise)) {
71 | schedule.add(indexLessonTitle + 1, exercise);
72 | }
73 | } else {
74 | schedule.add(lessonTitle);
75 | schedule.add(exercise);
76 | }
77 | break;
78 | }
79 |
80 |
81 |
82 |
83 |
84 | input = scanner.nextLine();
85 | }
86 |
87 | printList(schedule);
88 | }
89 |
90 |
91 |
92 | private static void printList(List elements) {
93 | int count = 1;
94 | for (String element : elements) {
95 | System.out.println(count + "." + element);
96 | count++;
97 |
98 | }
99 | }
100 |
101 | }
102 |
--------------------------------------------------------------------------------
/Lists - Lab/ListManipulationsAdvanced_05.java:
--------------------------------------------------------------------------------
1 | package Lists_Lab;
2 |
3 | import java.util.Arrays;
4 | import java.util.List;
5 | import java.util.Scanner;
6 | import java.util.stream.Collectors;
7 |
8 | public class ListManipulationsAdvanced_05 {
9 | public static void main(String[] args) {
10 | Scanner scanner = new Scanner(System.in);
11 |
12 | //1. прочитаме лист от цели числа
13 | List numbers = Arrays.stream(scanner.nextLine() // "4 19 2 53 6 43"
14 | .split(" ")) // ["4", "19", "2", "53", "6", "43"]
15 | .map(Integer::parseInt) // [4, 19, 2, 53, 6, 43]
16 | .collect(Collectors.toList()); // {4, 19, 2, 53, 6, 43}
17 |
18 | //2. въвеждаме команди, докато не получим end
19 | String command = scanner.nextLine(); //"end" или команда
20 |
21 | while (!command.equals("end")) {
22 | //валидна команда
23 |
24 | if (command.startsWith("Contains")) {
25 | //command = "Contains 5".split(" ") -> ["Contains", "5"]
26 | int numberToCheck = Integer.parseInt(command.split(" ")[1]);
27 | printContains(numbers, numberToCheck);
28 | } else if (command.equals("Print even")) {
29 | //само четните числа
30 | printEvenNumbers(numbers);
31 | } else if (command.equals("Print odd")) {
32 | //само нечетните числа
33 | printOddNumbers(numbers);
34 | } else if (command.equals("Get sum")) {
35 | //принтираме сумата на елементите в списъка
36 | printSum(numbers);
37 | } else if (command.startsWith("Filter")) {
38 | //command = "Filter {condition} {number}" => "Filter >= 43".split(" ")
39 | //["Filter", ">=", "43"]
40 | String condition = command.split(" ")[1]; // '<', '>', ">=", "<="
41 | int numberToFilter = Integer.parseInt(command.split(" ")[2]); //43
42 | printFilteredNumbers(numbers, condition, numberToFilter);
43 | }
44 | command = scanner.nextLine();
45 | }
46 | }
47 |
48 | private static void printContains(List numbers, int numberToCheck) {
49 | //yes -> ако числото го има в списъка
50 | if (numbers.contains(numberToCheck)) {
51 | System.out.println("Yes");
52 | } else {
53 | System.out.println("No such number");
54 | }
55 | }
56 |
57 | private static void printFilteredNumbers(List numbers, String condition, int numberToFilter) {
58 | //condition = '<', '>', ">=", "<="
59 | switch (condition) {
60 | case "<":
61 | //отпечатваме всички числа в списъка numbers < numberToFilter
62 | for (int number : numbers) {
63 | if (number < numberToFilter) {
64 | System.out.print(number + " ");
65 | }
66 | }
67 | break;
68 | case ">":
69 | //отпечатваме всички числа в списъка numbers > numberToFilter
70 | for (int number : numbers) {
71 | if (number > numberToFilter) {
72 | System.out.print(number + " ");
73 | }
74 | }
75 | break;
76 | case ">=":
77 | //отпечатваме всички числа в списъка numbers >= numberToFilter
78 | for (int number : numbers) {
79 | if (number >= numberToFilter) {
80 | System.out.print(number + " ");
81 | }
82 | }
83 | break;
84 | case "<=":
85 | //отпечатваме всички числа в списъка numbers <= numberToFilter
86 | for (int number : numbers) {
87 | if (number <= numberToFilter) {
88 | System.out.print(number + " ");
89 | }
90 | }
91 | break;
92 | }
93 | }
94 |
95 | public static void printSum(List numbers) {
96 | int sum = 0; //сума на числата в списъка
97 | for (int number : numbers) {
98 | sum += number;
99 | }
100 | System.out.println(sum);
101 | }
102 |
103 | public static void printEvenNumbers(List numbers) {
104 | //numbers = {4, 19, 2, 53, 6, 43}
105 | for (int number : numbers) {
106 | if (number % 2 == 0) {
107 | System.out.print(number + " ");
108 | }
109 | }
110 | }
111 |
112 | public static void printOddNumbers (List numbers) {
113 | //numbers = {4, 19, 2, 53, 6, 43}
114 | for (int number : numbers) {
115 | if (number % 2 != 0) {
116 | System.out.print(number + " ");
117 | }
118 | }
119 | }
120 | }
121 |
--------------------------------------------------------------------------------
/Final-Exam-Preparation-2/ThePianist_03.java:
--------------------------------------------------------------------------------
1 | package ExamPreparation2;
2 |
3 | import java.util.*;
4 |
5 | public class ThePianist_03 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 |
9 | //СЪХРАНИМ ИНФОРМАЦИЯТА ЗА ПИЕСИТЕ
10 | int countPieces = Integer.parseInt(scanner.nextLine()); //брой на пиеси
11 |
12 | //запис: пиеса -> списък с информация {композитор, тоналност}
13 | Map> piecesMap = new LinkedHashMap<>();
14 |
15 | for (int piece = 1; piece <= countPieces; piece++) {
16 | String []pieceData = scanner.nextLine().split("\\|");
17 | //"{piece}|{composer}|{key}".split("|") -> ["{piece}", "{composer}", "{key}"]
18 |
19 | String pieceName = pieceData[0]; //име на пиесата
20 | String composer = pieceData[1]; //композитора на пиесата
21 | String tone = pieceData[2]; //тоналност на пиесата
22 |
23 | //създаваме списък с информация
24 | List piecesInfo = new ArrayList<>(); //празен списък -> {}
25 | piecesInfo.add(composer); //[0] - първо място
26 | piecesInfo.add(tone); //[1] - второ място
27 |
28 | piecesMap.put(pieceName, piecesInfo);
29 | }
30 |
31 | //МОДИФИЦИРАМЕ ИНФОРМАЦИЯТА ЗА ПИЕСИТЕ СПРЯМО КОМАНДИ
32 | String command = scanner.nextLine();
33 | while (!command.equals("Stop")) {
34 | //валидна команда
35 | if (command.contains("Add")) {
36 | //command = "Add|{piece}|{composer}|{key}".split("|") -> ["Add", "{piece}", "{composer}", "{key}"]
37 | String pieceName = command.split("\\|")[1]; //име на пиесата за добавяне
38 | String composer = command.split("\\|")[2];; //име на композитора на пиесата за доабвяне
39 | String tone = command.split("\\|")[3];; //тоналност на пиесата за добавяне
40 |
41 | //имаме такава пиеса
42 | if (piecesMap.containsKey(pieceName)) {
43 | System.out.println(pieceName +" is already in the collection!");
44 | } else {
45 | //нямаме такава пиеса -> добавяме
46 | List piecesInfo = new ArrayList<>(); //празен списък -> {}
47 | piecesInfo.add(composer); //[0] - първо място
48 | piecesInfo.add(tone); //[1] - второ място
49 | piecesMap.put(pieceName, piecesInfo);
50 | System.out.printf("%s by %s in %s added to the collection!%n", pieceName, composer, tone);
51 | }
52 | } else if (command.contains("Remove")) {
53 | //command = "Remove|{piece}".split("|") -> ["Remove", "{piece}"]
54 | String pieceToRemove = command.split("\\|")[1]; //пиеса, която трябва да премахнем
55 | //имаме такава пиеса
56 | if (piecesMap.containsKey(pieceToRemove)) {
57 | piecesMap.remove(pieceToRemove);
58 | System.out.printf("Successfully removed %s!%n", pieceToRemove);
59 | } else {
60 | //нямаме такава пиеса
61 | System.out.printf("Invalid operation! %s does not exist in the collection.%n", pieceToRemove);
62 | }
63 |
64 | } else if (command.contains("ChangeKey")) {
65 | //command = "ChangeKey|{piece}|{new key}".split("|") -> ["ChangeKey", "{piece}", "{newTone}"]
66 | String pieceName = command.split("\\|")[1]; //пиеса, на която ще променим тоналността
67 | String newTone = command.split("\\|")[2]; //новата тоналност
68 |
69 | //нямаме такава пиеса
70 | if (!piecesMap.containsKey(pieceName)) {
71 | System.out.printf("Invalid operation! %s does not exist in the collection.%n", pieceName);
72 | } else {
73 | //имаме такава пиеса
74 | List pieceInfo = piecesMap.get(pieceName); //списък: {композитора, тоналността}
75 | pieceInfo.set(1, newTone); //променяме текущата тоналност
76 | piecesMap.put(pieceName, pieceInfo);
77 | System.out.printf("Changed the key of %s to %s!%n", pieceName, newTone);
78 | }
79 | }
80 |
81 | command = scanner.nextLine();
82 | }
83 |
84 | //"{Piece} -> Composer: {composer}, Key: {key}"
85 | //entry: пиеса -> списък с информация {[0] -> композитора, [1] -> тоналност}
86 | //entry.getKey() -> име на пиесата
87 | //entry.getValue() -> {[0] -> композитора, [1] -> тоналност}
88 | //entry.getValue().get(0) -> композитора
89 | //entry.getValue().get(1) -> тоналност
90 |
91 | piecesMap.entrySet() //всички записи
92 | .forEach(entry ->
93 | System.out.printf("%s -> Composer: %s, Key: %s%n",
94 | entry.getKey(), entry.getValue().get(0), entry.getValue().get(1)));
95 |
96 |
97 | }
98 | }
99 |
--------------------------------------------------------------------------------
/Final-Exam-Preparation-1/NeedForSpeed_03.java:
--------------------------------------------------------------------------------
1 | package ExamPreparation1;
2 |
3 | import java.util.*;
4 |
5 | public class NeedForSpeed_03 {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 |
9 | //запис: кола -> {км, гориво}
10 | Map> carsMap = new LinkedHashMap<>();
11 |
12 | int countCars = Integer.parseInt(scanner.nextLine());
13 | for (int car = 1; car <= countCars; car++) {
14 | String [] data = scanner.nextLine().split("\\|");
15 | //"Skoda|12000|34".split("|")
16 | //data = ["Skoda", "13", "34"]
17 | String carModel = data[0]; //модел на колата
18 | int mileage = Integer.parseInt(data[1]); //изминати км
19 | int fuel = Integer.parseInt(data[2]); //налично гориво
20 |
21 | carsMap.putIfAbsent(carModel, new ArrayList<>());
22 | carsMap.get(carModel).add(0, mileage);
23 | carsMap.get(carModel).add(1, fuel);
24 | }
25 |
26 |
27 | String input = scanner.nextLine();
28 |
29 | while (!input.equals("Stop")) {
30 | if (input.contains("Drive")) {
31 | //ШОФИРАНЕ
32 | //input = "Drive : {car} : {distance} : {fuel}".split(" : ") -> ["Drive", "AudiA6", "230" , "6"]
33 | String car = input.split(" : ")[1]; //коя кола искаме да караме
34 | int distance = Integer.parseInt(input.split(" : ")[2]); //колко км искаме да я караме
35 | int consumedFuel = Integer.parseInt(input.split(" : ")[3]); //колко гориво ще изразходим
36 |
37 | //1. имаме достатъчно гориво за каране
38 | int currentFuel = carsMap.get(car).get(1); //текущо количество на гориво в колата
39 | int currentKm = carsMap.get(car).get(0); //текущи км на колата
40 |
41 | if (currentFuel >= consumedFuel) {
42 | //отиваме на пътешествие
43 | carsMap.get(car).set(1, currentFuel - consumedFuel);
44 | carsMap.get(car).set(0, currentKm + distance);
45 | System.out.printf("%s driven for %d kilometers. %d liters of fuel consumed.%n", car, distance, consumedFuel);
46 | } else {
47 | //нямаме достатъчно количество за каране currentFuel < consumedFuel
48 | System.out.println("Not enough fuel to make that ride");
49 | }
50 |
51 | //проверка дали я премахваме
52 | if (carsMap.get(car).get(0) >= 100000) {
53 | //колата е стара -> продаваме
54 | System.out.println("Time to sell the " + car + "!");
55 | carsMap.remove(car);
56 | }
57 |
58 | } else if (input.contains("Refuel")) {
59 | //ЗАРЕЖДАНЕ
60 | //input = "Refuel : AudiA6 : 35".split(" : ") -> ["Refuel", "AudiA6", "35"]
61 | String carToRefill = input.split(" : ")[1]; //кола за зареждане
62 | int fuelToRefill = Integer.parseInt(input.split(" : ")[2]); //колко литра зареждаме
63 |
64 | int currentFuel = carsMap.get(carToRefill).get(1);//текущо количество гориво
65 | if (currentFuel + fuelToRefill > 75) {
66 | //max = 75 и го слагаме в колата
67 | carsMap.get(carToRefill).set(1, 75);
68 | System.out.printf("%s refueled with %d liters%n", carToRefill, 75 - currentFuel);
69 | } else {
70 | //не достигаме 75 литра
71 | carsMap.get(carToRefill).set(1, currentFuel + fuelToRefill);
72 | System.out.printf("%s refueled with %d liters%n", carToRefill, fuelToRefill);
73 | }
74 | } else if (input.contains("Revert")) {
75 | //ВРЪЩАМЕ КИЛОМЕТРАЖА
76 | //input = "Revert : Audi A6 : 120000".split(" : ") -> ["Revert", "Audi A6", "120000"]
77 | String carToRevert = input.split(" : ")[1]; //кола, която ще модифицираме
78 | int kmRevert = Integer.parseInt(input.split(" : ")[2]); //км за модификация
79 | int currentKm = carsMap.get(carToRevert).get(0); //текущи км на колата
80 |
81 | int kmAfterRevert = currentKm - kmRevert; //км след връщането
82 |
83 | if (kmAfterRevert < 10000) {
84 | kmAfterRevert = 10000;
85 | } else {
86 | System.out.printf("%s mileage decreased by %d kilometers%n", carToRevert, kmRevert);
87 | }
88 |
89 | carsMap.get(carToRevert).set(0, kmAfterRevert);
90 |
91 |
92 | }
93 | input = scanner.nextLine();
94 | }
95 |
96 | //entry
97 | //key: кола
98 | //value: {км, гориво}
99 | carsMap.entrySet().forEach(entry -> {
100 | System.out.printf("%s -> Mileage: %d kms, Fuel in the tank: %d lt.%n", entry.getKey(), entry.getValue().get(0), entry.getValue().get(1));
101 | });
102 | }
103 | }
104 |
--------------------------------------------------------------------------------