1 / 46

Modernās Programmēšanas Tehnoloģijas (Advanced Programming Technologies )

Modernās Programmēšanas Tehnoloģijas (Advanced Programming Technologies ). Edgars Celms, Mārtiņš Opmanis (askola@mii.lu.lv). Latvijas Universitātes Matemātikas un informātikas institūts 200 7, Rīga, Latvija. Ievads valodā JAVA III. “ Java™ How to Program, Sixth Edition ”

iolana
Télécharger la présentation

Modernās Programmēšanas Tehnoloģijas (Advanced Programming Technologies )

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Modernās Programmēšanas Tehnoloģijas(Advanced Programming Technologies) Edgars Celms, Mārtiņš Opmanis (askola@mii.lu.lv) Latvijas Universitātes Matemātikas un informātikas institūts 2007,Rīga, Latvija

  2. Ievads valodā JAVA III • “Java™ How to Program, Sixth Edition” • Chapter 4. Control Statements: Part I • Chapter 5. Control Statements: Part II • if, if … else instrukcijas • while, do … while, for cikli • continue un break instrukcijas • switch instrukcija • Saliktie (compouned) artimētiskie operatori • Loģiskie operatori

  3. Izvēles (selection) instrukcijas • if instrukcija(statement) • Vienkārša izvēles (single-selection)instrukcija • Izpilda kaut ko, ja nosacījums (condition) ir patiess, citādi nedara neko • if…elseinstrukcija • Divkārša izvēles (double-selection)instrukcija • Izpilda kaut ko vienu, ja nosacījums ir patiess un izpilda kaut ko citu, ja nosacījums ir aplams • switchinstrukcija • Daudzkārša izvēles (multiple-selection)instrukcija • Var izpildīt dažādus darbus atkarībā no izteiksmes vērtības • Nosacījuma (conditional)operators • ? : (vienīgais ternārais operators – nepieciešami trīs operandi)

  4. Ciklu (repetition, loop) instrukcijas • Atkārto kaut kādas darbības kamēr vien cikla turpināšanas nosacījums ir patiess • whileinstrukcija • Izpilda cikla darbības nevienu vai vairākas reizes • forinstrukcija • Izpilda cikla darbības nevienu vai vairākas reizes • sākot ar J2SE 5.0 ir ieviests paplašinātais for cikls kolekcijām (par to vēlāk) • whileun forinstrukcijas – ja cikla turpināšanās nosacījums jau pirmajā cikla izpildes reizē ir aplams (false) tad cikls neizpildās nevienu reizi • do…whileinstrukcija • Izpilda cikla darbības vienu vai vairākas reizes

  5. Izvēles (selection) instrukcijas UML aktivitāšu (activity) diagramma – bieži lietots formālisms, lai attēloti vadības plūsmas programmās (algoritmos) • if instrukcija. Izpilda kaut ko, ja nosacījums (condition) ir patiess, citādi nedara neko if (studentGrade >= 60) System.out.println(“Passed”); • if … else instrukcija. Izpilda kaut ko vienu, ja nosacījums ir patiess un izpilda kaut ko citu, ja nosacījums ir aplams if (studentGrade >= 60) System.out.println(“Passed”); else System.out.println(“Failed”); • Nosacījuma (conditional) operators • ? : un tā trīs operandi veido nosacījuma izteikmsi • Var tikt lietots un to bieži arī lieto if … else konstrukcijas vietā • Vienīgais ternārais operators valodā JAVA System.out.println((studentGrade >= 60)? “Passed”: “Failed”);

  6. Salikta if … else konstrukcija if (studentGrade >= 90) System.out.println( “A” ); else if (studentGrade >= 80) System.out.println( “B” ); else if (studentGrade >= 70) System.out.println( “C” ); else if (studentGrade >= 60) System.out.println( “D” ); else System.out.println( “F” );

  7. if … else lietošanas īpatnības I • Java kompilators vienmēr piekārto else tuvākajam pirms tam esošam if, ja nav likts darīt savādāk izmantojot figūriekavas (blokus) • if ( x > 5) • if ( y > 5) • System.out.println( “x and y are > 5” ); • else • System.out.println( “x is <= 5” ); • Nobīdes (idents) izejas kodā kompilators ignorē • Ja x ir mazāks vai vienāds ar 5, tad nekas nenotiek Tiek interpretēts kā if ( x > 5) if ( y > 5) System.out.println( “x and y are > 5” ); else System.out.println( “x is <= 5” ); if ( x > 5) { if ( y > 5) System.out.println( “x and y are > 5” ); } else System.out.println( “x is <= 5” ); Pareizais risinājums

  8. if … else lietošanas īpatnības II • if (studentGrade >= 60) • System.out.println(“Passed”); • else • System.out.println(“Failed”); • System.out.println(“Repeat course”); • Loģiska kļūda – “Repeat course” tiks vienmēr izvadīts Pareizais risinājums if (studentGrade >= 60) System.out.println(“Passed”); else { System.out.println(“Failed”); System.out.println(“Repeat course”); }

  9. while cikla instrukcija • Atkārto darbību (vai darbību virkni – programmas bloku) kamēr cikla nosacījums ir patiess int product = 3; while ( product <= 100) product = 3 * product; Darbību nenorādīšana while instrukcijas ķermenī – visticamāk, ka radīs loģisku izpildlaika kļūdu – bezgalīgs cikls (infinite loop)

  10. GradeBook klase (atgādinājums)

  11. while cikla instrukcijas piemērs I Lokālo mainīgo inicializācija Veselu skaitļu dalīšana: Rezultāts ir vesels skaitlis

  12. while cikla instrukcijas piemērs II Tipu konvertācija – nākamais slaids

  13. Primitīvo tipu konvertācijas • JAVA var izpildīt aritmētiskās operācijas tikai ar vienāda tipa operandiem !!! • Tiešā konvertācija (explicit conversion) • Konvertācijas operators • piemērs: (double)- rada laicīgu (temporary)peldoša punkta skaitļa kopiju • average = (double) total / gradeCounter; • Netiešākonvertācija (implicitconversionor promotion) • Konvertē vērtības (piem.,int) uz citu datu tipu (piem.,double), lai varētu veikt darbības • Nodrošina operandiem vienādus tipus • gradeCounter: konvertēts (paaugstināts (promoted))par double • Konvertēšana uz nesaderīgu tipu: izsauc kompilācijas vai izpildlaika (runtime)kļūdas

  14. Populārākās programmēšanas kļūdas I (Common Programming Error) • Placing a semicolon after the condition in anif or if...else statement leads to a logicerror in single-selection if statements and asyntax error in double-selection if...elsestatements (when the if-part contains anactual body statement).. • Not providing, in the body of a whilestatement, an action that eventually causesthe condition in the while to become falsenormally results in a logic error called aninfinite loop, in which the loop neverterminates. • Using the value of a local variable beforeit is initialized results in a compilationerror. All local variables must beinitialized before their values are used inexpressions. • When performing division by an expressionwhose value could be zero, explicitly test forthis possibility and handle it appropriately inyour program (e.g., by printing an errormessage) rather than allow the error to occur

  15. Iekļautas vadības instrukcijas • Valodā JAVA programmas vadības instrukcijas var būt iekļautas viena otrā

  16. Saliktie (compouned) artimētiskie operatori • Saliktie piešķiršanas operatori (compound assignment operators) • Palielināšanas un samazināšanas operatori (increment & decrement) • Prefix & postfix operatori

  17. Palielināšanas un samazināšanas operatori

  18. Dažas piezīmes • Vienu un to pašu var noprogrammēt daudzos dažādos veidos • rakstiet pēc iespējas vienkāršākas programmas (“KIS – keep it simple”) • izmantojiet standarta risinājumus Nav viens un tas pats!!! ++ir augstāka prioritāte par <= int counter = 1; while (++counter <= 10) Sytem.out.printf (“%d “, counter);

  19. Populārākās programmēšanas kļūdas II (Common Programming Error) • Attempting to use the increment ordecrement operator on an expressionother than one to which a value can beassigned is a syntax error. For example,writing ++(x + 1) is a syntax errorbecause (x + 1) is not a variable. • Control counting loops with integers. Because floating-point values may beapproximate, controlling loops with floating-pointvariables may result in imprecisecounter values and inaccurate terminationtests.

  20. for cikla instrukcija

  21. for cikla instrukcija Inicializācija notiek tikai vienreiz – pirms pirmās cikla nosacījuma pārbaudes

  22. for cikls • Cikla inicializācijas un palielināšanas izteiksmes (initialization and increment expressions)var būt izteiksmju saraksti atdalīti ar komatiem (comma-separated lists of expressions). • Piemēram, for ( int number = 2; number <= 20; number += 2 ) total += number; Ir tas pats kas: for ( int number = 2; number <= 20; total += number, number += 2 )

  23. for cikls • Daži for cikla piemēri: • Cikls no 1līdz 100 ar soli 1 • for ( int i = 1; i <= 100; i++ ) • Cikls no 100līdz 1 ar soli –1 • for ( int i = 100; i >= 1; i-- ) • Cikls no 7līdz77ar soli 7 • for ( int i = 7; i <= 77; i += 7 ) • Cikls no 20līdz2ar soli -2 • for ( int i = 20; i >= 2; i -= 2 ) • Cikls pa virkni: 2, 5, 8, 11, 14, 17, 20 • for ( int i = 2; i <= 20; i += 3 ) • Cikls pa virkni: 99, 88, 77, 66, 55, 44, 33, 22, 11, 0 • for ( int i = 99; i >= 0; i -= 11 )

  24. Populārākās programmēšanas kļūdas III (Common Programming Error) • Using an incorrect relational operator or an incorrect final value of a loop counter in the loop-continuation condition of a repetition statement can cause an off-by-one error. (This is a popular test question). • When a for statement’s control variable is declared in the initialization section of the for’s header, using the control variable after the for’s body is a compilation error. • Not using the proper relational operator in the loop-continuation condition of a loop that counts downward(e.g., using i <= 1 instead of i >= 1 in a loop counting down to 1) is usually a logic error.

  25. for cikla piemērs Problem Statement: A person invests $1,000 in a savings account yielding 5% interest. Assuming that all the interest is left on deposit, calculate and print the amount in the account at the end of each year for 10 years: a = p (1+r)n a: amount on deposit, p: principal, r: interest rate, n: years %20s: display the string with at least 20 character positions after displaying “Year” – right justified Left justification: use – formatting flag before the field width Math class static method pow - raise a value to a power Java does not have exponent operator : ^ or ** Comma (,) formatting flag - output with a thousands separator Each iteration calculates – performance issue

  26. for cikla piemērs

  27. Peldošo punktu skaitļu neprecizitātes • Uzmanieties attēlojot datus izmantojot formatēšanas virkni%.2f • Tiek noapaļots līdz simtdaļām • 14.234 14.23, 18.67318.67 • Divu skaitļu saskaitīšana • “Iekšēji” tiek saskaitīts 14.234 + 18.673 = 32.907 •  attēlojot ar %.2fiegūstam 32.91 • Bet ... iespējams, ka vēlējāmies kaut ko tādu • 14.23 + 18.67 = 32.90 • Nelietojiet double (vaifloat) tipus precīziem finansu aprēķiniem • Ir pieejamas klašu bibliotēkas, kuras risina šo problēmu • Tāda ir arī iekļauta Java API java.math.BigDecimal

  28. do … while cikla instrukcija • Līdzīga whileinstrukcijai • Pārbauda cikla nosacījumu cikla beigās • Cikla ķermenis izpildās vismaz vienu reizi

  29. switchinstrukcija • Daudzkārša izvēles (multiple-selection)instrukcija • Var izpildīt dažādus darbus atkarībā no izteiksmes vērtības • Katra darbība ir asociēta ar konstantas integrālās izteiksmes vērtību (value of a constant integral expression) • byte, short, int vai char tipa vērtības • long tipa vērtības nav atļautas

  30. switchinstrukcijas piemērs I

  31. switchinstrukcijas piemērs II end-of-filepazīme – sistēmatkarīga mūsu piemērā nosaka vai tik vēl kādi dati ievadīti(portability) grade: lokāls mainīgais total & gradeCounter: lauki (instanču mainīgie)

  32. switchinstrukcijas piemērs III switchnosaka, kurš casezars tiks izpildīts pamatojoties uz izteiksmes “grade/10” rezultātu 9 un 10 gadījumā izpilda vienu un to pašu breakinstrukcija: detalizētāk tiks aplūkota kopā ar continueinstrukciju Noklusētais darbību scenārijs (neobligāts) (default clause): izpildās tad, ja neviens no case zariem nav izpildījies - ieteikums lietot šādu konstrukciju, lai varētu apstrādāt neparedzētas situācijas

  33. switchinstrukcijas piemērs IV

  34. switchinstrukcijas piemērs V

  35. Citas programmas vadības instrukcjas • break instrukcija • continueinstrukcija • break un continue instrukcijas ar iezīmēm (labeled) • Kaut kas līdzīgs goto citās valodās (par to vēlāk)

  36. break un continue instrukcijas

  37. Loģiskie operatori • Vadības instrukcijas (if, if ..else, while, do..while un for): nosaka programmas plūsmas vadību • Vienkārši nosacījumi • count <= 10 • number != sentinelValue • Lai pārbaudītu daudzkāršus nosacījumus • iekļautās ifvaiif .. elseinstrukcijas • Loģiskie operatori dod iespēju veidot saliktus nosacījumus no vienkāršajiem nosacījumiem

  38. Īsslēguma vērtējums (short-circuit evaluation) • Izteiksmju daļas, kuras satur &&vai ||operatorus, tiek izvērtētas tikai tad, ja tas ir nepieciešams • Piemēram, (gender == FEMALE) && (age >= 65) • Izteiksmes izvērtējums tiek pārtraukts, ja gendernav vienāds ar FEMALE

  39. Loģiskais && operators if ( gender == FEMALE && age >= 65 ) ++seniorFemales;

  40. Loģiskais || operators if ( ( semesterAverage >= 90 ) || ( finalExam >= 90 )) System.out.println( “Student grade is A” );

  41. Citi loģiskie operatori • Boolean Logical AND (&) or OR (|) Operator • Darbojas “gandrīz” tāpat kā && or || • Vienmērtiek vērtēti abi operandi • Boolean Logical Exclusive OR (^) • true: ja viens operands ir trueun otrs false • false: ja abi operandi ir truevai abi irfalse • Loģiskais negācijas (!) operators • Unārais loģiskais operators • Reversē (maina uz pretējo) nosacījumu vērtību if (gender == FEMALE && ++age >=65) //age var tikt nepalielināts (short-circuit evaluation) ++seniorFemales; if (gender == FEMALE & ++age >=65) //age VIENMĒR tiks palielināts ++seniorFemales;

  42. Loģisko operatoru lietojumu piemēri • Attēlo loģisko izteiksmju vērtības • %b: Boolean format specifier (true or false)

  43. Loģisko operatoru lietojumu piemēri

  44. Populārākās programmēšanas kļūdas IV (Common Programming Error) • In expressions using operator &&, a condition may require another condition to be true for the evaluation of the dependent condition to be meaningful. • For example, in the expression ( i != 0 ) && ( 10 / i == 2 ), the second condition must appear after the first condition, or a divide-by-zero error might occur.

  45. Operatoru prioritāšu secība un asociativitāte

  46. Jautājumi ?

More Related