SOFTWARE AND PROGRAMMING 1 Lecture: MB33 7:30-9:00 (except 11&18.01.06) Lab: B43, MB321, MB536...

27
SOFTWARE AND PROGRAMMING 1 Lecture: MB33 7:30-9:00 (except 11&18.01.06) Lab: B43, MB321, MB536 6:00-7:30 (from 25.01.05) [each student must have obtained access to Birkbeck computing] Lab MB536: students whose family names fall in A-F Instructor: Mr Zheng Zhu LKL, tel. 020 7763 2115 E-mail: [email protected] Lab G03 Clore Centre: students whose family names fall in G-Ka Instructor: Mrs Jenny Hu SCSIS, room NG26, tel. 020 7631 6726 E-mail: [email protected] Lab 12 Gordon Sq. 43: students whose family names fall in Ke -Y Instructor: Prof. Boris Mirkin SCSIS, room 111, tel. 020 7631 6746 O

Transcript of SOFTWARE AND PROGRAMMING 1 Lecture: MB33 7:30-9:00 (except 11&18.01.06) Lab: B43, MB321, MB536...

Page 1: SOFTWARE AND PROGRAMMING 1 Lecture: MB33 7:30-9:00 (except 11&18.01.06) Lab: B43, MB321, MB536 6:00-7:30 (from 25.01.05) [each student must have obtained.

SOFTWARE AND PROGRAMMING 1

Lecture: MB33 7:30-9:00 (except 11&18.01.06)Lab: B43, MB321, MB536 6:00-7:30 (from

25.01.05)[each student must have obtained access to Birkbeck

computing]

Lab MB536: students whose family names fall in A-FInstructor:Mr Zheng ZhuLKL, tel. 020 7763 2115 E-mail: [email protected]

Lab G03 Clore Centre: students whose family names fall in G-Ka

Instructor: Mrs Jenny HuSCSIS, room NG26, tel. 020 7631 6726E-mail: [email protected]

Lab 12 Gordon Sq. 43: students whose family names fall in Ke -Y

Instructor: Prof. Boris MirkinSCSIS, room 111, tel. 020 7631 6746E-mail: [email protected]

O

Page 2: SOFTWARE AND PROGRAMMING 1 Lecture: MB33 7:30-9:00 (except 11&18.01.06) Lab: B43, MB321, MB536 6:00-7:30 (from 25.01.05) [each student must have obtained.

2

Subjects

• TicketMachine• TextIO and Scanner class to key in

data• String class• Math class

Page 3: SOFTWARE AND PROGRAMMING 1 Lecture: MB33 7:30-9:00 (except 11&18.01.06) Lab: B43, MB321, MB536 6:00-7:30 (from 25.01.05) [each student must have obtained.

3

Test1 8/2/6 awareness

Test1 will be carried out in MB33 during the lecture time (not lab time) from 7:30, 8/2/06

Subjects:• Variable: type, declaration, initialisation• Expression: arithmetic, Boolean• Loop for• Loop while• if( )… else if( ) ... else• Simple method

Page 4: SOFTWARE AND PROGRAMMING 1 Lecture: MB33 7:30-9:00 (except 11&18.01.06) Lab: B43, MB321, MB536 6:00-7:30 (from 25.01.05) [each student must have obtained.

4

What we want of a Ticket Machine

TicketMachine code: to model a ticket machine that issues flat-fare tickets.

The functionality: - accepting fare - calculating the amount to pay back- calculating the cumulative pay- issuing tickets- informing of the price and accumulated

payInstances may have different prices

Page 5: SOFTWARE AND PROGRAMMING 1 Lecture: MB33 7:30-9:00 (except 11&18.01.06) Lab: B43, MB321, MB536 6:00-7:30 (from 25.01.05) [each student must have obtained.

5

Coding Ticket MachinePrinciple: EACH function should be done with a specific

variable/method

Functions:

- differing instances (constructor)

- different pricing (var: price)

- accepting fare (var: balance)- calculating the cumulative pay (var: total)- calculating the money back (diff = balance-price)- issuing tickets (method for printing a ticket)- informing of the price and accumulated pay (methods for

each)

Page 6: SOFTWARE AND PROGRAMMING 1 Lecture: MB33 7:30-9:00 (except 11&18.01.06) Lab: B43, MB321, MB536 6:00-7:30 (from 25.01.05) [each student must have obtained.

6

Ticket Machine (1)/* * TicketMachine models a ticket machine that issues * flat-fare tickets. */

public class TicketMachine{private int price;private int balance;private int total;

public TicketMachine(int ticketCost) //constructor { price = ticketCost; balance = 0; total = 0; } public int getPrice() { return price; } public int getBalance() { return balance; } public int getTotal() { return total; } // see next page for continuation

Page 7: SOFTWARE AND PROGRAMMING 1 Lecture: MB33 7:30-9:00 (except 11&18.01.06) Lab: B43, MB321, MB536 6:00-7:30 (from 25.01.05) [each student must have obtained.

7

Ticket Machine (2)// TicketMachine’s continuationpublic void insertMoney(int amount) { if(amount > 0) balance = balance + amount; else { System.out.println("Use a positive amount: " + amount); } } public int refundBalance() { int amountToRefund; amountToRefund = balance; balance = 0; return amountToRefund; }// continued on the next page

Page 8: SOFTWARE AND PROGRAMMING 1 Lecture: MB33 7:30-9:00 (except 11&18.01.06) Lab: B43, MB321, MB536 6:00-7:30 (from 25.01.05) [each student must have obtained.

8

Ticket Machine (3)// TicketMachine’s end public void printTicket() { if(balance >= price) { // Simulate the printing of a ticket. System.out.println("##################"); System.out.println("# The BlueJ Line"); System.out.println("# Ticket"); System.out.println("# " + price + " pence."); System.out.println("##################"); System.out.println();

total = total + price; // Update the total balance = balance - price; // Update the balance } else { System.out.println("You must insert at least: " + (price - balance) + " more pence."); } } }//end of class

Page 9: SOFTWARE AND PROGRAMMING 1 Lecture: MB33 7:30-9:00 (except 11&18.01.06) Lab: B43, MB321, MB536 6:00-7:30 (from 25.01.05) [each student must have obtained.

9

Example of branching(1)Problem: calculate income taxAlgorithm (Input: Income, Output: Tax):When the salary is less than 10000,

there is no tax. The tax is 15% on the amount earned

over 10000 up to 50000. Any money earned over 50000 are taxed

at 40%, that is, they pay 6000, the tax at 50000, plus the 40% added from the earnings over 50000.

   

Page 10: SOFTWARE AND PROGRAMMING 1 Lecture: MB33 7:30-9:00 (except 11&18.01.06) Lab: B43, MB321, MB536 6:00-7:30 (from 25.01.05) [each student must have obtained.

10

Example of branching(2)If()… :

  int Salary; int Tax=0; TextIO.putln("Input your salary "); Salary=TextIO.getInt(); //TextIO – a class

to be // put into the class’

directory 

if ((Salary > 10000)&&(Salary<=50000)) Tax=(Salary-10000)*15/100; if (Salary>50000) Tax=(Salary-50000)*40/100 + 6000;

Page 11: SOFTWARE AND PROGRAMMING 1 Lecture: MB33 7:30-9:00 (except 11&18.01.06) Lab: B43, MB321, MB536 6:00-7:30 (from 25.01.05) [each student must have obtained.

11

Example of branching(3)If()…else if()…else (preferable):  int Salary; int Tax;   if (Salary<=10000)              Tax=0;    else if (Salary<=50000)              Tax=(Salary-10000)*15/100;    else              Tax=(Salary-50000)*40/100 +

6000; • Q: What this would produce for Salary=15777?

Page 12: SOFTWARE AND PROGRAMMING 1 Lecture: MB33 7:30-9:00 (except 11&18.01.06) Lab: B43, MB321, MB536 6:00-7:30 (from 25.01.05) [each student must have obtained.

12

Method for Tax calculationMethod TC with input/parameter – Salary; output

- Tax  public float TC(int Salary) { float Tax;   if (Salary<=10000)              Tax=0;    else if (Salary<=50000)              Tax=(Salary-10000)*15/100;    else              Tax=(Salary-50000)*40/100 + 6000;  return Tax;}

Application:int mywages=15777;float mytax=TC(mywages); // would assign 866.55 to mytax

Page 13: SOFTWARE AND PROGRAMMING 1 Lecture: MB33 7:30-9:00 (except 11&18.01.06) Lab: B43, MB321, MB536 6:00-7:30 (from 25.01.05) [each student must have obtained.

13

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.

Page 14: SOFTWARE AND PROGRAMMING 1 Lecture: MB33 7:30-9:00 (except 11&18.01.06) Lab: B43, MB321, MB536 6:00-7:30 (from 25.01.05) [each student must have obtained.

14

Input/Output TextIO class (2)

public class PrintSquare {       public static void main(String[] args) {              int uInput; 

             // the number to be input by the user             int Squared;    

             // the userInput, multiplied by itself    System.out.print("Please type a number:

");    uInput = TextIO.getInt();     Squared = uInputuInput; //why product?   System.out.print("The square is

"+Squared);           } // end of main()    } //end of class PrintSquare

Page 15: SOFTWARE AND PROGRAMMING 1 Lecture: MB33 7:30-9:00 (except 11&18.01.06) Lab: B43, MB321, MB536 6:00-7:30 (from 25.01.05) [each student must have obtained.

15

Input/Output TextIO class (3)

Other TextIO methods:b = TextIO.getByte(); // value read is a bytei = TextIO.getShort(); // value read is a shortj = TextIO.getInt(); // value read is an intk = TextIO.getLong(); // value read is a longx = TextIO.getFloat(); // value read is a floaty = TextIO.getDouble(); // value read is a doublea = TextIO.getBoolean(); // value read is a booleanc = TextIO.getChar(); // value read is a charw = TextIO.getWord(); // value read is a Strings = TextIO.getln(); // value read is a String

Page 16: SOFTWARE AND PROGRAMMING 1 Lecture: MB33 7:30-9:00 (except 11&18.01.06) Lab: B43, MB321, MB536 6:00-7:30 (from 25.01.05) [each student must have obtained.

16

Input with Scanner in JavaThe TextIO class contains static

member methods TextIO.put() and TextIO.putln(), the same as System.out.print() and System.out.println().

TextIO can only be used in a program if TextIO 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

Page 17: SOFTWARE AND PROGRAMMING 1 Lecture: MB33 7:30-9:00 (except 11&18.01.06) Lab: B43, MB321, MB536 6:00-7:30 (from 25.01.05) [each student must have obtained.

17

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 - declare an instance of Scanner - use it for prompting the user to

key in data (of a specified data type, preferably int or double or String) with a method: nextInt() or nextDouble() or next()

Page 18: SOFTWARE AND PROGRAMMING 1 Lecture: MB33 7:30-9:00 (except 11&18.01.06) Lab: B43, MB321, MB536 6:00-7:30 (from 25.01.05) [each student must have obtained.

18

Input with Scanner class (2)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

Page 19: SOFTWARE AND PROGRAMMING 1 Lecture: MB33 7:30-9:00 (except 11&18.01.06) Lab: B43, MB321, MB536 6:00-7:30 (from 25.01.05) [each student must have obtained.

19

Using method with Scanner import java.util.*;class PrintDot{ 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.nextInt(); 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

Page 20: SOFTWARE AND PROGRAMMING 1 Lecture: MB33 7:30-9:00 (except 11&18.01.06) Lab: B43, MB321, MB536 6:00-7:30 (from 25.01.05) [each student must have obtained.

20

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”;

Page 21: SOFTWARE AND PROGRAMMING 1 Lecture: MB33 7:30-9:00 (except 11&18.01.06) Lab: B43, MB321, MB536 6:00-7:30 (from 25.01.05) [each student must have obtained.

21

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.

Page 22: SOFTWARE AND PROGRAMMING 1 Lecture: MB33 7:30-9:00 (except 11&18.01.06) Lab: B43, MB321, MB536 6:00-7:30 (from 25.01.05) [each student must have obtained.

22

Strings(3)

Comparing String Values

•   Try  "HaHaHa ” "haHaHa" (2 differences)

s1.length() number of characters in s1 

•      charAt() method requires an integer argument which indicates the position of the character that the method returns

  s1.charAt(N) N-th character in s1(starting from N=0) String ss= “Look at you!”; What is ss.charAt(3)? ss.charAt(7)?

ss.charAt(17)?[In respect, ‘k’, ‘ ’ , and error]

Page 23: SOFTWARE AND PROGRAMMING 1 Lecture: MB33 7:30-9:00 (except 11&18.01.06) Lab: B43, MB321, MB536 6:00-7:30 (from 25.01.05) [each student must have obtained.

23

Strings(4)

  s1.substring(N,M) part of s1 in positions N, N+1, ..., M-1 (positions are numbered from 0)

String ss= “Look at you!”; What is ss.substring(3,7)?

Concatenation

    Concatenation - Joining strings, can be done with symbol +

      “45” + “36” = “4536”  

Page 24: SOFTWARE AND PROGRAMMING 1 Lecture: MB33 7:30-9:00 (except 11&18.01.06) Lab: B43, MB321, MB536 6:00-7:30 (from 25.01.05) [each student must have obtained.

24

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); 

Page 25: SOFTWARE AND PROGRAMMING 1 Lecture: MB33 7:30-9:00 (except 11&18.01.06) Lab: B43, MB321, MB536 6:00-7:30 (from 25.01.05) [each student must have obtained.

25

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 26: SOFTWARE AND PROGRAMMING 1 Lecture: MB33 7:30-9:00 (except 11&18.01.06) Lab: B43, MB321, MB536 6:00-7:30 (from 25.01.05) [each student must have obtained.

26

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 27: SOFTWARE AND PROGRAMMING 1 Lecture: MB33 7:30-9:00 (except 11&18.01.06) Lab: B43, MB321, MB536 6:00-7:30 (from 25.01.05) [each student must have obtained.

27

Casting a dice questionHow to generate a random integer

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