Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Да програмираш значи да описваш алгоритъм с формален език за програмиране. Алгоритми + данни = програми.
- // HelloWorld.java
- // javac HelloWorld.java
- // java HelloWorld
- // javac -d . HelloWorldPackage.java
- // java com.coolcsn.HelloWorldPackage
- // "C:\Program Files (x86)\Java\jdk1.8.0_192\bin\javac" HelloWorld.java
- // "C:\Program Files (x86)\Java\jdk1.8.0_192\bin\java" HelloWorld
- // sout + tab - prints System.out.println; Alt + Enter; Enter brak point, Start Debug, look down on the left step into
- // Ctrl + / - comment out, uncomment
- // ⌥ ⌘ / macOS or Ctrl + Shift + / - Block comments. Comment Uncomment
- // Refactor This using ⌃T (MacOS) or Shift+Ctrl+Alt+T (Windows)
- // Shift + F6 rename
- // Shift + F9 - Debug
- // Shoft + F10 - Rub
- // You can use ⌘N (macOS), or Alt+Insert (Windows/Linux) for the Generate menu and then select Constructor, Getter, Setter or Getter and Setter
- // IntelyJ shortcuts: sout, fori + /t
- package com.coolcsn;
- import java.util.*;
- public class HelloWorld {
- public static final String ANSI_RED_BACKGROUND = "\u001B[41m";
- public static final String ANSI_RESET = "\u001B[0m";
- public static final String ANSI_RED = "\u001B[31m";
- public static final String ANSI_GREEN_BACKGROUND = "\u001B[42m";
- public static void main(String[] args) throws java.io.IOException
- {
- // 1. Hello World
- System.out.println("Hello World!");
- // 2. Primitive types. Strictly typed, static language
- // 2.1. Integer. Default 0
- byte myByte = -128; // 8 bits signed -128 to 127
- short myShort = 23456; // 16 bits signed -2^15 to 2^15 -1
- int myInt = 432423423; // 32 bits signed -2^31 to 2^31 -1
- long myLong = 4321432423L; // 64 bits signed -2^63 to 2^63 -1
- long maxLong = Long.MAX_VALUE;
- System.out.println(maxLong);
- // Literal
- myShort = 034; // octal radix
- System.out.println(myShort);
- // Hex Literal
- myInt = 0xffab;
- System.out.println(myInt);
- // 2.2. Real
- float myFloat = 2.3454324234324F; // 32 bits signed 7 symbols
- double myDouble = 2.3454324234324D; // 64 bits signed 14 symbols
- System.out.println(myFloat);
- System.out.println(myDouble);
- // 1.3 * 10^3
- myDouble = 1.2e-1;
- System.out.println(myDouble);
- // 2.3. Char
- char myChar = 'S';
- System.out.println((int)myChar);
- System.out.println((char)84);
- myChar = '\u0041'; // A
- myChar = '\u004E';
- myChar = '\'';
- System.out.println(myChar);
- System.out.println("\'Stoyancho\\Sharo\' \t 45 & | ");
- // 2.4. String
- String myString = "Stoyan"; // null
- // 2.5. Bool
- boolean myBool = true; //
- // 2.6. Object
- Object myObject = 5;
- Object obj = 5;
- // obj = "Stoyancho";
- System.out.println(obj);
- // Object n = 4;
- // System.out.println(obj + n);
- System.out.println("Hello World IDE");
- System.out.println( 2 + 2);
- // 3. Operators
- // 3.1 Arithmetics
- int n = 25;
- int m = 32;
- System.out.println(m + n); //57
- System.out.println(m - n); // 7
- System.out.println(m * n); // 800
- System.out.println(m / n); // 1
- System.out.println((double)m / n); // 1.28
- System.out.println(m % n); // 7
- // System.out.println(m++ + n); // 57
- System.out.println(++m + n); // 58
- // System.out.println(m-- + n); // 58
- System.out.println(--m + n); // 57
- // 3.2. Comparison
- System.out.println(m > n); // true
- System.out.println(m < n); // false
- System.out.println(m <= n); // false
- System.out.println(m >= n); // true
- System.out.println(m != n); // true
- System.out.println(m == n); // false
- // 3.3. Logical
- boolean x = true;
- boolean y = false;
- System.out.println(x && y); // false
- // | x | y | && | || | !X | X^Y |
- // | true | true | true | true | false | false |
- // | true | false | false | true | false | true |
- // | false | true | false | true | true | true |
- // | false | false | false | flase| true | flase |
- System.out.println(x || y); // true
- System.out.println(!x); // fasle
- System.out.println(x ^ y); // true
- byte m1 = 3; //
- byte n1 = 2;
- System.out.println(m1 & n1); // 2
- System.out.println(m1 | n1); // 3
- System.out.println(~n1); // -1
- System.out.println(n1 << 1); // 4
- System.out.println(n1 >> 1); // 1
- System.out.println(n1 >>> 1); // 1
- // 3.4. Asignment
- m1 = 4;
- m1 += 3; // m1 = m1 + 3;
- int t = 4;
- t += 5; // t = t + 5;
- t *= 2; // t = t * 2;
- // =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=, >>>=
- System.out.println(myString + myByte);
- System.out.println("Bojidare " + "Dineva " + 1);
- System.out.println((n1 > m1)? "Stoyan" : "Bojidara" );
- // Oreder of operations change with ()
- System.out.println(((n1 + m1) * (n1 - m1++)) + --m1 / ( 5 + 2));
- System.out.println(obj.toString());
- // 4. Console
- // %[argument_index$][flags][width][.precision]conversion
- // argument_index - целочислен тип показващ позицията на аргумента от "аргументния списък".
- // Първият аргумент се индикира с "1$", втория с "2$" и т.н.
- // flags - поредица от символи които модифицират изходния формат.
- // (Примерни ефекти са, показването на числото да бъде винаги със знак, слагането
- // на скоби на отрицателните числа и т.н.) - Резултатът ще бъде ляво ориентиран;
- // + Резултатът винаги ще включва знак (+, -); 0 Резултатът ще се отмести с нули;
- // ( Резултатът ще затвори в скоби отрицателните числа
- // width - неотрицателен целочислен тип показващ минималния брой символи, които трябва да се отпечатат.
- // precision - неотрицателен целочислен тип ограничаващ броя на показваните символи.
- // Този атрибут си променя поведението според conversion спецификатора. В случай на float определя броя цифри след запетаята.
- // b, o, x, c, s, S, f, e, h, n
- System.out.print("Enter your name: ");
- System.out.print("Stoyan \n");
- String str = "Teodora";
- String str1 = "Jivko";
- System.out.printf("My name is %2$S and my name is %1$s . And I am a student! \n", str, str1);
- System.out.printf("%s \n", myInt);
- System.out.printf("%12d \n", myInt);
- System.out.printf("%12x \n", myInt);
- System.out.printf("%12o \n", myInt);
- System.out.printf("%+12.4f \n", -myFloat);
- // java.util.Date date = new java.util.Date();
- Date date = new Date();
- System.out.printf("%tY \n", date);
- System.out.printf("%tm \n", date);
- System.out.printf("%tB \n", date);
- System.out.printf("%tA \n", date);
- // System.out.printf("$tY, $tM \n", date);
- // Date myDate = new Date(2014, 02, 11); // deprecated
- Date myDate1 = new GregorianCalendar(2014, Calendar.FEBRUARY, 11).getTime();
- java.util.Locale.setDefault(new java.util.Locale("bg", "BG"));
- System.out.printf("%tA \n", date);
- System.out.printf("Денят, в който бяхме съсипани: %1$tA %1$tH:%1$tM %1$tB-%1$tY.\n", new java.util.Date());
- // 4.2. System.in
- // Only one character
- // System.out.print("Please enter your name: ");
- // int ch = System.in.read();
- // System.out.println("The first letter of your name has ASCII code: " + ch); // 83 System.out.println((char)ch);
- /* Uncomment to see System.in
- // Old way of reading
- int ch;
- System.out.print("Please enter your name: ");
- while ((ch = System.in.read()) != '\n') {
- System.out.print((char) ch);
- }
- // !!!!!!!!!!! Use this Scanner !!!!!!!!!!!!!!!!!!!!
- Scanner input = new java.util.Scanner(System.in);
- // String
- System.out.print("Please enter your name: ");
- String firstName = input.nextLine();
- // int
- System.out.print("Please enter your Age: ");
- int age = input.nextInt();
- // Double
- System.out.print("Please enter your Balance: ");
- double balance = input.nextDouble();
- input.close();
- // Non formatted output
- System.out.print("Your favorite number is " + (age * balance) + "\n");
- //
- System.out.printf("Your favorite number is %f", (age * balance));
- System.out.println(ANSI_GREEN_BACKGROUND + ANSI_RED + "This text has a green background and red text!" + ANSI_RESET ); // + "\u001B[41m"
- */
- // 5. Conditional logic. Условни конструкции
- // 5.1.
- if (n < m) {
- System.out.print("n < m");
- }
- // 5.2.
- if (n > m ){
- System.out.println("n > m");
- }
- else {
- System.out.println("n < m");
- }
- // 5.3.
- int testscore = 7;
- char grade;
- if (testscore >= 90) {
- grade = 'A';
- } else if (testscore >= 80) {
- grade = 'B';
- } else if (testscore >= 70) {
- grade = 'C';
- } else if (testscore >= 60) {
- grade = 'D';
- } else {
- grade = 'F';
- }
- // switch
- switch (m) {
- case 3:
- case 4 :
- System.out.println("m = 4 || m = 3");
- break;
- case 5 :
- System.out.println("m = 5");
- break;
- default:
- System.out.println("Deafult I couldn't guess!");
- break;
- }
- // 6. Loops Цикли
- // 6.1. While
- int i = 0;
- while (i < n){
- System.out.println(i);
- i++;
- }
- // 6.2.
- Scanner input = new java.util.Scanner(System.in);
- int age = 0;
- do {
- System.out.print("Please, enter your age (0 to 120): ");
- age = input.nextInt();
- } while( age < 0 || age >= 120);
- // 5.3. for
- for ( i = 0; i < 10; i++) {
- System.out.print(i);
- }
- // continue
- System.out.println("------- odd ---------");
- for ( i = 0; i < 10; i++) {
- if (i % 2 == 0) continue;
- System.out.println(i);
- }
- // break
- int prime = 46;
- for ( i = 2; i < prime; i++) {
- if (prime % i == 0 ) {
- System.out.println("The number is NOT prime");
- break;
- }
- // System.out.println(i);
- }
- System.out.println();
- // 5.4. Foreach. Douglas Addams
- int[] myArray = {23, 42, 324, 65, 76};
- for (int j : myArray) {
- System.out.println(j);
- }
- // 7. Arrays. Нареда/индексирана последователност от еднотипни елементи
- // 7.1. Single dimension
- int[] myIntArray = new int[5];
- myIntArray[0] = 0;
- myIntArray[3] = 3;
- for (i = 0; i < myIntArray.length; i++){
- System.out.printf("myIntArray[%1$d] = %2$d \n", i, myIntArray[i]);
- }
- String[] students = {"Iliya", "Jivko", "Nasko", "Teodora"};
- // 7.2. Multi dimension
- int[][] twoDimentionalArray;
- int[][][] threeDimentionalArray;
- int[][] matrix = {
- {1, 2, 3, 4}, // row 0 values
- {5, 6, 7, 8}, // row 1 values
- };
- // The matrix size is 2 x 4 (2 rows, 4 cols)
- for (int row = 0; row < matrix.length; row++) {
- for (int col = 0; col < matrix[0].length; col++) {
- System.out.printf("matrix[%1$d][%2$d] = %3$d \n", row, col, matrix[row][col]);
- }
- System.out.println();
- }
- int[][] matrixDefined = new int[2][3];
- String[] myStringArray = new String[5];
- for (i = 0; i < myStringArray.length; i++){
- System.out.println(myStringArray[i]);
- }
- boolean[] myBoolArray = new boolean[5];
- for (i = 0; i < myBoolArray.length; i++){
- System.out.println(myBoolArray[i]);
- }
- // 8. Numbering Systems
- // 8.1. Pozicionna Nepozicionna broyni systemi
- // VI
- // 44
- // IV VI X XI XII
- // 10 01
- // base radix основа
- // 0-9 основате се определя от броя на цифрите
- // 8.2. Opredelqne stoynostta/tegloto na chisloto
- // 234
- // 2*10^2 + 3*10^1 + 4*10^0 = 2*100 + 3*10 + 4*1 = 200 + 30 + 4 = 234
- // 44(10)
- // 4*10^1 + 4*10^0 = 4*10 + 4*1 = 44
- // 44(8)
- // 4*8^1 + 4*8^0 = 32 + 4 = 36
- // 44(16)
- // 4*16^1 + ...
- // 8.3. Preobrazuwane ot edna w druga broyni sistemi
- // 8.3.1. desetichna kxm dwoichna
- // from binary to decimal
- // 10101010
- // 1*2^7 + 0*2^6 + 1*2^5 + 0*2^4 + 1*2^3 + 0*2^2 + 1*2^1 + 0*2^0 = 128 + 32 + 8 + 2 = 170
- // 23(10) =>
- // 23 : 2 = 11 | 1
- // 11 : 2 = 5 | 1
- // 5 : 2 = 2 | 1
- // 2 : 2 = 1 | 0
- // 1
- // 10111(2) = 23(10)
- // 1*2^4 + 1
- // from decimal to binary
- // 170 / 2 = 85 0
- // 85 / 2 = 42 1
- // 42 / 2 = 21 0
- // 21 / 2 = 10 1
- // 10 / 2 = 5 0
- // 5 / 2 = 2 1
- // 2 / 2 = 1 0
- // 1
- // 10101010
- // 8.3.2. dwoichna w shestnadeseticha i osmichna 8421
- // 0011 1010 1010 1111 0101 0101
- // 3 A A F 5 5
- // 001 110 101 010 111 101 010 101
- // 1 6 5 2 7 5 2 5
- // 8.3.3. floating point
- // 23.45 = 10111.0101001 => 1.01110101001 4
- // 23 : 2 = 11 | 1
- // 11 : 2 = 5 | 1
- // 5 : 2 = 2 | 1
- // 2 : 2 = 1 | 0
- 1
- // .45 * 2 = 0.90 | 0
- // 0.9 * 2 = 0.8 | 1
- //8.4. Praw obraten dopxlnitelen kod
- //8.4.1. desetichna broyna sistema
- //3 + 4 = 7
- //
- // 7 - 3 = 4
- //
- //
- // 34
- //
- //obraten kod => (10^2 - 1) - 34 = 99 - 34 = 65
- // 34
- //dopxlnitelen (10^2 ) - 34 = 66 = 65 + 1
- //
- //
- // 99
- // -
- // 34
- // ----------------
- // 65
- //
- // 9999999999999999
- // -
- // 4343742364523476
- // -----------------------
- // 565...
- //
- // 999
- // -
- // 456
- // ---------
- // 543 - obraten => dopxlnitelen 544
- //
- // 7 - 3 = 4
- //
- // 7 + 7 = 1 | 4
- //
- // 3 - 7 = -4
- //
- // 3 + 3 = 6 => -4
- //
- // 8.4.2. dwoichna broyna sistema
- //1111111111111
- // -
- // 1010101111111
- // -----------------
- // 0101010000000 => 0101010000001
- // 9. Methods
- greet(); // greet("Stoyan");
- int[] ages = new int[3];
- // inputArray(ages);
- /*
- Scanner input1 = new java.util.Scanner(System.in);
- for (i = 0; i < ages.length; i++) {
- System.out.printf("Please enter the value of element : %d", i);
- ages[i] = input.nextInt();
- }
- */
- int[] fNumbers = new int[4];
- // inputArray(fNumbers);
- /*
- Scanner fNUmbers = new java.util.Scanner(System.in);
- for (i = 0; i < fNumbers.length; i++) {
- System.out.printf("Please enter the value of element : %d", i);
- fNumbers[i] = input.nextInt();
- }
- */
- /*
- for (i = 0; i < 10; i++) {
- System.out.println(i);
- }
- for (i = 20; i <=30; i++) {
- System.out.println(i);
- }
- */
- printInterval(0, 10);
- printInterval(20, 30);
- System.out.println(calculateInterest(35.0));
- printMenu();
- // 9.1. Java doesn't have default values for the formal parameters. Use overloading instead
- // Java does not support default arguments in the same way that languages like C++ or Python do. However, you can achieve similar behavior in Java using method overloading.
- // 9.2. Variable number of parameters
- welcomePerson("Stoyan", "Ivan", "Petko");
- // 10. Recursion
- // 0! = 1;
- // n! = (n-1)!*n
- // 3! = 1*2*3 = 6
- int mul = 1;
- for (i = 1; i <= 4; i++) {
- mul *= i;
- }
- System.out.println("Factorial = " + mul);
- System.out.println(calculateFactorIterations(4));
- System.out.println(calculateFactorialRecursion(4));
- // 11. Data Structures
- //slow on add and remove fast on access indexes/elements
- java.util.ArrayList<Integer> myArrayList = new java.util.ArrayList<Integer>();
- myArrayList.add(10);
- myArrayList.get(0);
- System.out.println(myArrayList.get(0));
- // fast on add and remove slow on access indexes
- java.util.LinkedList<Integer> myLinkedList = new java.util.LinkedList<Integer>();
- myLinkedList.add(5);
- myLinkedList.get(0);
- String text = "Stoyan";
- Map<String, Integer> words = new TreeMap<String, Integer>();
- Scanner textScanner = new Scanner(text);
- while (textScanner.hasNext()) {
- String word = textScanner.next();
- Integer count = words.get(word);
- if (count == null) {
- count = 0;
- }
- words.put(word, count + 1);
- }
- for (Map.Entry<String, Integer> wordEntry
- : words.entrySet()) {
- System.out.printf(
- "word '%s' is seen %d times in the text%n",
- wordEntry.getKey(), wordEntry.getValue());
- }
- }
- // Recursion
- public static int calculateFactorialRecursion(int number) {
- if (number == 0) return 1;
- return calculateFactorialRecursion(number -1) * number;
- }
- public static int calculateFactorIterations(int number) {
- int mul = 1;
- for (int i = 1; i <= number; i++) {
- mul *= i;
- }
- return mul;
- }
- static void greet(String name){ // static void greet()
- System.out.println("Hello " + name);
- }
- public static void inputArray(int[] myArray) {
- Scanner input = new java.util.Scanner(System.in);
- for (int i = 0; i < myArray.length; i++) {
- System.out.printf("Please enter the value of element : %d : ", i);
- myArray[i] = input.nextInt();
- }
- }
- public static void printInterval(int from, int to){
- for (int i = from; i <=to; i++) {
- System.out.println(i);
- }
- }
- public static double calculateInterest(double amount) {
- double interest = (1/4.0) * amount;
- return interest;
- }
- public static double calculateCompoundInterest(double amount, double interest, int period) {
- double totalAmount = amount * Math.pow((1 + interest/100), period);
- return totalAmount;
- }
- public static void printMenu()
- {
- System.out.println("File");
- System.out.println("Edit");
- }
- public static boolean isPrime(int prime) {
- for (int i = 2; i < prime; i++) {
- if (prime % i == 0 ) {
- return false; // System.out.println("The number is NOT prime");
- // break;
- }
- }
- return true;
- }
- public static int inputNumber(int min, int max) { // String question, String question,
- int age = 0;
- Scanner input = new java.util.Scanner(System.in);
- do {
- // System.out.print("Please, enter a number between (5 to 25): ");
- System.out.printf("Please, enter a number between (%1$s to %2$s): ", min, max );
- age = input.nextInt();
- } while( age < min || age >= max);
- return age;
- }
- public static void welcomePerson(String ... people) {
- for (String person : people) {
- System.out.println("Welcome " + person);
- }
- }
- }
- // OOP
- // 1. История 1967 Алан Кай
- // 2. Класове и обекти
- // 3. Елементи на класа
- // 4. Статични елементи на класа
- // 5. Inheritance - Вьзможността да се преизползват дефинираните елементите на друг клас
- // 6. Abstraction - Вьзможността обект от даден клас да се третира като обект от родителски клас или интерфейс
- // 7. Encapsulation - Вьзможността да се скриват/енкапсулират вътрешните елементи на обектите от даден клас и да се излагат само важните за потребиеля. Обикновено това са методите от интерфейсите
- // 8. Polymorphism - Вьзможността обектите да запазват специфичната си функционалност (методи) и да се проявяват полиморфно, въпреки прилагането на абстракция.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement