1 / 27

SOFTWARE AND PROGRAMMING 1

This lecture covers the fundamentals of variable types, expression evaluation, loops with for and while, and creating simple methods in Java. The code examples include modeling a ticket machine that issues flat-fare tickets and performs various operations such as accepting fare, calculating cumulative pay, issuing tickets, and providing price information.

rromeo
Download Presentation

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. O 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: zheng@dcs.bbk.ac.uk 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: jennychhu@yahoo.com Lab 12 Gordon Sq. 43: students whose family names fall in Ke -Y Instructor: Prof.Boris Mirkin SCSIS, room 111, tel. 020 7631 6746 E-mail: mirkin@dcs.bbk.ac.uk

  2. Advice: setting a path to Java • Right-click on "My Computer", choose Properties, then Advanced tab; hit button for Environment Variables • Set a new variable called Path with the value "C:\Program Files\Java\jdk1.5.0_04\bin"

  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

  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 pay Instances may have different prices

  5. Coding Ticket Machine Principle: 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)

  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

  7. Ticket Machine (2) // TicketMachine’s continuation public 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

  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

  9. Example of a while loop: Structure: initialisation; while(test){…, update, …} int a=1; int b=6; while(a<=b){ a=a+2; b=b-2; System.out.println(“a = ” + a + “ and b = ” + b); } 1. What this loop does? 2. Can it be rewritten in the forformat? Homework

  10. What the while loop does: int a=1; int b=6; while(a<=b){ a=a+2; b=b-2; System.out.println(“a = ” + a + “ and b = ” + b); } This loop prints a = 3 and b = 4 a = 5 and b = 2

  11. Double loop (1) 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

  12. Double loop (2) This prints 2 3 4 5 3 4 5 6  Why? A better printing ? Such as: Addition Table + 1 2 3 4 1 2 3 4 5 2 3 4 5 6

  13. Double loop (3) class AddTable { public static void main (String[] args) {int sum; for (int i1=1;i1<3; i1++){ System.out.print(i1 + " ! "); for (int i2=1;i2<5; i2++){ sum=i1+i2; System.out.print(sum +" ");} System.out.println();} } }

  14. Double loop (4): with method class AddTableMeth { public static void main (String[] args) { PrintTable(2,4); }\\end main public static PrinTable(int rowsize, int columnsize){ for (int i1=1;i1<rowsize+1; i1++){ System.out.print(i1 + " ! "); for (int i2=1;i2<columnsize+1; i2++){ sum=i1+i2; System.out.print(sum +" ");} System.out.println();} } }\\end class

  15. Double loop (5) produces 1! 2 3 4 5 2! 3 4 5 6 3! 4 5 6 7 Q: How to make it look better? (See printing method in TicketMachine.) Q: How to modify it to other ranges? Q: Make a MULTIPLICATION TABLE?

  16. 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

  17. Example of branching(1) Problem: calculate income tax Algorithm (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.

  18. 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;

  19. 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?

  20. Method for Tax calculation Method 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

  21. 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.

  22. 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 = uInputuInput; //why product? System.out.print("The square is "+Squared); }// end of main()     } //end of class PrintSquare

  23. Input/Output TextIO class (3) Other TextIO methods: b = TextIO.getByte(); // value read is a byte i = TextIO.getShort(); // value read is a short j = TextIO.getInt(); // value read is an int k = TextIO.getLong(); // value read is a long x = TextIO.getFloat(); // value read is a float y = TextIO.getDouble(); // value read is a double a = TextIO.getBoolean(); // value read is a boolean c = TextIO.getChar(); // value read is a char w = TextIO.getWord(); // value read is a String s = TextIO.getln(); // value read is a String

  24. Input/Output in Java The 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

  25. 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 or double) from keyboard

  26. 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

  27. 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

More Related