11/9: Recursion, Method Overloading About Scoping.java Recursion Method overloading.

Slides:



Advertisements
Similar presentations
Drawing in a frame – Java GUI
Advertisements

1 Lecture 4: Chapter 6 - Methods Outline Introduction Program Modules in Java Math -Class Methods Method Declarations Java API Packages Random-Number Generation.
Java GUI Libraries Swing Programming. Swing Components Swing is a collection of libraries that contains primitive widgets or controls used for designing.
Chapter 7 - Arrays Outline 7.1Introduction 7.2Arrays 7.3Declaring and Allocating Arrays 7.4Examples Using Arrays 7.5References and Reference Parameters.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 25 - Beyond C & C++: Operators, Methods, and Arrays in Java Outline 25.1Introduction 25.2Primitive.
JTextArea formatting text areas. Using JTextArea JTextArea class is found in the javax.swing package. Creates an text area that can process the escape.
Mathematical Operators  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Computers and Programming in.
Event-Driven Programming
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 6 - Methods Outline 6.1 Introduction 6.2 Program Modules in Java 6.3 Math -Class Methods 6.4.
Final Review. Review A Binary Search divides a sorted data structure into two equal parts and each time throws away the part that cannot contain the item.
1 lecture 12Lecture 13 Event Handling (cont.) Overview  Handling Window Events.  Event Adapters Revisited.  Introduction to Components and Containers.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 6 - Methods Outline 6.1 Introduction 6.2 Program Modules in Java 6.3 Math -Class Methods 6.4.
Chapter Day 9. © 2007 Pearson Addison-Wesley. All rights reserved4-2 Agenda Day 8 Questions from last Class?? Problem set 2 posted  10 programs from.
1 Class 8. 2 Chapter Objectives Use Swing components to build the GUI for a Swing program Implement an ActionListener to handle events Add interface components.
Chapter 6: Graphical User Interface (GUI) and Object-Oriented Design (OOD) J ava P rogramming: Program Design Including Data Structures Program Design.
Lesson 35: Review of the Java GUI. The JFrame, Container and JButton.
Chapter 9: Applets Jim Burns Fall Outline Learn about applets Learn about applets Write an HTML doc to host an applet Write an HTML doc to host.
10/25: Methods & templates Return to concepts: methods Math class methods 1 st Program of the day About DrawLine.java modifications Method definitions.
8/9: Multiple-Subscripted Arrays About BinarySearch.java Multiple-Subscripted Arrays Program of the Day.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Java I--Copyright © 2000 Tom Hunter. Chapter 6 Methods: Part II.
Java Programming: From Problem Analysis to Program Design, Second Edition1  Learn about basic GUI components.  Explore how the GUI components JFrame,
Applets and Frames CS 21a: Introduction to Computing I First Semester,
 2002 Prentice Hall. All rights reserved. 1 Chapter 6 - Methods Outline 6.1 Introduction 6.2 Program Modules in Java 6.3 Math Class Methods 6.4 Methods.
1 Chapter 6 - Methods Outline 6.1 Introduction 6.2 Program Modules in Java 6.3 Math Class Methods 6.4 Methods 6.5 Method Definitions 6.6 Argument Promotion.
Methods Divide and conquer Programmer-declared methods Prepackaged methods – Java API Software reusability Debug-ability and maintainability AKA functions.
GUI programming Graphical user interface-based programming.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 6 - Methods.
11/15: Ch. 7: Arrays What is an array? Declaring & allocating arrays Sorting & searching arrays.
9/6: Variable Types, Arithmetic Operators, Comparison Operators Addition.java in depth Variable types & data types Input from user: how to get it Arithmetic.
习 题 4.23 编写一个 applet ,读取一个矩形的边长,然后 用在 paint 方法中使用 drawString 方法画出用星组成 的空心矩形。程序应能画出边长从 1 到 20 的任何矩 形。
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 2 - Introduction to Java Applications Outline 2.1Introduction 2.2A Simple Program: Printing a.
MSc Workshop - © S. Kamin, U. ReddyLect 3 - GUI -1 Lecture 3 - Graphical User Interfaces r GUI toolkits in Java API r JFrame r GUI components.
Chapter 6 - Methods Outline 6.1Introduction 6.3 Math Class Methods 6.4Methods 6.5Method Definitions 6.6Java API Packages 6.7Random Number Generation 6.8Example:
9/20: The while Repetition Structure last time’s program repetition structures: what they are the while repetition structure homework due on Thursday program.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 7 - Arrays Outline 7.1Introduction 7.2Arrays 7.3Declaring and Allocating Arrays 7.4Examples Using.
Layout Managers Arranges and lays out the GUI components on a container.
Applets and Frames. Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L14: GUI Slide 2 Applets Usually.
1/28: Inputs, Variable Types, etc. Addition.java in depth Variable types & data types Input from user: how to get it Arithmetic operators.
3/25: Scope Rules, More Methods about RollDie.java & modifications Scope rules More methods Program of the day.
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
1 GUI programming Graphical user interface-based programming Chapter G1 (pages )
Java Programming: From Problem Analysis to Program Design, 3e Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
4/17: Multiple-Subscripted Arrays About BinarySearch.java Multiple-Subscripted Arrays Program of the Day.
1 Chapter 3 – Object-Based Programming 2 Initializing Class Objects: Constructors Class constructor is a specical method to initialise instance variables.
11/2: Math.random, more methods About DrawLine.java modifications –allow user input –draw a curve Method definitions Math.random()
Java Programming: From Problem Analysis to Program Design, Second Edition1 Lecture 5 Objectives  Learn about basic GUI components.  Explore how the GUI.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 6 - Methods Outline 6.1Introduction 6.2Program Modules in Java 6.3 Math Class Methods 6.4Methods.
Graphical User Interfaces A Graphical User Interface (GUI) in Java is created with at least three kinds of objects: –components, events, and listeners.
Architectural Patterns Support Lecture Patterns Pattern: A representation of a proven solution. Problem Applicable Forces Solution Consequences Benefits.
11/30: Sorting and Searching Arrays Look at PassArray.java Sorting arrays: the bubble sort method Searching arrays: the linear search Searching arrays:
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "___________________" in Java Purpose –Reuse code –Modularize.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 6 – Methods Part I.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 6 - Methods Outline 6.1 Introduction 6.2 Program Modules in Java 6.3 Math -Class Methods 6.4.
Lesson 28: More on the GUI button, frame and actions.
Event Handling CS 21a: Introduction to Computing I First Semester,
Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
8/2: Recursion About Scoping.java Recursion Program of the Day.
Applets. 9/04/2005 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L12: Applets Slide 2 Applets Usually.
MIT AITI 2004 Swing Event Model Lecture 17. The Java Event Model In the last lecture, we learned how to construct a GUI to present information to the.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
Introduction Many Java application use a graphical user interface or GUI (pronounced “gooey”). A GUI is a graphical window or windows that provide interaction.
Java Applet What is a Java Applet? How is applet compiled?
“Form Ever Follows Function” Louis Henri Sullivan
2.5 Another Java Application: Adding Integers
Java Programming: From Problem Analysis to Program Design,
Ellen Walker Hiram College
Chapter 6 - Methods Outline 6.1 Introduction 6.2 Program Modules in Java 6.3 Math Class Methods 6.4 Methods 6.5 Method Definitions 6.6 Argument.
Graphical user interface-based programming
Constructor Laboratory /12/4.
Presentation transcript:

11/9: Recursion, Method Overloading About Scoping.java Recursion Method overloading

Scoping.java pt.1 //Fig. 6.10: Scoping.java -- A scoping example import java.awt.Container; import javax.swing.*; public class Scoping extends JApplet { JTextArea outputArea; int x = 1; //note: an instance variable public void init () { outputArea = new JTextArea(); Container c = getContentPane(); c.add ( outputArea ); }

Scoping.java pt.2 public void start () { int x = 5; //note: a local variable with the same name. outputArea.append ( "local x in start is " + x ); methodA(); //methodA has automatic local x methodB(); //methodB uses instance variable x methodA(); //methodA reinitializes automatic local x methodB(); //instance variable x retains its value outputArea.append ( "\n\nlocal x in start is " + x ); }

Scoping.java pt.3 public void methodA() { int x = 25; //initialized each time methodA is called. outputArea.append( "\n\nlocal x in methodA is " + x + " after entering methodA" ); ++x; outputArea.append( "\nlocal x in methodA is " + x + " before exiting methodA" ); }

Scoping.java pt.4 public void methodB() { outputArea.append ( "\n\ninstance variable x is " + x + " on entering methodB" ); x *= 10; outputArea.append ( "\ninstance variable x is " + x + " on exiting methodB" ); }

Recursion Somewhat like iteration A recursive method calls itself. EX from math: factorial: n! = n * ( n - 1 ) ! EX: finding a name in phone book –go to the middle of the phone book. –if name is before that page, go to middle of front half –if name is before that page, go to middle of front half of front half –if name is before that page, go to middle of front half of front half of front half...

Example: countZeros.java pt. 1 //Counting zeros: a recursion example import javax.swing.JOptionPane; public class CountZeros { public static void main ( String args [] ) { int number, zeros; number = Integer.parseInt ( JOptionPane.showInputDialog ( "Give me an integer. I'll count the zeros for you." ) ); zeros = count0s( number ); JOptionPane.showMessageDialog ( null, "The number " + number + " has " + zeros + " zeros in it." ); System.exit ( 0 ); }

Example: countZeros.java pt. 2 public static int count0s ( int n ) //called by the method above { if ( n == 0 ) return 1; else if ( n < 10 ) //and not zero, mind you return 0; else if ( n % 10 == 0 ) //remainder of n/10 return ( count0s ( n / 10 ) + 1 ); else //n%10 is not = to zero return ( count0s ( n / 10 ) ); }

Notes about Recursive Methods base case (or stopping case) –last one to be evaluated –must exist for recursion to end. Without it, the recursion is endless (and the program won’t stop.) –EX: factorial: n! = n * ( n - 1 ) ! –the base case would be 2 * 1 –factorials, by definition, stop at 1: 0! = 1, 1! = 1

Memory Issue: Recursive Methods Java stores all values generated along the way: –Java calculating factorial of 6 : 6! = 6 * (6 - 1 )! = 720 = 5 * ( )! = 120 = 4 * ( )! = 24 = 3 * ( )! = 6 = 2 * ( )! = 2 = 1 Java stores these values in a stack.

Recursive vs. Iterative Methods Any recursive method can be rewritten as an iterative method. Why use recursion, then? –recursion may mimic the problem at hand better. –iterative solutions may not be obvious.

1 st Program of the day pg. 239 FibonacciTest.java

FibonacciTest: JTextField, JLabel import java.awt.*; import java.awt.event.*; import javax.swing.*; public class FibonacciTest extends JApplet implements ActionListener { JLabel numLabel, resultLabel; JTextField num, result; public void init() { Container c = getContentPane(); c.setLayout ( new FlowLayout() );

FibonacciTest: JTextField, JLabel numLabel = new JLabel ("Enter int. & press enter:"); c.add ( numLabel ); num = new JTextField ( 10 ); num.addActionListener( this ); c.add ( num ); resultLabel = new JLabel ( "Fibonacci value is:" ); c.add ( resultLabel ); result = new JTextField ( 10 ); result.setEditable ( false ); c.add ( result ); }

JLabels & JTextFields JLabel s: text labels intended for use with input fields. JTextField s: input fields that accept String -type values. have to be added to containers (Applet windows, frames, etc.): c.add ( numlabel );

actionPerformed method num.addActionListener( this ); //from above public void actionPerformed ( ActionEvent e ) { long number, fValue; number = Long.parseLong(num.getText()); showStatus ( "Calculating..." ); fValue = fibonacci ( number ); showStatus ( "Done." ); result.setText ( Long.toString ( fValue ) ); }

JLabels & JTextFields JLabel s: text labels intended for use with input fields. JTextField s: input fields that accept String -type values. have to be added to containers (Applet windows, frames, etc.): c.add ( numlabel );

actionPerformed method Used to respond to user’s actions ( pressing the enter key, clicking a key on the keyboard, etc.) Must have an actionListener added to the JTextField, etc. to be used. (Have to know what to listen to for actions.) Note the parameter “ ActionEvent e ”. See similarity with parameter for paint method “ Graphics g ”.

recursive Fibonacci method Fibonacci series: 0, 1, 1, 2, 3, 5, 8, 13, 21, … add the previous two numbers in the series to get next number. “the golden ratio” series describes a spiral of sorts. number fibonacci value

recursive Fibonacci method //Recursive definition of method fibonacci public long fibonacci ( long n ) { if ( n == 0 || n == 1 ) //base case return n; else return fibonacci ( n - 1 ) + fibonacci ( n - 2 ); } number fibonacci value

Method Overloading Naming two methods with the same name Signatures differ: methods have the same name, but the input types are different Examples are plentiful: –JOptionPane.showMessageDialog ( null, String ); –JOptionPane.showMessageDialog ( null, String, String, icon_type ); Why do it? –creating certain types of output based on input types –allowing for different types of input to occur

Method Overloading public int root ( int a ) { return (int) Math.sqrt ( a ); } public double root ( double a ) { return Math.sqrt ( a ); }

2 nd Program of the Day MethodOverload.java – pg. 245 After you get it to run, modify it to return an int -type value with a double -type input and a double -type value with an int -type input. Don’t forget: Quiz #4 (last one!) on Thursday. guaranteed programs: scope & recursion.