1 / 29

SOFTWARE AND PROGRAMMING 1

SOFTWARE AND PROGRAMMING 1. Revision Lecture 11/5/2011: Review of concepts involved in lectures and exam Review of questions in previous exam papers (they are posted on SP1 site, for example, http://www.dcs.bbk.ac.uk/~mirkin/sp109/ - see in menu on the left)

audra
Télécharger la présentation

SOFTWARE AND PROGRAMMING 1

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. SOFTWARE AND PROGRAMMING 1 Revision Lecture 11/5/2011: Review of concepts involved in lectures and exam Review of questions in previous exam papers (they are posted on SP1 site, for example, http://www.dcs.bbk.ac.uk/~mirkin/sp109/ - see in menu on the left) PLEASE BRING YOUR QUESTIONS on the exam questions !!! Will try to address them all

  2. Fundamental concepts • How a Java program works • Class; object; instance • Method; constructor • Parameter • Variable (local, static, instance) • Expression • Control structures: looping, branching • Input/output • Data type, including that user-defined • Array, 2D array

  3. Objects and classes • Classes: program templates • represent all objects of a kind (example: “student”) • Object = instance • A template copy to represent a specific element of the class (“an individual student”) • Instances are created with the so-called constructors, explicitly in JDK or somewhat easier in BlueJ

  4. Variables, methods and parameters • classescontain data stored in the so-called variables and operations which can be invoked (they are called methodsin Java) • methods may have inputs (they are called parameters in Java) to get additional data needed to get them executed

  5. Structure of a method Output’s type Inputs modifiers return-type name ( parameter-list ) { statements; return variable/expression; //if return type is not void } Modifiers: • static -       method/variable that belongs to class as whole and is shared by all • public -    method/variable that is accessible from anywhere • private -    method/variable that is accessible from only within the class

  6. Constructor • Constructor is a special method that • Has the same name as the class • No return type (nor “return”) • Is called with modifier “new” • to reserve a memory space for an object of class type (an instance) • List of parameters, as well as the block, can be user defined • The constructor with no parameters is available by default (like Const(){ }; )

  7. Assigning values • Values are stored into fields (and other variables) via assignment statements: • variable = expression; • price = ticketCost; • The value on the right is assigned to a variable on the left. • A variable stores a single value, so any previous value is lost.

  8. Variable • It provides for multiple uses of the same program • A variable is a name for a location in memory that can hold data. • Variables are declared and/or initialisedA variable declaration includes the following: • A data type that identifies the type of data that is stored in the variable • An identifier that is the variable’s name • An optional assigned initial value

  9. Scope of a variable:        - The range of statements that can access the variable. It stretches from the declaration point to the end of the block containing the declaration Q: WHAT is BLOCK ? (part within curly braces{…} ) Q: WHAT is DECLARATION? (type name ; 3-part command)

  10. Type casting       The unifying type can be overridden by explicitly stating a type cast: • Place the desired type result in parentheses followed by the variable or constant to be cast •      (int) 6.0+7=13 • Example: • int bankbalance=931786; float weeklybudget = (float) bankbalance /4;

  11. Static and instance variables Static variable: belongs to its class, and it is shared by all class instances, with the same value Instance variable: a class variable without the “static” modifier, is shared by all class instances, but its values can differ in different instances Local variable: is created within a method or instance in a { } block. Its scope is limited within the block.

  12. Loop for for(int var=1;var<=st;var++) % no ‘;’ here!!! {do operation depending on var} var++ is var=var+1 , not var=var+2; • Two types of parentheses: (loop specified) and {body to do} • The expression in () consists of three items in this order: • initialising the counting variable once, • variable update, and • stop-condition • First, • var is intialised, • stop-condition is tested; • if true, block {} is executed, • if no, the program proceeds further on, after the block { } • control returns to ( ) • After control returns to ( ), • varis updated; • stop-condition is checked; • if true, block {} is executed, then control returns to ( ), • if no, the program proceeds further on, after the block { }

  13. Loop while for(init;test;update){ statements } All three in the parentheses refer to a counter that is initialised, updated and tested over reaching the pre-specified threshold Structure of while loop, less rigid – init, test and update are not necessarily based on counter: init; while(test){ statements; update } Similar elements: ( ), { }, initialisation, test condition (not necessarily involving the counter!), and update

  14. Double loop class AddTable { public static void main(String[ ] args){ int sum; for (int ite1=1;ite1<3; ite1++) {//loop1 for (int ite2=1;ite2<5; ite2++) {//loop2 sum=ite1+ite2; System.out.print(sum +" ");}//loop2 System.out.println();}//loop1 } //method main ends } //class ends

  15. Java branching structure : if( ) … else if( ) … else if( ) … else if(BooleanExpr1) Statement1; (e.g. Tax=2;) else if(BooleanExpr2) Statement2; (e.g. Tax=18;) else Statement3; (e.g. Tax=7;) • Note: No (Boolean Expression) at else

  16. Input/Output TextIO class TextIO.java, added to the directory that contains your class, eases input of data from the keyboard To input an integer:   int UsInput = TextIO.getInt(); Computer will wait for the user to type in an integer value to UsInput.

  17. Input with Scanner class import java.util.* class PrintDot{ int num=0; public static void main(String[ ] args){ Scanner scap = new Scanner(System.in); System.out.println(“How many dots to print? “); num=scap.nextInt(); for (ik=0; ik<num; ik++) System.out.print(‘.’); System.out.println(); } //end of main } //end of class

  18. Strings(1) Declaring a String Object String variable •      An object of the class String –    The class String is defined in java.lang.String and is automatically imported into every program      Create a String object by using the keyword new and the String constructor method •      String aGreeting = new String(“Hello”); or String aGreeting = “Hello”;

  19. Strings(2) Comparing String Values •     Strings are never actually changed; instead new Strings are created and String variables hold the new addresses; A part of the Java system called the garbage collector will discard the unused strings •     It is impossible to make a simple comparison of Strings; thus a number of methods are: –   equals() method   if s1 and s2 are declared and initialised as String: s1.equals(s2) true if s1 and s2 are exactly the same sequences of characters NEVER s1==s2 !!! This is wrong, == applies to numbers only.

  20. Class Math Math.pi  =3.14…, the ratio of the circumference to its diameter Math.abs(a) a if a >= 0, or -a if a < 0 Math.log(a) the natural logarithm (base e) of a Math.sqrt(a) square root of a Math.pow(a,b) ab , if b is integer then ab =aa…a (b times) Math.random() pseudorandom number: double within interval [0.0, 1.0) (zero included, unity not) How to use it to generate a random integer between 1 and 6 (inclusive), to mimic casting a dice? double aa=Math.random(); //aa, a real number between 0 and 1 int an= 6*aa; //a real number between 0 and 6 int rand=(int) an; // whole number between 0 and 5 int randw=rand+1;// whole number betw. 1 and 6 Casting in Java: converting from higher number types to lower types int randw= (int) (6*Math.random()+1); How to generate a random integer between 10 and 20 inclusive? Answer: int rdt= (int) (11*Math.random()+10);

  21. Math.random() pseudorandom number: double within interval [0.0, 1.0) (zero included, unity not) How to use it to generate a random integer between 1 and 6 (inclusive), to imitate casting a dice?

  22. Array (1) Array is an indexed list of elements of the same type A string array nam[ ]: contains both entries and index. String nam[] ={“John”,“Paul”,“George”,“Ringo”};Index   is        0          1          2         3 Length (the number of entries) is  4 An integer array age[ ]: int age[ ]= {23, 32, 19, 30, 25, 25, 23, 30};Index  is    0  1    2  3   4   5   6  7 Length is  8

  23. Array (2) bmi[ ]=new double[5]; for (int I = 0; I < 5; I + +) bmi[I]=weight[I] / (height[I]height[I]); If we do not know the length of student arrays or it is variable: bmi[ ]=new double[height.length]; for (int I = 0; I < height.length; I + +) bmi[I]=weight[I] / (height[I]height[I]);

  24. User defined type Follows classes: - Oblong and OblongTester, sections 6.3 and 7.2, Charatan and Kans, “Java in two semesters” - Counter and CounterTest, sections 6.3-6.6, Pohl and McDowell, “Java by dissection” - Employee and TwoEmployee, p. 96-112, Ch.3, Farrell, “Java programming”

  25. 2D arrays Summary sales: •     int sum =0; •     for (int shop = 0; shop < 4; shop ++) •     for(int day = 0; day < 7; day ++) •     sum = sum + sales[shop][day]; As a method:  public int sum( int[][] a) { •  int total = 0; • for (int row = 0; row < a.length; row ++) •  for( int col = 0; col < a[0].length; col ++) •  total = total + a [row][col]; •                     return total;               }

  26. Array of user-defined type(1) • The setting: We have a number of applicants for whom we have separate, but matching, lists of names and id’s organised as arrays. • We would like to develop a new type for an Applicant to hold all individual data of the applicant, in this case just id and name, but it can have as many attributes as it takes. • With this new type, we would like to organise a list of applicants as an array of this type

  27. Array of user-defined type(2) • To develop an array of applicants, we need • A named class, say Appl, with variables declared to hold all individual applicant data (A); • A constructor in this class that would take values from the arrays holding id and name information (B); • Representation of the id and name arrays (C); • Generation of an instance of array of new type, Appl (D); • Feeding the Id’s and names into the Appl array (E); • We can show that this does work by printing out data of all the entries in the Appl array.

  28. Array of user-defined type(3) • class Appl{ • public int ids; • public String nms; • public Appl(int iden, String nnn){ • ids=iden; • nms=nnn;} • static int[] iden(){ • int ii[]={12, 15, 22, 18, 11}; • return ii;} • static String[] namen(){ • String jj[]={"Aa", "Bb", "Cc", "Dd", "Ee"}; • return jj;}

  29. Array of user-defined type(4) • public static void main(String[] args){ • int id[]=iden(); • String name[]=namen(); • Appl[] many=new Appl[id.length]; • for(int i=0;i<id.length;i++) • many[i]=new Appl(id[i],name[i]); • //many – array of Appl type objects. Check: • for(int i=0;i<name.length;i++){ • System.out.println(i +"th applicant data:"); • System.out.println("Id: "+many[i].ids); • System.out.println("Name: "+many[i].nms); • System.out.println(); } • } • }

More Related