Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSE 501N Fall ’09 07: Iteration 17 September 2009 Nick Leidenfrost.

Similar presentations


Presentation on theme: "CSE 501N Fall ’09 07: Iteration 17 September 2009 Nick Leidenfrost."— Presentation transcript:

1 CSE 501N Fall ’09 07: Iteration 17 September 2009 Nick Leidenfrost

2 2 Lecture Outline Loops NullPointerExceptions Lab 2 Overview

3 3 Repetition Statements Iteration Repetition statements allow us to execute a statement multiple times Repetitive statements are referred to as loops Like conditional statements, they are controlled by boolean expressions Java (like other C-based languages) has three kinds of repetition statements:  the while loop  the do loop  the for loop The programmer should choose the right kind of loop for the situation

4 4 The while Statement A while statement has the following syntax: while ( condition ) statement; If the condition is true, the statement is executed Then the condition is evaluated again, and if it is still true, the statement is executed again The statement is executed repeatedly until the condition becomes false Boolean-valued expression

5 5 Control flow of a while Loop statement true false condition evaluated

6 6 The while Statement Like the if statement, a while statement can have a block statement as the statement it conditionally controls Allows the repetition of multiple statements while ( condition ) { // Statements }

7 7 The while Statement An example of a while statement: int count = 1; while (count <= 5) { System.out.println(count); count++; } What is the output of the while loop above? If the condition of a while loop is false initially, the statement is never executed Therefore, the body of a while loop will execute zero or more times

8 8 Infinite Loops The body of a while loop eventually must* make the condition false If not, it is called an infinite loop, which will execute until the user terminates the program*  (* Or some control statement cause the loop to exit) This is most often a logical error You should always double check the logic of a program to ensure that your loops will terminate normally [Example of an infinite loop – Nested if ]

9 9 Nested Loops Similar to nested if statements, loops can be nested as well That is, the body of a loop can contain another loop For each iteration of the outer loop, the inner loop iterates completely  Print a list of numbers which are the sum of numbers from 1 - 10, 11 - 20, …, 91 - 100. [Example on board] while ( condition ) { statements; }

10 10 Nested Loops How many times will the string "Here" be printed? count1 = 1; while (count1 <= 10) { count2 = 1; while (count2 <= 20) { System.out.println("Here"); count2++; } count1++; } 10 * 20 = 200

11 11 The do Statement A do statement has the following syntax: do { statement; } while ( condition ); The statement is executed once initially, and then the condition is evaluated The statement is executed repeatedly until the condition becomes false

12 12 Control flow of a do Loop true condition evaluated statement false

13 13 The do Statement An example of a do loop: The body of a do loop executes at least once  A do loop executes one or more times int count = 4; do { count++; System.out.println(count); } while (count < 5);

14 14 Comparing while and do statement true false condition evaluated The while Loop true condition evaluated statement false The do Loop

15 15 The for Statement A for statement has the following syntax: for ( initialization ; condition ; increment ) statement; The initialization is executed once before the loop begins The statement is executed until the condition becomes false The increment portion is executed at the end of each iteration

16 16 Logic of a for loop statement true condition evaluated false increment initialization

17 17 The for Statement A for loop is functionally equivalent to the following while loop structure: Example on the board - Translating for loops to while loops initialization; while ( condition ) { statements; increment; }

18 18 The for Statement An example of a for loop: for (int i=1; i <= 5; i++) System.out.println(i); The initialization section can be used to declare and/or initialize a variable Like a while loop, the condition of a for loop is tested prior to executing the loop body Therefore, the body of a for loop will execute zero or more times

19 19 The for Statement Increment The increment section can perform any calculation What’s with the variable name i, anyway? for (int i=100; i > 0; i -= 5) System.out.println(num);

20 20 The for Statement Each expression in the header of a for loop is optional If the initialization is left out, no initialization occurs If the condition is left out, it is always considered to be true, and therefore creates an infinite loop If the increment is left out, no increment operation occurs for (int count=1; count <= 5; count++) System.out.println (count); int count = 1; for (; count <= 5; count++) System.out.println(count); int count = 1; for (; ; count++) System.out.println (count); int count = 1; for (; ; ) System.out.println(count);

21 21 Loops When to Use Each? The Important thing is to make the repetitive statement comply to your logic, and not the other way around. while  When loop will execute an arbitrary number of times (0 or more) do / while  When loop will execute an arbitrary number of times, but at least once for  When loop will execute a specific number of times that can be calculated or determined in advance Number of times is a constant, e.g. 100 Number of times is contained in some variable

22 22 NullPointerExceptions Bad Programmer! No Cookie! NullPointerExceptions occur when a method is invoked or a field is referenced on an object variable that refers to null NullPointerExceptions are Runtime Errors, meaning they cannot be detected at compile-time before the program executes  Occur at runtime Most of the time, Runtime Errors (such as NullPointerExceptions) are due to programmer error BankAccount account; account.getBalance(); account.balance = 0.0; null

23 23 NullPointerExceptions The Aftermath NullPointerExceptions print a stack trace to the console and usually terminate your program // BankAccount.java void transfer (BankAccount other, double amount) { other.withDraw(amount) this.deposit(amount); } Exception in thread "main" java.lang.NullPointerException at MyBankApp.main(MyBankApp.java:12) // MyBankApp.java BankAccount one; BankAccount two; one.transfer(two, 1000); // MyBankApp.java BankAccount one; BankAccount two; one = new BankAccount(5000); one.transfer(two, 1000); Exception in thread "main" java.lang.NullPointerException at BankAccount.transfer(BankAccount.java:37) at MyBankApp.main(MyBankApp.java:13)

24 24 NullPointerExceptions Anatomy of a Stack Trace A stack trace tells you where an exception occurred, and context in which it occurred Exception in thread "main" java.lang.NullPointerException at BankAccount.transfer(BankAccount.java:37) at MyBankApp.main(MyBankApp.java:13) The type of exception that occurred The class and method in which the exception occurred The file in which the exception occurred The line number at which the exception occurred The method that called the method where the exception occurred (the call stack)

25 25 NullPointerExceptions Anatomy of a Stack Trace A stack trace may consist of numerous calling methods: The stack trace above tells us that the main method invoked…  executeATMCommand on line 13 which invoked…  doService on line 83 which invoked…  transfer on a BankAccount object at line 27  Wherein the exception occurred at line 37 of BankAccount.java Exception in thread "main" java.lang.NullPointerException at BankAccount.transfer(BankAccount.java:37) at MyBankApp.doService(MyBankApp.java:27) at MyBankApp.executeATMCommand(MyBankApp.java:83) at MyBankApp.main(MyBankApp.java:13)

26 26 NullPointerExceptions Some Common Causes Sometimes the problem caused by the direct use of an object variable that has not been initialized public static void main (String[] args) { BankAccount accountOne; BankAccount accountTwo = new BankAccount(10000); accountOne.transfer(accountTwo, 5000); } Exception in thread "main" java.lang.NullPointerException at MyBankApp.main(MyBankApp.java:13)

27 27 NullPointerExceptions Some Common Causes Sometimes the problem is the fault of the method that called the method where the exception occurs: public void transfer (BankAccount other, double amount) { other.withdraw(amount); this.balance += interest; } Exception in thread "main" java.lang.NullPointerException at BankAccount.transfer(BankAccount.java:37) at MyBankApp.main(MyBankApp.java:13)

28 28 NullPointerExceptions Some Common Causes Forgetting to initialize an object instance variable in the constructor: public class BankAccount { protected Bank bank protected double interest; public BankAccount (Bank bank, double balance) { } public void awardInterest () { double interest = bank.calculateInterest(this); this.balance += interest; } bank = bank; this.bank = bank; This method invocation results in a NullPointerException because bank is null

29 29 NullPointerExceptions … And the this Reference public void transferAll (BankAccount other) { this.transfer(other, other.getBalance()); } public void transfer (BankAccount other, double balance) { // … transfer logic … } Exception in thread "main" java.lang.NullPointerException at BankAccount.transferAll(BankAccount.java:37) at MyBankApp.main(MyBankApp.java:13) How do we know this is not the null reference?  The NullPointerException would have been preempted by another NullPointerException…  this can never refer to null.

30 30 NullPointerExceptions With Multiple Suspects public void transferAll (BankAccount from, BankAccount to) { to.transfer(from, from.getBalance()); } Exception in thread "main" java.lang.NullPointerException at MyBankApp.transferAll(MyBankApp.java:98) at MyBankApp.main(MyBankApp.java:13)

31 31 Lab 2 SimBee Grid-based Turn-Based Coordinates / Vectors

32 32 Conclusion Questions? Lab 2 Assigned Now  More difficult than 1 & 1.5 Get Started Early  Due Tuesday, Sept. 29 I will be in Lab now


Download ppt "CSE 501N Fall ’09 07: Iteration 17 September 2009 Nick Leidenfrost."

Similar presentations


Ads by Google