SOFTWARE AND PROGRAMMING 1 Lecture 2 2010 Labs

SOFTWARE AND PROGRAMMING 1 Lecture 2, 2010 Labs start 20. 01. 2010: DCSIS room 131 SH room B 29 LAB Lecture 6. 00 - 7. 30 - 9. 00 EACH student must have obtained access to Birkbeck computing by 20. 01. 10 – otherwise no use in the lab Instructor: Prof. Boris Mirkin SCSIS, room 111, tel. 020 7631 6746 E-mail: mirkin@dcs. bbk. ac. uk Course Assistant:

Webpages Course web page at Black. Board: http: //www. ble. ac. uk Please check it regularly. It will be used for announcements and assignments. Another page, at an open-to-all website, functions with relevant materials too: www. dcs. bbk. ac. uk/~mirkin/sp 109 2

Concepts from lecture 1 • Compiler (javac. exe) and Interpreter (java. exe), should be on system’s path • JDK and Blue. J for running Java • Class (template) and Object (its instantiation); every Java program must be a class • Variable and its type; primitive types • Method (input-to-output operation) and its Parameters (inputs - with their types at method’s declaration) 3

Concepts for tonight • • • Casting of primitive data types Boolean expression Loops for, while Choice structure if/else Strings Input • Using Text. IO class • Using Scanner 4

Unifying type Look at A=6. 0+5 What type of A can be? Can A be Integer? No way. Unifying type: float or double 5

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; Another way: float weeklybudget = bankbalance /4. 0; 6

Boolean expressions: true or false • • |, || or 5==(1+3+7) | a+b==b+a • • • E 1 0 1 E 2 0 0 1 1 E 1|E 2 0 1 1 1 • &, && and • ! not • == equal to • < less than • > greater than • <= < or == • >= > or == Always after arithmetic; If not sure, use parentheses (…): first performed inside 7

Condition int x=2; x+4*2 > 5 true at what x is this false? int x=3; int y=1; x-4 == 1. 5*(y+2) can this be true? 8

Precedence table 9

Loop for(int var=1; var<=st; var=var+1) {do operations depending on var} var=var+1 is var++ • Two types of parentheses: (loop control) and {body to do operations} • Three items in control ( ): – initialising the counting variable once, – variable update, and – stop-condition • Exit from the loop – only from within control ( … ) 10

Loop for(int var=1; var<=st; var++) % no ‘; ’ here!!! {do operations depending on var} Two types of parentheses: (loop specified) and {body to do} • The expression in loop control “()” consists of three items in this order – initialising the counting variable once – stop-condition – variable update • First, – var is initialised, – 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 { } 11

Loop while: less rigid 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 contains same elements – init, test and update – but less rigid, not necessarily based on counter but rather on a condition; while’s structure: init; while(test){ statements; update } Similar elements: ( ), { }, initialisation, test condition (not necessarily involving the counter!), and update 12

Example: for (int K = 10; K > 1 ; K--) { //k-- is k=k-1; if (K < 7) { break; } // Stops execution of the loop else System. out. print(“ ” + K); } 1. What this loop does? 2. Can it be rewritten in the while format? 13

Example: answer 1 for (int K = 10; K > 1 ; K--) { if (K < 7) { break; } else { System. out. print(“ ” + K); } } What this loop does? Prints 10 9 8 7 14

Example: answer 2 int K = 10; while(K >1) { if (K< 7) break; else System. out. print(“ ” + K); K--; } 15

Blue. J Hello. World N times public class Hello. N { int number; \ variable declared public void go() { System. out. println("Hello, world"); } public Hello. N(int howmany) {number=howmany; } \constr-r to initialise an object public void prrt() \printing number times { for(int i=1; i<=number; i++) \loop go(); 16
![Three branching structures (1) Do under a condition; otherwise do nothing [if… structure] if(Boolean. Three branching structures (1) Do under a condition; otherwise do nothing [if… structure] if(Boolean.](http://slidetodoc.com/presentation_image_h2/b7eeb750750059b77f6fe97e5324507d/image-17.jpg)
Three branching structures (1) Do under a condition; otherwise do nothing [if… structure] if(Boolean. Expr) Statement or if(Boolean. Expr) {Statements} (2) Do under a condition; otherwise do differently [if…else… structure] if(Boolean. Expr) {Statements 1} else {Statements 2} 17

Java branching structure (3): (3) Several conditions to do differently [if…else if… … else if… else structure] if(Bool. Expr 1) Statement 1; else if(Bool. Expr 2)\and not Bool. Expr 1 Statement 2; else \ (not Bool. Expr 1) and (not Bool. Expr 2) Statement 3; • Note NO Bool. Exp at else 18

If/else example • Ticket’s price is £ 5, 60+ concession £ 3, children 12 or less go for free • Need a variable for the age, say Your. Age, and the price, say Price; • The fragment can be as: if (Your. Age<=12) Price=0; else if (Your. Age<=60) Price=5; else //note NO CONDITION to be put here Price=3; 19

Statements • • • Assignment (followed by ; ) Method call (followed by ; ) if/ifelse/else (block, no ; ) for/while loop (block, no ; ) break (followed by ; ) 20
![Double loop with method class ATM { public static void main (String[] args) { Double loop with method class ATM { public static void main (String[] args) {](http://slidetodoc.com/presentation_image_h2/b7eeb750750059b77f6fe97e5324507d/image-21.jpg)
Double loop with method class ATM { public static void main (String[] args) { Pr. Tab(2, 4); }\end main static Pr. Tab(int rowsize, int columnsize){ for (int i 1=1; i 1<rowsize+1; i 1++){ System. out. print(i 1 + " ! "); for (int i 2=1; i 2<columnsize+1; i 2++){ sum=i 1+i 2; System. out. print(sum +" "); } System. out. println(); } } }\end class 21

This produces: produces 1! 2 3 4 5 2! 3 4 5 6 3! 4 5 6 7 Q: How to make the print look better? (See printing method in Ticket. Machine – next time. ) Q: How to modify table to other ranges? Q: Make a MULTIPLICATION TABLE? 22

Input/Output Text. IO class Text. IO. java, added to the directory that contains your class, eases input of data from the keyboard To input an integer: int Us. Input = Text. IO. get. Int(); Computer will wait for the user to type in an integer value to Us. Input. 23
![Input/Output Text. IO class (2) public class Print. Square { public static void main(String[] Input/Output Text. IO class (2) public class Print. Square { public static void main(String[]](http://slidetodoc.com/presentation_image_h2/b7eeb750750059b77f6fe97e5324507d/image-24.jpg)
Input/Output Text. IO class (2) public class Print. Square { public static void main(String[] args) { int u. Input; // the number to be input by the user int Squared; // the user. Input, multiplied by itself System. out. print("Please type a number: "); u. Input = Text. IO. get. Int(); Squared = u. Input; //why product? System. out. print("The square is "+Squared); } // end of main() } //end of class Print. Square 24

Input/Output Text. IO class (3) Other Text. IO methods: b = Text. IO. get. Byte(); // value read is a byte i = Text. IO. get. Short(); // value read is a short j = Text. IO. get. Int(); // value read is an int k = Text. IO. get. Long(); // value read is a long x = Text. IO. get. Float(); // value read is a float y = Text. IO. get. Double(); // value read is a double a = Text. IO. get. Boolean(); // value read is a boolean c = Text. IO. get. Char(); // value read is a char w = Text. IO. get. Word(); // value read is a String s = Text. IO. getln(); // value read is a String 25

Input/Output in Java The Text. IO class contains static member methods Text. IO. put() and Text. IO. putln(), the same as System. out. print() and System. out. println(). Text. IO can only be used in a program if Text. IO is available to that program. It is not built into Java. From Java 1. 5. 0 version on, there is a similar class in Systems. in: Scanner 26

Input with Scanner class(1) From Java 1. 5. 0 version on, there is a similar class in System. in. Scanner(System. in): - import the java. util package in a line preceding the class, - then declare an instance of Scanner and - then use it for prompting the user to enter data (of a specified data type, preferably int, next. Int(), or double, next. Double()) from keyboard 27

Input with Scanner class (2) import java. util. * class Print. Dot{ 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. next. Int(); for (int ik=0; ik<num; ik++) System. out. print(‘. ’); System. out. println(); } \end of main } \end of class [footnote: will not compile!!!] 28

Using method with Scanner import java. util. * class Print. Dot{ int number=0; public static void main(String[ ] args){ Scanner scap = new Scanner(System. in); System. out. println(“How many ampersands to print? “); number=scap. next. Int(); ppp(number); } \end of main void ppp(nnn) { for (ik=0; ik<nnn; ik++) System. out. print(‘&’); System. out. println(); } \end of ppp } \end of class 29

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 a. Greeting = new String(“Hello”); or by assigning an actual string String a. Greeting = “Hello”; 30

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 discards the unused strings • Strings are not numbers; arithmetic and logic Java operations are not applicable. To compare Strings, a number of methods are utilised: – equals() method if s 1 and s 2 are declared and initialised as String: s 1. equals(s 2) true if s 1 and s 2 are exactly the same sequences of characters NEVER s 1==s 2 !!! This is wrong, == applies to numbers only. 31

Strings(3) Comparing String Values Try "Ha. Ha ” "ha. Ha" (2 differences) s 1. length() number of characters in s 1 char. At() method requires an integer argument which indicates the position of the character that the method returns s 1. char. At(N) N-th character in s 1 starting from N=0) String ss= “Look at you!”; Q. What is ss. char. At(3)? ss. char. At(7)? ss. char. At(17)? A. In respect, ‘k’, ‘ ’ , and error] 32

Strings(4) s 1. substring(N, M) part of s 1 in positions N, N+1, . . . , M-1 (positions are numbered from 0 !!!) String ss= “Look at you!”; What is ss. substring(3, 7)? Concatenation - Joining strings, can be done with symbol + “ 45” + “ 36” = “ 4536” 33

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 square root of number a Math. sqrt(a) Math. pow(a, b) ab ; if b is an integer then ab =a a … a (b times) 34

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? 35

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

Casting a dice question How to generate a random integer between 10 and 20 inclusive? Answer: int rdt= (int) (11*Math. random()+10); Another possibility: using class Random with import java. util. Random 37

This is what was covered tonight • • Primitive type casting Boolean expression Loop for, while Double loop Choice structure if/else Input from keyboard classes String Math 38
- Slides: 38