02-ObjectsControlArrays

02-ObjectsControlArrays - 2-1 Data Structures and Design...

Info icon This preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: 2-1 Data Structures and Design with Java 5 and JUnit Chapter 2 Objects, Control Structures, and Arrays Rick Mercer, 2006 2-2 Outline Objects Assertions with JUnit Control Structures: if, else, for, while 1-D Arrays 2-D Arrays 2-3 Find real world entities Implement a bank teller application that provides many bank customers access to bank accounts through a unique ID. The customer, with the help of the teller, may complete any of the following transactions: withdraw money, deposit money, query account balances, and see the most recent ten (10) transactions. The system must maintain the correct balances for all accounts. The system must be able to process one 2-4 BankTeller Window 2-5 Nouns are possible classes Potential objects to model a solution: BankTeller Customer BankAccount IdentificationNumber Transaction ListOfTransactions MonthlyStatement Nore object inthe view: JFrame, JButton, JLabel Let's consider one object as a collection of methods and data to represent an account at a bank 2-6 A BankAccount type BankAccount models an account at a bank This class could have a collection of methods to allow for operations like these withdraw(50.00) deposit(152.27) getBalance() // return account balance getID() // return account identification The class could allow all instances to have state (values) such as this: an ID such as "Little, Stuart" a balance such as 507.99 2-7 Constructing objects The BankAccount class is not part of Java It is domain specific Each BankAccount object must be constructed with tw values: A String to initialize the ID A number that represents the current balance // Construct a BankAccount object with 2 arguments BankAccount anAccount = new BankAccount("Kim", 100.00); 2-8 Class and Object Diagrams Relationship between a class and it objects Each object stores its state in instance variables BankAccount instance variables -String my_ID -double my_balance +withdraw(double amount) +deposit(double amount) +double getBalance( ) +String getID( ) +String toString() class name instance (object) state BankAccount: anAcct my_ID = "Kim" my_balance = 100.0 methods BankAccount: acct2 my_ID = "Daly" my_balance = 75.00 instance (object) state 2-9 What is an Object in the computer? Object: a bunch of bits in the computer memory Every object has 1) a name: a reference variable to find the object 2) a set of messages that it understands 3) state the values that the object remembers The state, set of values is often initialized at construction when memory is allocated with new Can send messages (invoke functions) to objects 2-10 Constructing objects Whereas primitives may be initialized with one value: int n = 0; double x = 0.000001; object construction requires new class-name identifier name(initial-value(s)); = new class- Some classes require 0, 1, 2, 3, or more arguments JFrame theWindow = new JFrame(); String name = new String("Kim Broderbroens"); JButton clickMeButton = new JButton("A Button"); Font aFont = new Font("Courier", Font.ITALIC, 24); BankAccount myAcct = new BankAccount("Bob", 123.45); GregorianCalendar aDay=new GregorianCalendar(2001,1,1); 2-11 Sending Messages Each class has a collection of methods BankAccount has withdraw deposit getID getBalance length indexOf charAt toLowerCase String has A method (function) is invoked via a message A message has a sender (main e.g.), a receiver (the object), a message-name and the arguments. object name . messsagename( arguments) 2-12 Messages continued General Form: sending a message to an object object-name . method-name (argument-list ) Example Messages anAccount.deposit(100.00); name.toUpperCase(); theWindow.setSize(200, 400); theTextField.setText("A different String"); theTextField.getText(); 2-13 Messages Some messages return information about an object's state Other messages tell an object to do something. A message that asks the object to return information: anAccount.getBalance(); A message that tells the object to do something: anAccount.withdraw(25.00); 2-14 The String class Java has a class for manipulating a collection of characters The character set could be any of the hundreds in the world, we'll use the ASCII character set String methods include substring toUpperCase charAt length indexOf 2-15 Example String Messages String str = new String("Kim Devonshore"); // first argument to substring is beginIndex (4), // the second is endIndex 1 (13) here String lastName = str.substring(str.indexOf(" ")+1, str.length()); 2-16 Shortcut String object construction In Java, the compiler adds the new() when it see a String literal "abc" // s2 can be xconstructed witout new String s2 = "Don't need 'new String("Abc")'"; assertEquals(Don't need 'new String("Abc")', s2); Consider always giving the object a value // Compiler will say: "s1 may not be initialized" String s1; System.out.println(s1); // Compiletime ERROR 2-17 Reference types Java has two types of data primitive types that store one value char boolean byte int long float double reference types to store many values with one name any of the hundreds of classes that come with Java String BufferedReader Student URLAddress Jukebox JButton any domain types for specific applications BankAccount CD Classes that provide utility in a wide variety of applications Scanner String arrays JFrame 2-18 What's the difference Primitive type variables that store the actual value of the variable int n = 0; // n stores 0 Reference type variables store a special value for finding the object at runtime the object is a bunch of bits on the heap (special part of memory that gets allocated at runtime) the reference value is used to locate the object (not a pointer, but easy to see it as one) 2-19 Object and Classes Objects model real world entities that are more complex than numbers or single characters Objects are "constructed" from an existing class such as String A class is a blueprint for constructing many objects A class is a collection of related methods and data needed by the methods to fulfill their responsibilities An object has it own set of values 2-20 JUnit JUnit: A framework for designing and testing Java classes Can be used standalone, but is part of most Java Development Environments: Eclipse, Dr. Java, BlueJ JUnit also provides a convenient way to reason and demonstrate how objects work with assertions 2-21 Assertions if it is not, there is something wrong Assertion: A statement that is expected to be true Junit provides many assertions such as assertTrue, assertFalse, and assertEquals General Form: A FEW Junit assertions assertEquals(int expected, int actual); assertEquals(double expected, double actual, double error); assertTrue(BooleanExpression); assertFalse(BooleanExpression); 2-22 Example Unit Test import static org.junit.Assert.*; import org.junit.Test; public class BankAccountTest { @Test // This is a test method public void testDeposit() { BankAccount b1 = new BankAccount("Ali", 0.00); assertTrue(b1.getBalance() == 0.0); b1.deposit(123.45); assertEquals(123.45, b1.getBalance(), 1e-14); } @Test // Another test method public void testWithdraw() { BankAccount b2 = new BankAccount("Britt", 500.00); b2.withdraw(160.01); assertEquals(339.99, b2.getBalance(), 1e-14); } } 2-23 Red Bar / Green Bar JUnit provides a way to see if any assertion fails Can run the previous test class named BankAccount.class with text output public class RunBankAccountTest { public static void main(String args) { junit.textui.TestRunner.run(BankAccountTest.class); } } Output .. Time: 0.01 OK (2 tests) 2-24 Failing Assertion If an assertion fails the output indicates that also: assertTrue(5 != 5); Output .F Time: 0.016 There was 1 failure: ... output deleted ... FAILURES!!! Tests run: 1, Failures: 1, Errors: 0 2-25 Can use a Graphical View public class RunBankAccountTest { public static void main(String args) { } } junit.swingui.TestRunner.run(BankAccountTest.class); 2-26 Assertions Assertions can relay the current state of an object or convey the result of a message to an object The next slide shows the actual value returned by substring (Eclipse on a Mac) The expected value is wrong, the code forgot substring's endIndex has 1 subtracted from it 2-27 See what a method returns 2-28 Object Behavior JUnit allows a more coherent way to observe the how objects work The next slide shows several things Attempt to withdraw a negative is not allowed The state is not changed Attempt to withdraw more than the balance is not allowed The state is not changed 2-29 Demo Behavior (and test) 2-30 Methods act of using and/or understanding something without full knowledge of the implementation allows programmer to concentrate on essentials Abstraction: how does a String's substring? Not to worry How does System.out.println send output to the console? how does a JButton know it's been clicked? Don't really need to know What algorithm does the Math.sqrt method use? However, programmers often create new methods We will need to implement methods 2-31 Methods A Java class typically contains many methods, each of which has a method heading Method headings specify the number and types of arguments required There are two major components to a method: the method heading the block (a set of curly braces with the code that completes the method's responsibility) 2-32 Method Headings Sun uses method headings (and other things) to document methods so we know how to use them public String substring( int beginIndex, int endIndex ) Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex-1. Thus the length of the substring is endIndex-beginIndex. Examples: "hamburger".substring(4, 8) returns "urge" "smiles".substring(1, 5) returns "mile" Parameters: beginIndex - the beginning index, inclusive. endIndex - the ending index, exclusive. Returns: the specified substring. 2-33 What method headings tell us Method headings provide the information needed to use it they show us how to send a message to instances of the class public String substring(int beginIndex, int endIndex) What does the method evaluate to? String - What is the method name? substring - How many arguments are required? 2 - What type of arguments are required? int Example message String fullName = "Murphy, John"; String lastName = fullName.substring(0, 6); 2-34 Parameters = Arguments The substring method requires two arguments in order to specify the portion of the string to return. When the message is sent, the argument 0 is assigned to the parameter named beginIndex and the argument 6 to the parameter name endIndex fullName.substring( 0, 6 ); public String substring( int beginIndex, int endIndex ) Implementation of the method is not shown here 2-35 Arguments / Parameters When a message is sent The first argument is assigned to the first parameter, second argument gets assigned to the second parameter,... If you do not supply the correct number and type of arguments, you get compiletime errors Examples of errors fullName.substring( fullName.substring( fullName.substring( fullName.substring( "wrong type" ); 0, 6, fullName.length() ); ); 0.0, 6.0 ); 2-36 Method Headings General form of a Java method heading public returntype methodname ( parameter1, parameter2, parametern, ... ) public says a method is known where objects are constructed return-type may be any primitive type, any class, or void A void method returns nothing therefore, a void method can not be assigned to anything also, you can not place a call to a void method in println parameters, which are optional, specify the number and type of arguments required in the message Sometimes objects need extra information: How much to deposit? 2-37 Parameters class-name identifier -orprimitive-type identifier General form of a parameter between ( and ) in method headings Example method headings: public public public public int length() // class void withdraw(double amount)// class double nextInt() // class boolean hasNextInt() // class String BankAccount Scanner Scanner 2-38 Method Headings whether the method is available to the outside world In summary, method headings provide these things: public methods are known in the block where constructed return-type the kind of value a message evaluates to method-name that begins a valid method call parameter-list the number and type of needed arguments documentation describing what the method does Hopefully, the programmer who wrote the method documents them with useful information Now go to Sun's JavaTM API for sample method headings http://java.sun.com/javase/6/docs/api/ 2-39 The Method Body The method body is Java code enclosed within a block { } Curly braces can have the same things we've seen in main variable declarations and initializations: int creditOne = 0; input and output messages: nextInt, println construct objects: Scanner in= new Scanner(System.in); messages: in.nextDouble(); Method bodies have access to the state of the object The "state" of an object is implemented as variables declared inside the class rather than a method body more on these "instance" variables later 2-40 Selection 2-41 The Guarded Action Pattern Guarded Action Pattern: Problem: Execute actions only under certain conditions General Form Code Example: if (true-or-false-condition is true) execute this set of statements if(aStudent.getGPA() >= 3.5) deansList.add(aStudent); 2-42 The if statement if(boolean-expression) true-part ; General form: Execute true-part only when boolean-expression evaluates to true A boolean-expression is any expression that evaluates to true or false three examples sales < 15000.00 hoursWorked > 40 true || false // read as true or false 2-43 Flowchart view of guarded action logical expression True Part statement -1 statement-n False After the boolean expression of the if statement evaluates, the true-part executes only when the boolean expression is true 2-44 Example if import static org.junit.Assert.*; import org.junit.Test; public class OvertimeHoursTest { @Test public void testOvertimeHours() { assertEquals(0.0, overTimeHours(38.0), assertEquals(0.0, overTimeHours(40.0), assertEquals(0.5, overTimeHours(40.5), assertEquals(2.0, overTimeHours(42.0), } 1e-12); 1e-12); 1e-12); 1e-12); } // Return 0.0 or the number of hours worked over 40.0 public double overTimeHours(double hoursWorked) { double result = 0.0; if (hoursWorked > 40.0) result = hoursWorked - 40; return result; } 2-45 Alternative Action Alternative Action Must choose one action from two alternatives if (true-or-false-condition is true) execute action-1 else execute action-2 if(finalGrade >= 60.0) System.out.println("passing"); else System.out.println("failing"); Pattern: Problem: Outline: Code Example: 2-46 if-else General Form if (boolean-expression) true-part ; else false-part ; When the boolean expression evaluates to true, the truepart executes and the false-part is disregarded. When the boolean expression is false, only the false-part executes. 2-47 The if...else statement The if...else statement allows two alternate courses of action. True statement-1 statement-n logical expression False statement-1 statement-n True Part False Part 2-48 if...else Example Write the output below if(sales >= 15000.00) System.out.println("Bonus="+((sales-15000.0)*0.05)); else System.out.println((15000.0-sales) + " short"); sales Output 16000.00 ____________________________ 2000.00 ____________________________ 15000.00 ____________________________ 2-49 import import public if...else Example with JUnit static org.junit.Assert.*; org.junit.Test; class PassFailTest { @Test public void testPassFailMessage() { assertEquals("Failing", passFailMessage(59.9)); assertEquals("Passing", passFailMessage(60.0)); assertEquals("Passing", passFailMessage(61.0)); } // Return a string to indicate pass/fail public String passFailMessage(double finalGrade) { String result = "?"; if (finalGrade < 60.0) result = "Failing"; else result = "Passing"; return result; } } 2-50 Multiple Selection Nested logic: one control structure contains another similar control structure. an if...else inside another if...else. allows selections from 3 or more alternatives We must often select one alternative from many 2-51 2-52 Example of Multiple Selection nested if...else if(GPA < 3.5) System.out.println("Try harder"); else if(GPA < 4.0) System.out.println("Dean's List"); else System.out.println("President's list"); The false part is another if...else GPA 3.0 3.6 4.0 Output: __________________ __________________ __________________ 2-53 Complete the method Given the scale below, complete this method public String weather() { // Assume my_temp is an instance variable with a nested if..else to return the appropriate message Value of my_temp C >= 34 20 <= C < 34 12 <= C < 20 0 <= C < 12 C < 0 Return this String Hot Warm Mild Cold Freezing 2-54 Multiple Returns It is possible to have multiple return statements in a method terminate when the first return executes, BUT return something public String letterGrade() { if(my_percentage >= 90.0) Error! You must return something return "A"; if(my_ percentage >= 80.0) To fix, remove return "B"; if(percentage >= 0.0) if(my_ percentage >= 70.0) return "C"; if(my_ percentage >= 60.0) return "D"; if(my_ percentage >= 0.0) return "F"; // OOPS! WRONG when percentage < 0 } 2-55 Boolean Operators A logical operator (&& means AND) used in an if...else statement: if((test >= 0) && (test <= 100)) System.out.println("Test in range"); else System.out.println("**Warning: out of range"); The code evaluates an expression to see if test is in the range of 0 through 100 inclusive 2-56 Truth Tables for Boolean Operators Truth tables for the Logical (Boolean) operators !, , && 2-57 Using && in an expression Is test within the range of 0 through 100 inclusive? Assuming test == 97, ((test >= 0) && (test <= 100)) ((97 >= 0) && (97 <= 100)) ( true && true ) true Is test outside the range of 0 through 100 inclusive? ((test < 0) (test > 100)) ((97 < 0) (97 > 100)) ( false false ) false Evaluate both expressions when test == 101 ?__? 2-58 More Precedence Rules The following slide summarizes all operators used in this textbook (we've seen 'em all now) Precedence: most operators are evaluated (grouped) in a left-to-right order: a / b / c / d is equivalent to (((a/b)/c)/d) Assignment operators group in a right-to-left order so the expression x = y = z = 0.0 is equivalent to (x=(y=(z=0.0))) 2-59 Operators we will use 2-60 Short Circuit Boolean Evaluation Java boolean expressions evaluate subexpressions in a left to right order Sometimes the evaluation could stop early This expression never evaluates the sqrt of a negative number (it only evaluates what is necessary) : if((x >= 0.0) && (Math.sqrt(x) <= 2.5)) // ... and test>100 is not evaluated when test<0 is true if(test < 0 || test > 100) // ... 2-61 Repetition 2-62 2-63 Determinate Loops This template repeats a process n times (you fill in the comments): int n = /* how often we must repeat the process */ for(int j = 1; j <= n; j = j + 1) { } // the process to be repeated determinate loops must know the number of repetitions before they begin know exactly how many employees, or students, or whatever that must be processed, for example 2-64 General Form The Java for loop for (initial statement ; looptest ; ...
View Full Document

{[ snackBarMessage ]}

What students are saying

  • Left Quote Icon

    As a current student on this bumpy collegiate pathway, I stumbled upon Course Hero, where I can find study resources for nearly all my courses, get online help from tutors 24/7, and even share my old projects, papers, and lecture notes with other students.

    Student Picture

    Kiran Temple University Fox School of Business ‘17, Course Hero Intern

  • Left Quote Icon

    I cannot even describe how much Course Hero helped me this summer. It’s truly become something I can always rely on and help me. In the end, I was not only able to survive summer classes, but I was able to thrive thanks to Course Hero.

    Student Picture

    Dana University of Pennsylvania ‘17, Course Hero Intern

  • Left Quote Icon

    The ability to access any university’s resources through Course Hero proved invaluable in my case. I was behind on Tulane coursework and actually used UCLA’s materials to help me move forward and get everything together on time.

    Student Picture

    Jill Tulane University ‘16, Course Hero Intern