sp1 lecture 5: 9/2/11:

27
1 SP1 Lecture 5: 9/2/11: Static and instance variables Class Math – Random – Loan calculator Local variables Array (if time permits)

Upload: giolla

Post on 07-Jan-2016

25 views

Category:

Documents


0 download

DESCRIPTION

SP1 Lecture 5: 9/2/11:. Static and instance variables Class Math Random Loan calculator Local variables Array (if time permits). Static and instance variables. Static variable :belongs to its class, and it is shared by all class instances, with the same value - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: SP1 Lecture 5: 9/2/11:

1

SP1 Lecture 5: 9/2/11:

• Static and instance variables• Class Math

– Random – Loan calculator

• Local variables• Array (if time permits)

Page 2: SP1 Lecture 5: 9/2/11:

2

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.

Page 3: SP1 Lecture 5: 9/2/11:

3

Example (1)public class TesNum { int instVar = 1; static int statVar = 10;TesNum() { System.out.println("test: " + instVar +

" and " + statVar); instVar = 7; statVar = 5; } \\ constructor

Page 4: SP1 Lecture 5: 9/2/11:

4

Example(2)public static void main(String[] args) { TesNum alpha1 = new TesNum(); alpha1.instVar = 3; alpha1.statVar = 6; //syn. to: TesNum.statVar

= 6;

TesNum alpha2 = new TesNum(); System.out.println("inst: " + alpha1.instVar + "

and " + alpha2.instVar); System.out.println("stat: " + alpha1.statVar + "

and " + alpha2.statVar);//System.out.print("mix: " + instVar + " and " + statVar);

wrong

}//end of main

}//end of class

Page 5: SP1 Lecture 5: 9/2/11:

5

What’s going on in TesNum

instVar statVar 1. With the class:

1 (in class) 102. At the constructor in class (virtual):

7 53. After alpha1:Constructor prints: 1 and 10

3 (within alpha1) 64. After alpha2:Constructorprints: 1 and 6

7 (within alpha2) 55. Method main prints: 3 and 7

5 and 5

Page 6: SP1 Lecture 5: 9/2/11:

6

A method added:

public int SS(int a){ int b=instVar; int sum=0; if (a>b){ //swap a and b

int c=b; b=a; a=c;} for(int i=a;i<=b;i++) sum=sum+i; return sum; }// computes the sum of integers from a to b

int b1=alpha1.SS(statVar);int b2=alpha2.SS(statVar);System.out.println("sum : " + b1 + " and " +

b2);

Page 7: SP1 Lecture 5: 9/2/11:

7

Sums to be printed

From alpha1: a=5, b=3The sum: 3+4+5=12, that is,

b1=12From alpha2: a=5, b=7

The sum: 5+6+7=18, that is, b2=18

The print:sum: 12 and 18

Page 8: SP1 Lecture 5: 9/2/11:

8

References to object variables and methods

Examples from TesNum

alpha1.statVar

alpha2.instVar

TesNum.statVar

from TesNMod

alpha1.SS(statVar)

Page 9: SP1 Lecture 5: 9/2/11:

9

Class Math (no need to import)

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 number a Math.sqrt(a) square root of number

a Math.pow(a,b) ab ; if b is an integer

then ab =aa…a (b times)

Page 10: SP1 Lecture 5: 9/2/11:

10

Loan calculator I• Deposit:

– You put £1000 with annual interest rate 5%– Q: How much money it will be in 10 years?– A: Run Java loop:

• int A=1000;• for (int k=1;k<=10;k++)•A=A*1.05;•System.out.println(“In 10 years the value

is ”+A);

• Loan– You take £1000 with annual interest rate

5% for 10 years.– Q: How much money to pay monthly?

Page 11: SP1 Lecture 5: 9/2/11:

11

Loan calculator II• Loan

– You take £1000 with annual interest rate 5% for 10 years.

– Q: How much money to pay monthly?– No simple arithmetic answer; powers needed

• Java computation– double a=1000.0; double air=0.05; – int period=10; – double mopay, totpay;– double mir=air/12; int

mp=period*12;//month unit

– mopay=(a*mir)/(1 – Math.pow(1/(1+mir),mp));– totpay=mopay*mp;

Page 12: SP1 Lecture 5: 9/2/11:

12

Loan calculator III• public class Loan{• public static void main(String[] args) {• Loan lo = new Loan();• double mopay=lo.pay(10000, 0.05,10);• double topay=mopay*12*10;• System.out.println("Monthly payment is "+mopay);• System.out.println("Total payment is "+topay);• }

• double pay(double a, double air,int period){• double mir=air/12; int mp=period*12;//month unit• double mop=(a*mir)/(1 -

Math.pow(1/(1+mir),mp));• return mop;• }• }

Page 13: SP1 Lecture 5: 9/2/11:

13

Loan calculator IV (Homework)

Modify class loan in such a way that its constructor takes from the user some or all of the details needed to do the computation:

–Loan value–Repayment period (in years)–Rate

Page 14: SP1 Lecture 5: 9/2/11:

14

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?

 

Page 15: SP1 Lecture 5: 9/2/11:

15

Casting a dicedouble 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 between 1 and 6 The same in one line:int randw= (int) (6*Math.random()+1); 

Page 16: SP1 Lecture 5: 9/2/11:

16

Casting a dice questionHow to generate a random integer

between 10 and 20 inclusive? Answer:int rdt= (int) (11*Math.random()+10);

 Another possibility: using class

Randomwithimport java.util.Random

Page 17: SP1 Lecture 5: 9/2/11:

17

Local variables: Definition

Local variable:

is created within a method or instance in a { } (curly brace) block.

Its scope is limited within the block.

Therefore, same name can be used in different blocks for different variables.

Page 18: SP1 Lecture 5: 9/2/11:

18

Local variables(1)public class Prog03{ private static int i=3; public static void method1(){ int i=2; i+=6;

System.out.println(i); } public static int method2(int a){ a=a+3; int i=2*a-6; return i; } public static void method3(int i){ System.out.println(i+1); i=i+2; System.out.println(method2(i)); }

Page 19: SP1 Lecture 5: 9/2/11:

19

Local variables(2)public static void main(String[] args){ System.out.println(i); System.out.println(i+1); method1(); i = method2(i); System.out.println(i); method3(i+1); }} //end of class

Page 20: SP1 Lecture 5: 9/2/11:

20

Actual printoutWorking from main method:

Print Why 3 First line executed, static i=3

4 Second line executed, static i=3

8 Third line executed, method1 at which i=8

6 Fifth line executed with i=method2(3), that is, i=6

8 Sixth line executed, method3(9), two printings

18

Page 21: SP1 Lecture 5: 9/2/11:

21

Array (1) Array is an indexed list of elements of the

same type; the index is supplied by default (!)

A string array nam[ ]: contains both entries and index.

String nam[] ={“John”,“Paul”,“George”,“Ringo”}; Index:         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:    0  1    2  3   4   5   6  7

Length is  8  

Page 22: SP1 Lecture 5: 9/2/11:

22

Array (2) Not an array: abc[ ]={8, Ringo, +} - WHY? (different types) [ ] - on the array name's right is used

to indicate arrays2. Declaring arrays Both, int ages[ ]; and int[ ] ages;  is OK

Page 23: SP1 Lecture 5: 9/2/11:

23

Array (3)

 Initialisation of an array: either ages = new int[8]; // array with 8 zeros or ages[ ] = {23, 32, 19, 30, 25, 25, 23,

30}; //specify what is needed  Simultaneously declaring & initialising (with

zeros)

int ages[] = new int[8];

Page 24: SP1 Lecture 5: 9/2/11:

24

Array (4)

ages[ ] = {23, 32, 19, 30, 25, 25, 23, 30};

Accessing array elements ages [1]   is   32

   

int i=4;int j = ages [i];  // assigning j with   25

Page 25: SP1 Lecture 5: 9/2/11:

25

Work with arrays(1)Data of 5 students:

double height[ ]={1.56, 1.72, 1.80, 1.85, 1.90}; //in m

double weight[ ]={65.3,80.0,78.1,76.5,112.8}; // in kg

Problem: compute the body mass index for all the students, bmi=weight/height2

(in the US, those with bmi between 20 and 25 are considered of normal weight)

Page 26: SP1 Lecture 5: 9/2/11:

26

Work with arrays(2)Loop for is natural with arrays: the index used as the

counterbmi[ ]=new double[5];for (int I = 0; I < 5; I + +)

bmi[I]=weight[I] / (height[I]height[I]); If length of student arrays is not known or is

variable, put array’s length whatever it is: bmi[ ]=new double[height.length];for (int I = 0; I < height.length; I + +)

bmi[I]=weight[I] / (height[I]height[I]); 

Page 27: SP1 Lecture 5: 9/2/11:

27

Work with arrays(3)

The same result with a method for the bmi: 

double[ ] bmiindex(double h[ ], double w[ ]){

double in[ ];

for (int ii = 0; ii < h.length; ii = ii+1)

in[ii]=h[ii]/(w[ii]w[ii]);

return in; }

Method bmiindex is just a frame box; to make it work, one needs to put within a class this:

double[ ] bmi=bmiindex(weight, height);