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

SOFTWARE AND PROGRAMMING 1 Lecture 7/5/8: Review of concepts involved in lectures and exam Lecture 14/5/8: Review of questions in previous exam papers

Embed Size (px)

Citation preview

SOFTWARE AND PROGRAMMING 1

Lecture 7/5/8:

Review of concepts involved in lectures and exam

Lecture 14/5/8:

Review of questions in previous exam papers (they are posted on SP1 site, for example,

http://www.dcs.bbk.ac.uk/~mirkin/sp105/ - see in menu on the left)

- PLEASE BRING YOUR QUESTIONS on the questions !!! – will try to address 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”)• Objects = instances

– 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

• classes contain data stored in the so-called variables and operations which can be invoked (they are called methods in 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

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

Output’s type Inputs

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

initialised A 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 forfor(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 ( ),

– var is 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 loopclass AddTable {public static void main(String[ ] args){int sum; for (int ite1=1;ite1<3; ite1++) {//loop1for (int ite2=1;ite2<5; ite2++) {//loop2

sum=ite1+ite2;System.out.print(sum +" ");}//loop2System.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 classTextIO.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 classimport 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 MathMath.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 =aa…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 1int an= 6*aa; //a real number between 0 and 6int rand=(int) an; // whole number between 0 and 5int 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 typeFollows 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

User defined type (my lectures)

Task: supplementary to primitive number types, introduce an interval type

First, define attributes that you want to be maintained by the type (depend on what needs are to be satisfied with it)

0 a b

al ar bl br x axis

Attributes: colour, left_bound, right_bound, length

a.length=ar-al; b.length=br-bl;

26

2D arraysSummary 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;               }