wingman007

Java2018IntroCheatSheet

Oct 21st, 2018 (edited)
1,320
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 24.81 KB | None | 0 0
  1. // Да програмираш значи да описваш алгоритъм с формален език за програмиране. Алгоритми + данни = програми.
  2. // HelloWorld.java
  3. // javac HelloWorld.java
  4. // java HelloWorld
  5. // javac -d . HelloWorldPackage.java
  6. // java com.coolcsn.HelloWorldPackage
  7. // "C:\Program Files (x86)\Java\jdk1.8.0_192\bin\javac" HelloWorld.java
  8. // "C:\Program Files (x86)\Java\jdk1.8.0_192\bin\java" HelloWorld
  9. // sout + tab - prints System.out.println; Alt + Enter; Enter brak point, Start Debug, look down on the left step into
  10. // Ctrl + / - comment out, uncomment
  11. // ⌥ ⌘ / macOS or Ctrl + Shift + / - Block comments. Comment Uncomment
  12. // Refactor This using ⌃T (MacOS) or Shift+Ctrl+Alt+T (Windows)
  13. // Shift + F6 rename
  14. // Shift + F9 - Debug
  15. // Shoft + F10 - Rub
  16. // You can use ⌘N (macOS), or Alt+Insert (Windows/Linux) for the Generate menu and then select Constructor, Getter, Setter or Getter and Setter
  17. // File > Settings (или Ctrl + Alt + S)
  18.  
  19. // IntelyJ shortcuts: sout, fori + /t
  20. // HSift + F9 - debug, F8 - step
  21. //TIP To <b>Run</b> code, press <shortcut actionId="Run"/> Shift+F10 or
  22. // click the Alt + Enter <icon src="AllIcons.Actions.Execute"/> icon in the gutter.
  23. // public class Main {
  24. //    public static void main(String[] args) {
  25.         //TIP Press <shortcut actionId="ShowIntentionActions"/> with your caret at the highlighted text
  26.         // to see how IntelliJ IDEA suggests fixing it.
  27. //        System.out.printf("Hello and welcome!");
  28.  
  29. //        for (int i = 1; i <= 5; i++) {
  30.             //TIP Press <shortcut actionId="Debug"/> Shift + F9 to start debugging your code. We have set one <icon // src="AllIcons.Debugger.Db_set_breakpoint"/> breakpoint
  31.             // for you, but you can always add more by pressing <shortcut actionId="ToggleLineBreakpoint"/>.
  32. //            System.out.println("i = " + i);
  33. //        }
  34. //    }
  35. // }
  36.  
  37.  
  38. package com.coolcsn;
  39. import java.util.*;
  40.  
  41. public class HelloWorld {
  42.  
  43.  
  44.     public static final String ANSI_RED_BACKGROUND = "\u001B[41m";
  45.     public static final String ANSI_RESET = "\u001B[0m";
  46.     public static final String ANSI_RED = "\u001B[31m";
  47.     public static final String ANSI_GREEN_BACKGROUND = "\u001B[42m";
  48.  
  49.  
  50.     public static void main(String[] args) throws java.io.IOException
  51.     {
  52.          // 1. Hello World
  53.          System.out.println("Hello World!");
  54.  
  55.         // 2. Primitive types. Strictly typed, static language
  56.         // 2.1. Integer. Default 0
  57.         byte myByte = -128; // 8 bits signed -128 to 127
  58.         short myShort = 23456; // 16 bits signed -2^15 to 2^15 -1
  59.         int myInt = 432423423; // 32 bits signed -2^31 to 2^31 -1
  60.         long myLong = 4321432423L; // 64 bits signed -2^63 to 2^63 -1
  61.         long maxLong = Long.MAX_VALUE;
  62.         System.out.println(maxLong);
  63.  
  64.  
  65.         // Literal
  66.         myShort = 034; // octal radix
  67.         System.out.println(myShort);
  68.  
  69.         // Hex Literal
  70.         myInt = 0xffab;
  71.         System.out.println(myInt);
  72.  
  73.  
  74.         // 2.2. Real
  75.         float myFloat = 2.3454324234324F; // 32 bits signed  7 symbols
  76.         double myDouble = 2.3454324234324D; // 64 bits signed 14 symbols
  77.  
  78.         System.out.println(myFloat);
  79.         System.out.println(myDouble);
  80.  
  81.         // 1.3 * 10^3
  82.         myDouble = 1.2e-1;
  83.         System.out.println(myDouble);
  84.  
  85.         // 2.3. Char
  86.         char myChar = 'S';
  87.  
  88.  
  89.         System.out.println((int)myChar);
  90.         System.out.println((char)84);
  91.  
  92.         myChar = '\u0041'; // A
  93.         myChar = '\u004E';
  94.         myChar = '\'';
  95.         System.out.println(myChar);
  96.  
  97.         System.out.println("\'Stoyancho\\Sharo\' \t 45 & | ");
  98.  
  99.         // 2.4.  String
  100.         String myString = "Stoyan"; // null
  101.  
  102.         // 2.5. Bool
  103.         boolean myBool = true; //
  104.  
  105.         // 2.6. Object
  106.         Object myObject = 5;
  107.  
  108.         Object obj = 5;
  109.         // obj = "Stoyancho";
  110.         System.out.println(obj);
  111.  
  112.         // Object n = 4;
  113.  
  114.         // System.out.println(obj + n);
  115.  
  116.         System.out.println("Hello World IDE");
  117.         System.out.println( 2 + 2);
  118.  
  119.         // 3. Operators
  120.         // 3.1 Arithmetics
  121.         int n = 25;
  122.         int m = 32;
  123.  
  124.         System.out.println(m + n); //57
  125.         System.out.println(m - n); // 7
  126.         System.out.println(m * n); // 800
  127.         System.out.println(m / n); // 1
  128.         System.out.println((double)m / n); // 1.28
  129.         System.out.println(m % n); // 7
  130.         // System.out.println(m++ + n); // 57
  131.         System.out.println(++m + n); // 58
  132.         // System.out.println(m-- + n); // 58
  133.         System.out.println(--m + n); // 57
  134.  
  135.  
  136.         // 3.2. Comparison
  137.         System.out.println(m > n); // true
  138.         System.out.println(m < n); // false
  139.         System.out.println(m <= n); // false
  140.         System.out.println(m >= n); // true
  141.         System.out.println(m != n); // true
  142.         System.out.println(m == n); // false
  143.  
  144.         // 3.3. Logical
  145.         boolean x = true;
  146.         boolean y = false;
  147.         System.out.println(x && y); // false
  148.         // | x     | y     | &&    | ||   | !X     |  X^Y  |
  149.         // | true  | true  | true  | true |  false | false |
  150.         // | true  | false | false | true |  false | true  |
  151.         // | false | true  | false | true |  true  | true  |
  152.         // | false | false | false | flase|  true  | flase |
  153.         System.out.println(x || y); // true
  154.         System.out.println(!x); // fasle
  155.         System.out.println(x ^ y); // true
  156.  
  157.         byte m1 = 3; //
  158.         byte n1 = 2;
  159.         System.out.println(m1 & n1); // 2
  160.         System.out.println(m1 | n1); // 3
  161.         System.out.println(~n1); // -1 Операторът ~ в Java е побитов оператор за отрицание (bitwise NOT) int n1 = 0; System.out.println(~n1); // -1 00000000 00000000 00000000 00000000  (това е 0) ~n1 обръща всеки бит: 11111111 11111111 11111111 11111111  (в Java това е -1 в 2's complement)
  162.         System.out.println(n1 << 1); // 4
  163.         System.out.println(n1 >> 1); // 1
  164.         System.out.println(n1 >>> 1); // 1
  165.  
  166.         // 3.4. Asignment
  167.         m1 = 4;
  168.         m1 += 3; // m1 = m1 + 3;
  169.  
  170.         int t = 4;
  171.         t += 5; // t = t + 5;
  172.         t *= 2; // t = t * 2;
  173.         // =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=, >>>=
  174.  
  175.         System.out.println(myString + myByte);
  176.  
  177.         System.out.println("Bojidare " + "Dineva " + 1);
  178.  
  179.         System.out.println((n1 > m1)? "Stoyan" : "Bojidara" );
  180.  
  181.         // Oreder of operations change with ()
  182.         System.out.println(((n1 + m1) * (n1 - m1++)) + --m1 / ( 5 + 2));
  183.  
  184.         System.out.println(obj.toString());
  185.  
  186.         // 4. Console
  187.         // %[argument_index$][flags][width][.precision]conversion
  188.         // argument_index - целочислен тип показващ позицията на аргумента от "аргументния списък".
  189.         // Първият аргумент се индикира с "1$", втория с "2$" и т.н.
  190.         // flags - поредица от символи които модифицират изходния формат.
  191.         // (Примерни ефекти са, показването на числото да бъде винаги със знак, слагането
  192.         // на скоби на отрицателните числа и т.н.) - Резултатът ще бъде ляво ориентиран;
  193.         // + Резултатът винаги ще включва знак (+, -); 0 Резултатът ще се отмести с нули;
  194.         // ( Резултатът ще затвори в скоби отрицателните числа
  195.         // width - неотрицателен целочислен тип показващ минималния брой символи, които трябва да се отпечатат.
  196.         // precision - неотрицателен целочислен тип ограничаващ броя на показваните символи.
  197.         // Този атрибут си променя поведението според conversion спецификатора. В случай на float определя броя цифри след запетаята.
  198.         // b, o, x, c, s, S, f, e, h, n
  199.         System.out.print("Enter your name: ");
  200.         System.out.print("Stoyan \n");
  201.  
  202.         String str = "Teodora";
  203.         String str1 = "Jivko";
  204.         System.out.printf("My name is %2$S and my name is %1$s . And I am a student! \n", str, str1);
  205.  
  206.         System.out.printf("%s \n", myInt);
  207.         System.out.printf("%12d \n", myInt);
  208.         System.out.printf("%12x \n", myInt);
  209.         System.out.printf("%12o \n", myInt);
  210.         System.out.printf("%+12.4f \n", -myFloat);
  211.  
  212.         // java.util.Date date = new java.util.Date();
  213.         Date date = new Date();
  214.         System.out.printf("%tY \n", date);
  215.         System.out.printf("%tm \n", date);
  216.         System.out.printf("%tB \n", date);
  217.         System.out.printf("%tA \n", date);
  218.         // System.out.printf("$tY, $tM \n", date);
  219.  
  220.         // Date myDate = new Date(2014, 02, 11); // deprecated
  221.         Date myDate1 = new GregorianCalendar(2014, Calendar.FEBRUARY, 11).getTime();
  222.  
  223.         java.util.Locale.setDefault(new java.util.Locale("bg", "BG"));
  224.         System.out.printf("%tA \n", date);
  225.         System.out.printf("Денят, в който бяхме съсипани: %1$tA %1$tH:%1$tM %1$tB-%1$tY.\n", new java.util.Date());
  226.  
  227.         // 4.2. System.in
  228.  
  229.         // Only one character
  230.         // System.out.print("Please enter your name: ");
  231.         // int ch = System.in.read();
  232.         // System.out.println("The first letter of your name has ASCII code: " + ch); // 83 System.out.println((char)ch);
  233.  
  234.         /* Uncomment to see System.in
  235.         // Old way of reading
  236.         int ch;
  237.         System.out.print("Please enter your name: ");
  238.         while ((ch = System.in.read()) != '\n') {
  239.              System.out.print((char) ch);
  240.         }
  241.  
  242.  
  243.         // !!!!!!!!!!! Use this Scanner !!!!!!!!!!!!!!!!!!!!
  244.         Scanner input = new java.util.Scanner(System.in);
  245.         // String
  246.         System.out.print("Please enter your name: ");
  247.         String firstName = input.nextLine();
  248.         // int
  249.         System.out.print("Please enter your Age: ");
  250.         int age = input.nextInt();
  251.         // Double
  252.         System.out.print("Please enter your Balance: ");
  253.         double balance = input.nextDouble();
  254.  
  255.         input.close();
  256.  
  257.         // Non formatted output
  258.         System.out.print("Your favorite number is " + (age * balance) + "\n");
  259.  
  260.         //
  261.         System.out.printf("Your favorite number is %f", (age * balance));
  262.  
  263.         System.out.println(ANSI_GREEN_BACKGROUND + ANSI_RED + "This text has a green background and red text!" + ANSI_RESET ); // + "\u001B[41m"
  264.         */
  265.  
  266.         // 5. Conditional logic. Условни конструкции
  267.         // 5.1.
  268.         if (n < m) {
  269.             System.out.print("n < m");
  270.         }
  271.  
  272.         // 5.2.
  273.         if (n > m ){
  274.             System.out.println("n > m");
  275.         }
  276.         else {
  277.             System.out.println("n < m");
  278.         }
  279.  
  280.  
  281.         // 5.3.
  282.         int testscore = 7;
  283.         char grade;
  284.  
  285.         if (testscore >= 90) {
  286.             grade = 'A';
  287.         } else if (testscore >= 80) {
  288.             grade = 'B';
  289.         } else if (testscore >= 70) {
  290.             grade = 'C';
  291.         } else if (testscore >= 60) {
  292.             grade = 'D';
  293.         } else {
  294.             grade = 'F';
  295.         }
  296.  
  297.         // switch
  298.         switch (m) {
  299.             case 3:
  300.             case 4 :
  301.                 System.out.println("m = 4 || m = 3");
  302.                 break;
  303.             case 5 :
  304.                 System.out.println("m = 5");
  305.                 break;
  306.             default:
  307.                 System.out.println("Deafult I couldn't guess!");
  308.                 break;
  309.         }
  310.  
  311.         // 6. Loops Цикли
  312.         // 6.1. While
  313.         int i = 0;
  314.         while (i < n){
  315.             System.out.println(i);
  316.             i++;
  317.         }
  318.  
  319.         // 6.2.
  320.         Scanner input = new java.util.Scanner(System.in);
  321.         int age = 0;
  322.         do {
  323.             System.out.print("Please, enter your age (0 to 120): ");
  324.             age = input.nextInt();
  325.         } while( age < 0 || age >= 120);
  326.  
  327.         // 5.3. for
  328.         for ( i = 0; i < 10; i++) {
  329.             System.out.print(i);
  330.         }
  331.  
  332.         // continue
  333.         System.out.println("------- odd ---------");
  334.         for ( i = 0; i < 10; i++) {
  335.             if (i % 2 == 0) continue;
  336.             System.out.println(i);
  337.         }
  338.  
  339.  
  340.         // break
  341.         int prime = 46;
  342.  
  343.         for ( i = 2; i < prime; i++) {
  344.             if (prime % i == 0 ) {
  345.                 System.out.println("The number is NOT prime");
  346.                 break;
  347.             }
  348.             // System.out.println(i);
  349.         }
  350.  
  351.         System.out.println();
  352.         // 5.4. Foreach. Douglas Addams
  353.         int[] myArray = {23, 42, 324, 65, 76};
  354.         for (int j : myArray) {
  355.             System.out.println(j);
  356.         }
  357.  
  358.         // 7. Arrays. Нареда/индексирана последователност от еднотипни елементи
  359.         // 7.1. Single dimension
  360.         int[] myIntArray = new int[5];
  361.         myIntArray[0] = 0;
  362.         myIntArray[3] = 3;
  363.  
  364.         for (i = 0; i < myIntArray.length; i++){
  365.             System.out.printf("myIntArray[%1$d] = %2$d \n", i, myIntArray[i]);
  366.         }
  367.  
  368.         String[] students = {"Iliya", "Jivko", "Nasko", "Teodora"};
  369.  
  370.         // 7.2. Multi dimension
  371.         int[][] twoDimentionalArray;
  372.         int[][][] threeDimentionalArray;
  373.  
  374.         int[][] matrix = {
  375.                 {1, 2, 3, 4}, // row 0 values
  376.                 {5, 6, 7, 8}, // row 1 values
  377.         };
  378.         // The matrix size is 2 x 4 (2 rows, 4 cols)
  379.  
  380.         for (int row = 0; row < matrix.length; row++) {
  381.             for (int col = 0; col < matrix[0].length; col++) {
  382.                 System.out.printf("matrix[%1$d][%2$d] = %3$d \n", row, col, matrix[row][col]);
  383.             }
  384.             System.out.println();
  385.         }
  386.  
  387.         int[][] matrixDefined = new int[2][3];
  388.  
  389.         String[] myStringArray = new String[5];
  390.         for (i = 0; i < myStringArray.length; i++){
  391.             System.out.println(myStringArray[i]);
  392.         }
  393.  
  394.         boolean[] myBoolArray = new boolean[5];
  395.         for (i = 0; i < myBoolArray.length; i++){
  396.             System.out.println(myBoolArray[i]);
  397.         }
  398.  
  399.         // 8. Numbering Systems
  400.         // 8.1. Pozicionna Nepozicionna broyni systemi
  401.         //  VI
  402.         //  44 
  403.         // IV VI X XI XII
  404.         // 10 01
  405.         // base radix основа
  406.         // 0-9 основате се определя от броя на цифрите
  407.         // 8.2. Opredelqne stoynostta/tegloto na chisloto
  408.         // 234
  409.         // 2*10^2 + 3*10^1 + 4*10^0 = 2*100 + 3*10 + 4*1 = 200 + 30 + 4 = 234
  410.  
  411.         // 44(10)
  412.         // 4*10^1 + 4*10^0 = 4*10 + 4*1 = 44
  413.  
  414.         // 44(8)
  415.         // 4*8^1 + 4*8^0 = 32 + 4 = 36
  416.  
  417.         // 44(16)
  418.         // 4*16^1 + ...
  419.  
  420.         // 8.3. Preobrazuwane ot edna w druga broyni sistemi
  421.         // 8.3.1. desetichna kxm dwoichna
  422.         // from binary to decimal
  423.         // 10101010
  424.         // 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
  425.  
  426.         // 23(10) =>
  427.         // 23 : 2 = 11 | 1
  428.         // 11 : 2 = 5 | 1
  429.         // 5 : 2 = 2 | 1
  430.         // 2 : 2 = 1 | 0
  431.         //         1
  432.         // 10111(2) = 23(10)
  433.         // 1*2^4 + 1
  434.  
  435.         // from decimal to binary
  436.         // 170 / 2 = 85  0
  437.         // 85 / 2 = 42  1
  438.         // 42 / 2 = 21 0
  439.         // 21 / 2 = 10 1
  440.         // 10 / 2 = 5 0
  441.         // 5 / 2 = 2  1
  442.         // 2 / 2 = 1 0
  443.         //           1
  444.         // 10101010
  445.  
  446.         // 8.3.2. dwoichna w shestnadeseticha i osmichna 8421
  447.         // 0011 1010 1010 1111 0101 0101
  448.         // 3    A     A    F    5    5
  449.  
  450.         // 001 110 101 010 111 101 010 101
  451.         // 1    6   5   2   7   5   2   5
  452.  
  453.         // 8.3.3. floating point
  454.         // 23.45 = 10111.0101001 => 1.01110101001      4
  455.  
  456.         // 23 : 2 = 11 | 1
  457.         // 11 : 2 = 5 | 1
  458.         // 5 : 2 = 2 | 1
  459.         // 2 : 2 = 1 | 0
  460.                      1
  461.  
  462.         // .45 * 2 = 0.90 | 0
  463.         // 0.9 * 2 = 0.8 | 1
  464.  
  465. /*
  466. VI
  467. 44(10)
  468. 4*10^1 + 4*10^0 = 4*10 + 4*1 = 44
  469.  
  470. 44(8)
  471. 4*8^1 + 4*8^0 = 32 + 4 = 36
  472.  
  473. 44(16)
  474. 4*16^1 + 4*16^0 = 64 + 4 = 68
  475.  
  476.  
  477.  
  478. 10 : 2 = 5 | 0
  479. 5 : 2 = 2 | 1
  480. 2 : 2 = 1 |0
  481.           | 1
  482.  
  483. 1010(2)
  484.  
  485. 1*2^3 + 0*2^2 + 1 *2^1 + 0*2^0 = 8 + 0 + 2 + 0 = 10
  486.  
  487. 10 : 8 = 1 | 2
  488.            | 1
  489.  
  490. 12(8)
  491.  
  492. 1*8^1 + 2*8^0 = 8 + 2 = 10
  493.  
  494. 241 : 8 = 30 | 1
  495. 30 : 8 = 3 | 6
  496.              3
  497. 361(8) = 241(10)
  498.  
  499.  
  500. 0010 1010 1010 1011 1001 0101 0101 0101 0101(2)
  501. 2     A    A    B    9    5     5   5    5
  502.  
  503.  
  504. 44(10)
  505.  
  506. (10^2 -1) - 44 = 99 - 44 = 55
  507.  
  508. 2345
  509. (10^4 - 1) - 2345 = 9999 - 2345 = 7654- obraten
  510. (10^4) - 2345 = 7655 - dopxlnitelen
  511.  
  512. 9999999999999999999999
  513. -
  514. 6547654123675476452376
  515. ----------------------------
  516. 345....
  517.  
  518. 7 - 4 = 3
  519.  
  520. 7 + 6 = 1 | 3
  521.  
  522. 4 - 7 = -3
  523.  
  524. 4 + 3 = 7 => -3
  525.  
  526. 11111111111111111
  527. -
  528. 10101010101011111
  529. ---------------------
  530. 01010101010100000
  531.  
  532.  
  533. Floating point
  534. 23.45 => 10111.0111 => 1.01110111 * 2^4
  535.  
  536. 23 : 2 = 11 | 1
  537. 11 : 2 = 5 | 1
  538. 5 : 2 = 2 | 1
  539. 2: 2 = 1 | 0
  540.           1
  541.  
  542.  
  543. 0.45 * 2 = 0.9 |0
  544. 0.9 * 2 = 0.8 | 1
  545. 0.8 * 2 = 0.6 | 1
  546. 0.6 * 2 = 0.2 | 1
  547.  
  548. 345.67 => 3.4567 * 10^2
  549.  
  550. 4567.435 => 4.567435 * 10^3
  551.  
  552.  
  553.  
  554. */
  555.  
  556.  
  557.  
  558. //8.4. Praw obraten dopxlnitelen kod
  559. //8.4.1. desetichna broyna sistema
  560. //3 + 4 = 7
  561. //
  562. //        7 - 3 = 4
  563. //
  564. //
  565. //        34
  566. //
  567. //obraten kod => (10^2 - 1) - 34 = 99 - 34 = 65
  568. //        34
  569. //dopxlnitelen (10^2 ) - 34 = 66 = 65 + 1
  570. //
  571. //
  572. //        99
  573. //        -
  574. //        34
  575. //        ----------------
  576. //        65
  577. //
  578. //        9999999999999999
  579. //        -
  580. //        4343742364523476
  581. //        -----------------------
  582. //        565...
  583. //
  584. //        999
  585. //        -
  586. //        456
  587. //        ---------
  588. //        543 - obraten => dopxlnitelen 544
  589. //
  590. //        7 - 3 = 4
  591. //
  592. //        7 + 7 = 1 | 4
  593. //
  594. //        3 - 7 = -4
  595. //
  596. //        3 + 3 = 6 => -4
  597. //
  598. //        8.4.2. dwoichna broyna sistema
  599. //1111111111111
  600. //        -
  601. //        1010101111111
  602. //        -----------------
  603. //        0101010000000 => 0101010000001
  604.  
  605.         // 9. Methods - look down for method definitions
  606.         greet(); // greet("Stoyan");
  607.         int[] ages = new int[3];
  608.         // inputArray(ages);
  609.         /*
  610.         Scanner input1 = new java.util.Scanner(System.in);
  611.         for (i = 0; i < ages.length; i++) {
  612.             System.out.printf("Please enter the value of element : %d", i);
  613.             ages[i] = input.nextInt();
  614.         }
  615.         */
  616.  
  617.  
  618.         int[] fNumbers = new int[4];
  619.         // inputArray(fNumbers);
  620.         /*
  621.         Scanner fNUmbers = new java.util.Scanner(System.in);
  622.         for (i = 0; i < fNumbers.length; i++) {
  623.             System.out.printf("Please enter the value of element : %d", i);
  624.             fNumbers[i] = input.nextInt();
  625.         }
  626.         */
  627.         /*
  628.         for (i = 0; i < 10; i++) {
  629.         System.out.println(i);
  630.         }
  631.  
  632.         for (i = 20; i <=30; i++) {
  633.             System.out.println(i);
  634.         }
  635.         */
  636.  
  637.         printInterval(0, 10);
  638.         printInterval(20, 30);
  639.  
  640.         System.out.println(calculateInterest(35.0));
  641.  
  642.  
  643.         printMenu();
  644.  
  645.         // 9.1. Java doesn't have default values for the formal parameters. Use overloading instead
  646.         // Java does not support default arguments in the same way that languages like C++ or Python do. However, you can achieve  
  647.         // Use method overloading instead:
  648.         // void greet(String name) {
  649.         // System.out.println("Hello, " + name);
  650.         //}
  651.  
  652.         // void greet() {
  653.         //  greet("World"); // Default value
  654.         // }
  655.         // use the overloaded methods like this:
  656.         // greet("Stoyan");  // Output: Hello, Stoyan
  657.         // greet();          // Output: Hello, World
  658.  
  659.         // 9.2. Variable number of parameters
  660.         welcomePerson("Stoyan", "Ivan", "Petko");
  661.  
  662.  
  663.         // 10. Recursion
  664.         // 0! = 1;
  665.         // n! = (n-1)!*n
  666.  
  667.         // 3! = 1*2*3 = 6
  668.  
  669.  
  670.         int mul = 1;
  671.         for (i = 1; i <= 4; i++) {
  672.             mul *= i;
  673.         }
  674.         System.out.println("Factorial = " + mul);
  675.  
  676.         System.out.println(calculateFactorIterations(4));
  677.  
  678.         System.out.println(calculateFactorialRecursion(4));
  679.  
  680.  
  681.         // 11. Data Structures
  682.         //11.1 slow on add and remove fast on access indexes/elements
  683.         java.util.ArrayList<Integer> myArrayList = new java.util.ArrayList<Integer>();
  684.         myArrayList.add(10);
  685.         myArrayList.get(0);
  686.         System.out.println(myArrayList.get(0));
  687.  
  688.         // 11.2. fast on add and remove slow on access indexes
  689.         java.util.LinkedList<Integer> myLinkedList = new java.util.LinkedList<Integer>();
  690.         myLinkedList.add(5);
  691.         myLinkedList.get(0);
  692.  
  693.  
  694.         // 11.3.
  695.         String text = "Stoyan";
  696.         Map<String, Integer> words = new TreeMap<String, Integer>();
  697.         Scanner textScanner = new Scanner(text);
  698.         while (textScanner.hasNext()) {
  699.             String word = textScanner.next();
  700.             Integer count = words.get(word);
  701.             if (count == null) {
  702.                 count = 0;
  703.             }
  704.             words.put(word, count + 1);
  705.         }
  706.  
  707.         for (Map.Entry<String, Integer> wordEntry
  708.                 : words.entrySet()) {
  709.             System.out.printf(
  710.                     "word '%s' is seen %d times in the text%n",
  711.                     wordEntry.getKey(), wordEntry.getValue());
  712.         }
  713.     }
  714.  
  715.     // 10. Recursion
  716.     public static int calculateFactorialRecursion(int number) {
  717.         if (number == 0) return 1;
  718.         return calculateFactorialRecursion(number -1) * number;
  719.     }
  720.  
  721.     public static int calculateFactorIterations(int number) {
  722.         int mul = 1;
  723.         for (int i = 1; i <= number; i++) {
  724.             mul *= i;
  725.         }
  726.         return mul;
  727.     }
  728.  
  729.     static void greet(String name){ // static void greet()
  730.         System.out.println("Hello " + name);
  731.     }
  732.  
  733.     public static void inputArray(int[] myArray) {
  734.         Scanner input = new java.util.Scanner(System.in);
  735.         for (int i = 0; i < myArray.length; i++) {
  736.             System.out.printf("Please enter the value of element : %d : ", i);
  737.             myArray[i] = input.nextInt();
  738.         }
  739.     }
  740.  
  741.     public static void printInterval(int from, int to){
  742.         for (int i = from; i <=to; i++) {
  743.             System.out.println(i);
  744.         }
  745.     }
  746.  
  747.     public static double calculateInterest(double amount) {
  748.         double interest = (1/4.0) * amount;
  749.         return  interest;
  750.     }
  751.  
  752.     public static double calculateCompoundInterest(double amount, double interest, int period) {
  753.         double totalAmount = amount * Math.pow((1 + interest/100), period);
  754.         return  totalAmount;
  755.     }
  756.  
  757.     public static void printMenu()
  758.     {
  759.         System.out.println("File");
  760.         System.out.println("Edit");
  761.     }
  762.  
  763.     public static boolean isPrime(int prime) {
  764.         for (int i = 2; i < prime; i++) {
  765.             if (prime % i == 0 ) {
  766.                 return false; // System.out.println("The number is NOT prime");
  767.                 // break;
  768.             }
  769.         }
  770.         return true;
  771.     }
  772.  
  773.     public static int inputNumber(int min, int max) { // String question, String question,
  774.         int age = 0;
  775.         Scanner input = new java.util.Scanner(System.in);
  776.         do {
  777.             // System.out.print("Please, enter a number between (5 to 25): ");
  778.             System.out.printf("Please, enter a number between (%1$s to %2$s): ", min, max );
  779.             age = input.nextInt();
  780.         } while( age < min || age >= max);
  781.         return age;
  782.     }
  783.  
  784.     public static void  welcomePerson(String ... people) {
  785.         for (String person : people) {
  786.             System.out.println("Welcome " + person);
  787.         }
  788.     }
  789. }
  790.  
  791. // OOP
  792. // 1. История 1967 Алан Кай
  793. // 2. Класове и обекти
  794. // 3. Елементи на класа
  795. // 4. Статични елементи на класа
  796. // 5. Inheritance - Вьзможността да се преизползват дефинираните елементите на друг клас
  797. // 6. Abstraction - Вьзможността обект от даден клас да се третира като обект от родителски клас или интерфейс
  798. // 7. Encapsulation - Вьзможността да се скриват/енкапсулират вътрешните елементи на обектите от даден клас и да се излагат само важните за потребиеля. Обикновено това са методите от интерфейсите
  799. // 8. Polymorphism - Вьзможността обектите да запазват специфичната си функционалност (методи) и да се проявяват полиморфно, въпреки прилагането на абстракция.
Add Comment
Please, Sign In to add comment