+ All Categories
Home > Documents > lec2 programming

lec2 programming

Date post: 02-Jun-2018
Category:
Upload: a3251332
View: 232 times
Download: 0 times
Share this document with a friend

of 20

Transcript
  • 8/11/2019 lec2 programming

    1/20

    OOD Identifying Classes

    Identifying the nouns (and noun phrases) in the

    application description

    The attributes correspond to descriptive words

    The behavior corresponds topublic methods

    contained in their corresponding classes

    Occasionally classes are not build to generate

    objects but to collect static methods and constants. Utility classes, e.g.,Math, Color, Integer

    Create classes which represent a single concept

  • 8/11/2019 lec2 programming

    2/20

    class Purse {

    public Purse();

    public void addNickels(int count);public addDimes(int count);

    public addQuarters(int count);

    public double getTotal();

    }

    class Coin{

    public Coin(double value, String aName);

    public double getValue();}

    class Purse {

    public Purse();

    public void add(Coin aCoin);

    public double getTotal();

    }

    Two concepts:

    1. a purse that holds coins,

    and

    2. the value of each coin.

    Class Purse uses/depends on

    class Coin

  • 8/11/2019 lec2 programming

    3/20

    Case Study: Invoices

    Write a set of classes to support the creation and

    printing of invoices

    Classes:

    Invoice

    Product

    LineItem

    Address

  • 8/11/2019 lec2 programming

    4/20

    public class Product {

    public Product(String aDescription, double aPrice) {

    description = aDescription;

    price = aPrice;}

    public String getDescription() {

    return description;

    }

    public double getPrice() {

    return price;

    }

    private String description;

    private double price;

    }

    public class LineItem{

    public LineItem(Product aProduct, int aQuantity) {

    theProduct = aProduct;

    quantity = aQuantity;

    }

    public double getTotalPrice() {

    return theProduct.getPrice() * quantity;

    }

    public String format() {return String.format("%-30s%8.2f%5d%8.2f",

    theProduct.getDescription(), theProduct.getPrice()

    , quantity, getTotalPrice());

    }

    private int quantity;

    private Product theProduct;}

    Product and LineItem

    classes

  • 8/11/2019 lec2 programming

    5/20

    public class Address{

    public Address(String aName, String aStreet,

    String aCity, String aState, String aZip) {

    name = aName;

    street = aStreet;

    city = aCity;

    state = aState;

    zip = aZip;

    }

    public String format() {

    return name + "\n" + street + "\n"

    + city + ", " + state + " " + zip;

    }

    private String name;private String street;

    private String city;

    private String state;

    private String zip;

    }

    Address class

  • 8/11/2019 lec2 programming

    6/20

    public class Invoice{

    public Invoice(Address anAddress) {

    items = new ArrayList();

    billingAddress = anAddress;

    }public void add(Product aProduct, int quantity) {

    LineItem anItem = new LineItem(aProduct, quantity);

    items.add(anItem);

    }

    public String format()

    {

    String r = " I N V O I C E\n\n"+ billingAddress.format()

    + String.format("\n\n%-30s%8s%5s%8s\n",

    "Description", "Price", "Qty", "Total");

    for (LineItem i : items) {

    r = r + i.format() + "\n";

    }

    r = r + String.format("\nAMOUNT DUE: $%8.2f", getAmountDue());

    return r;

    }

    public double getAmountDue() {

    double amountDue = 0;

    for (LineItem i : items) {

    amountDue = amountDue + i.getTotalPrice();

    }

    return amountDue;

    }

    private Address billingAddress;

    private ArrayList items;

    }

    Invoice class

  • 8/11/2019 lec2 programming

    7/20

    public class InvoiceTester{

    public static void main(String[] args) {

    Address samsAddress

    = new Address("Sam's Small Appliances",

    "100 Main Street", "Anytown", "CA", "98765");

    Invoice samsInvoice = new Invoice(samsAddress);

    samsInvoice.add(new Product("Toaster", 29.95), 3);

    samsInvoice.add(new Product("Hair dryer", 24.95), 1);

    samsInvoice.add(new Product("Car vacuum", 19.99), 2);

    System.out.println(samsInvoice.format());}

    }

    InvoiceTester

  • 8/11/2019 lec2 programming

    8/20

    UML

    Universal Modeling Language (UML) a standard language for specifying, visualizing, constructing,

    and documenting the artifacts of software systems, as well asfor business modeling and other non-software systems.

    Class diagram a type of static structure diagram that describes the

    structure of a system class name, attributes, methods

    relationship between classes

    Object diagram shows the snapshot of a modeled system, at a specific point

    in time

    Not required

  • 8/11/2019 lec2 programming

    9/20

    A Case Study

    An Application Centre for university admissions

    A student can choose 3 different universities, and

    lets assume that this center will accept up to 100

    different applications.

    This program has to allow the user to:

    enter the student applications,

    accept students in some of the universities that they chose,

    display the status of the applications.

  • 8/11/2019 lec2 programming

    10/20

    Class Candidates Based on Nouns

    Application Centre

    University Admissions

    Student

    Universities

    Applications Status of Applications

    Two classes: ApplicationCentre and

    StudentApplication

    Too simple to constitute

    separate classes

    Should be a property

  • 8/11/2019 lec2 programming

    11/20

    UML Class Diagram

    Application Centre

    - st[100]: StudentApplication

    - name : String

    + addStudent(): boolean

    + getStudent(int): StudentApplication

    StudentApplication

    - name: String

    - univ1, univ2, univ3: String

    - acc1, acc2, acc3: boolean

    + setAcceptance(): void

    + toString(): String

    *1

  • 8/11/2019 lec2 programming

    12/20

    1. class StudentApplication{2. private String name;3. private String university0;4. private String university1;5. private String university2;6. private boolean accept0;7. private boolean accept1;8. private boolean accept2;9. public StudentApplication (String n, String u0, String u1, String u2){10. name = n;11. university0=u0;12. university1=u1;

    13. university2=u2;14. accept0=accept1=accept2=false;15. }16. public void setAcceptance(int which, boolean decision){17. switch(which){18. case 0: accept0=decision; break;19. case 1: accept1=decision; break;20. case 2: accept2=decision; break;

    21. }22. }23. public String toString(){24. String result = name + ":\n";25. result += university0;26. if (accept0) result += " - accepted\n";27. else result += " - rejected\n";28. result += university1;

    29. if (accept1) result += " - accepted\n";30. else result += " - rejected\n";31. result += university2;32. if (accept2) result += " - accepted\n";33. else result += " - rejected\n";34. return result;35. }36. }

  • 8/11/2019 lec2 programming

    13/20

    1. class ApplicationCentre {

    2. private String name;

    3. private StudentApplication[] st;

    4. private int studentCount;5. private int size;

    6.

    7. public ApplicationCentre(String s){

    8. name=s;

    9. size=100;

    10. st = new StudentApplication[size];

    11. studentCount=0;

    12. }

    13. public String getName() {

    14. return name;

    15. }

    16. public boolean addStudent(StudentApplication s){

    17. if (studentCount==size) return false;

    18. st[studentCount]=s;

    19. studentCount ++;20. return true;

    21. }

    22. public StudentApplication getStudent(int which){

    23. if ( which < 0 || which > studentCount-1){

    24. return null;

    25. }

    26. return st[which];

    27. }

    28.}

  • 8/11/2019 lec2 programming

    14/20

    JOptionPane

    a class in javax.swing

    Method Name Description

    showConfirmDialog Asks a confirming question, like yes/no/cancel.

    showInputDialog Prompt for some input.

    showMessageDialog Tell the user about something that has happened.

    showOptionDialog The Grand Unification of the above three.

  • 8/11/2019 lec2 programming

    15/20

    1. import javax.swing.JOptionPane;

    2. public class Applications {

    3. public static void main( String args[] ) {

    4. ApplicationCentre appCentre= new ApplicationCentre (OUAC");

    5. String stopper="quit";6. int nrStud=0;

    7. JOptionPane.showMessageDialog(null,"Enter student names, each followed by 3 choices

    8. of universities. To stop enter for name the word quit","Input", JOptionPane.PLAIN_MESSAGE);

    9. String n = JOptionPane.showInputDialog("Student's name ?");

    10. boolean flag = true;

    11. while ( !n.equals(stopper) && flag){

    12. String u1 = JOptionPane.showInputDialog("1st university ?");

    13. String u2 = JOptionPane.showInputDialog("2nd university ?");

    14. String u3 = JOptionPane.showInputDialog("3rd university ? ");15. StudentApplication s=new StudentApplication (n, u1, u2, u3);

    16. flag = appCentre.addStudent(s);

    17. n = JOptionPane.showInputDialog("Student's name ?");

    18. nrStud++;

    19. }

    20.

    21. String line = JOptionPane.showInputDialog(" Indicate which applications are to be

    22. accepted by entering the student index number. To stop enter for name the word quit");

    23. while (!line.equals(stopper)) {24. int stnr = Integer.parseInt(line);

    25. line = JOptionPane.showInputDialog("Enter university index 0..2");

    26. int anr = Integer.parseInt(line);

    27. appCentre.getStudent(stnr).setAcceptance(anr, true);

    28. line= JOptionPane.showInputDialog(" Indicate which applications are to be accepted by

    29. entering the student index number. To stop enter for name the word quit");

    30. }

    31.

    32. JOptionPane.showMessageDialog(null, " Records for all applicants to "+ appCentre.getName() +33. "\n","Records", JOptionPane.PLAIN_MESSAGE);

    34. for (int i = 0; i < nrStud; i++)

    35. JOptionPane.showMessageDialog(null,appCentre.getStudent(i).toString() ,"Records",

    36. JOptionPane.PLAIN_MESSAGE);

    37. }

    38.}

  • 8/11/2019 lec2 programming

    16/20

    Arrays

    Related data items of same type

    Group of contiguous memory locations Each memory location has same name

    Each memory location has same type

  • 8/11/2019 lec2 programming

    17/20

    A 12-element array

    -45

    6

    0

    72

    1543

    -89

    0

    62

    -3

    1

    6453

    78

    c[ 1 ]

    c[ 2 ]

    c[ 4 ]

    c[ 3 ]

    c[ 5 ]

    c[ 6 ]

    c[ 7 ]

    c[ 8 ]

    c[ 9 ]

    c[ 10 ]

    c[ 11 ]

    c[ 0 ]Name of array (Notethat all elements of

    this array have thesame name, c)

    Position number (index

    of subscript) of theelement within array c

  • 8/11/2019 lec2 programming

    18/20

    Declaring and Allocating Arrays

    Declaring and allocating arrays

    Arrays are objects that occupy memory

    Allocated dynamically with operator newint c[] = new int[ 12 ];

    Equivalent to

    int c[]; // declare array

    c = new int[ 12 ]; // allocate array We can allocate arrays of objects too

    String b[] = new String[ 100 ];

    Obtaining the size of an array c.length

  • 8/11/2019 lec2 programming

    19/20

    Initializing Arrays

    Initialize array elements

    Use initializer list

    Items enclosed in braces ({}) Items in list separated by commas

    int n[] = { 10, 20, 30, 40, 50 };

    Creates a five-element array

    Subscripts of 0, 1, 2, 3, 4

    Do not need operator new

  • 8/11/2019 lec2 programming

    20/20

    Arrays of Objects

    Allocating memory for an array does not

    automatically allocate the memory for each

    element! Only references to the elements are created

    The objects need to be allocated separately

    ExampleAccount accounts[] = new Account[12];

    accounts[0].getBalance(); // wrong, Account[0] is not initialized

    Account accounts[] = new Account[12];

    for (int i = 0; i < accounts.length; i++)

    accounts[i] = new Account(); // initializing the array elements

    accounts[0].getBalance(); // correct


Recommended