 2000 Prentice Hall, Inc. All rights reserved. Chapter 25 - Beyond C & C++: Operators, Methods, and Arrays in Java Outline 25.1Introduction 25.2Primitive.

Slides:



Advertisements
Similar presentations
 2005 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Advertisements

1 Programmer-Defined Functions Functions allow program modularization Variables declared in function are local variables Only known inside function in.
Page 1 of 26 Javascript/Jscript Ch 7,8,9,10 Vadim Parizher Computer Science Department California State University, Northridge Spring 2003 Slides from.
Deitel Ch 11-part 1 Java GUIs 1 Java GUIs (Deitel, Chap 14-part1) Focus: Attaching GUI components + event handling  input dialog => only one value for.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 15.1 Test-Driving the Craps Game Application.
A Java API Package java.security  The Java Security Package contains classes and interfaces that are required by many Java programs.  This package is.
1 Lecture 4: Chapter 6 - Methods Outline Introduction Program Modules in Java Math -Class Methods Method Declarations Java API Packages Random-Number Generation.
 2003 Prentice Hall, Inc. All rights reserved. 7.1 Introduction Arrays –Data structures which reference one or more value –All items must have same data.
Chapter 7 - Arrays Outline 7.1Introduction 7.2Arrays 7.3Declaring and Allocating Arrays 7.4Examples Using Arrays 7.5References and Reference Parameters.
Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition 5.3The for Repetition Structure 5.4Examples.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions.
Introduction to Computers and Programming Lecture 12: Math.random() Professor: Evan Korth New York University.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
Math class methods & User defined methods Math class methods Math.sqrt(4.0) Math.random() java.lang is the library/package that provides Math class methods.
 2007 Pearson Education, Inc. All rights reserved C Functions.
 2003 Prentice Hall, Inc. All rights reserved. Chapter 7 - Arrays Outline 7.1 Introduction 7.2 Arrays 7.3 Declaring and Creating Arrays 7.4 Examples Using.
 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.
 2007 Pearson Education, Inc. All rights reserved C Functions.
Review for Midterm 2 Nested loops & Math class methods & User defined methods.
Outline IS400: Development of Business Applications on the Internet Fall 2004 Instructor: Dr. Boris Jukic JavaScript: Functions 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.
 2003 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Arrays Introduction to Computers and Programming in.
C Lecture Notes Functions (Cont...). C Lecture Notes 5.8Calling Functions: Call by Value and Call by Reference Used when invoking functions Call by value.
1 JavaScript/Jscript 4 Functions. 2 Introduction Programs that solve real-world programs –More complex than programs from previous chapters Best way to.
 2004 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3.
1 Lecture 3 Part 1 Functions with math and randomness.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 16.1 Test-Driving the Flag Quiz Application.
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3.
Java I--Copyright © 2000 Tom Hunter. Chapter 6 Methods: Part II.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3.
11/9: Recursion, Method Overloading About Scoping.java Recursion Method overloading.
 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.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 – Control Structures: Part 2 Outline 5.1 Introduction 5.2 Essentials of Counter-Controlled.
 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.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Part II © Copyright by Pearson Education, Inc. All Rights Reserved.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 2 - Introduction to Java Applications Outline 2.1Introduction 2.2A Simple Program: Printing a.
Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions 5.5Function Definitions 5.6Function Prototypes.
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:
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 7 - Arrays Outline 7.1Introduction 7.2Arrays 7.3Declaring and Allocating Arrays 7.4Examples Using.
 2001 Deitel & Associates, Inc. All rights reserved. 1 Outline 16.1Introduction 16.2Program Modules in JavaScript 16.3Programmer-Defined Functions 16.4Function.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 6 - Functions.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Introduction Arrays Declaring Arrays Examples Using Arrays.
3/25: Scope Rules, More Methods about RollDie.java & modifications Scope rules More methods Program of the day.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
11/2: Math.random, more methods About DrawLine.java modifications –allow user input –draw a curve Method definitions Math.random()
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 – Control Structures: Part 2 Outline 5.1 Introduction 5.2 Essentials of Counter-Controlled.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 7 - Arrays Outline 7.1 Introduction 7.2 Arrays 7.3 Declaring and Creating Arrays 7.4 Examples.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 24.1 Test-Driving the Enhanced Car Payment.
 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.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Craps Game Application Introducing Random-Number Generation and Enum.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Tutorial 4 – Completing the Inventory Application.
 2000 Prentice Hall, Inc. All rights reserved. 5.2Program Modules in C Functions –Modules in C –Programs combine user-defined functions with library functions.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 5.1 Test-Driving the Enhanced Inventory Application.
Review for Nested loops & Math class methods & User defined methods.
11/30: Sorting and Searching Arrays Look at PassArray.java Sorting arrays: the bubble sort method Searching arrays: the linear search Searching arrays:
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 25 - Beyond C & C++: Operators, Methods, and.
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.
 2000 Prentice Hall, Inc. All rights reserved Introduction Divide and conquer –Construct a program from smaller pieces or components –Each piece.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 17.1 Test-Driving the Student Grades Application.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 7.1 Test-Driving the Dental Payment Application.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
Lecture 4: Chapter 7 - Arrays Outline Declaring and Creating Arrays Examples Using Arrays References and Reference Parameters Passing Arrays to Methods.
“Form Ever Follows Function” Louis Henri Sullivan
Chapter 5 – Control Structures: Part 2
Presentation transcript:

 2000 Prentice Hall, Inc. All rights reserved. Chapter 25 - Beyond C & C++: Operators, Methods, and Arrays in Java Outline 25.1Introduction 25.2Primitive Data Types and Keywords 25.3Logical Operators 25.4Method Definitions 25.5Java API Packages 25.6Random Number Generation 25.7Example: A Game of Chance 25.8Methods of Class JApplet 25.9Declaring and Allocating Arrays 25.10Examples Using Arrays 25.11References and Reference Parameters 25.12Multiple-Subscripted Arrays

 2000 Prentice Hall, Inc. All rights reserved. 25.1Introduction In this chapter –Differences between C, C++, and Java –Java's logical operators and methods –Packages that comprise Applications Programming Interface (API) –Craps simulator –Random numbers in Java –Arrays in Java

 2000 Prentice Hall, Inc. All rights reserved. 25.2Primitive Data Types and Keywords Primitive data types – char, byte, short, int, long, float, double, boolean –Building blocks for more complicated types All variables must have a type before being used Strongly typed language –Primitive types portable, unlike C and C++ In C/C++, write different versions of programs –Data types not guaranteed to be identical –int s may be 2 or 4 bytes, depending on system WORA - Write once, run anywhere –Default values boolean gets false, all other types are 0

 2000 Prentice Hall, Inc. All rights reserved. 25.2Primitive Data Types and Keywords (II)

 2000 Prentice Hall, Inc. All rights reserved. 25.2Primitive Data Types and Keywords (III) Keywords –Reserved names, cannot be used as identifiers –Used to implement features

 2000 Prentice Hall, Inc. All rights reserved. 25.3Logical Operators Logical operators –Form complex conditions and control structures –Logical AND ( && ) true if both conditions true –Logical OR ( || ) true if either condition true true if both conditions true (inclusive) If left condition true, skips right condition –Boolean logical AND (&), boolean logical inclusive OR ( | ) Act like counterparts, but always evaluate both expressions Useful if expression performs action: birthday == true | ++age >= 65

 2000 Prentice Hall, Inc. All rights reserved. 25.3Logical Operators (II) Logical Operators (continued) –Boolean logical exclusive OR ( ^ ) true if exactly one condition true false if both conditions true –Logical NOT (negation) Unary operator (one operand) –All other logical operators binary (two operands) Reverses condition If true, returns false If false, returns true != - "does not equal" if (grade != sentinelValue)

 2000 Prentice Hall, Inc. All rights reserved. 25.3Logical Operators (III) More GUI Classes ( javax.swing ) –JTextArea Create an area where text can be displayed Provide (rows, columns) to constructor to specify size JTextArea myArea; //declares object type myArea = new JTextArea( 17, 20 ); //initialize –myArea.setText( myString ); Sets the text of myArea to myString –JScrollPane Creates a window that can scroll JScrollPane myScroller = new JScrollPane ( myArea ); Declaration and initialization, allows myArea have scrolling

 2000 Prentice Hall, Inc. All rights reserved. 25.3Logical Operators (IV) More GUI classes –showMessageDialog(null, myScroller, titleString, type); Second argument indicates that myScroller (and attached myArea ) should be displayed in message dialog

 2000 Prentice Hall, Inc. All rights reserved. Outline 1. Class definition 1.1 Initialize objects ( JTextArea, JScrollPane ) 1.2 Declare String 1.3 Append logical operator statements 1// Fig. 25.7: LogicalOperators.java 2// Demonstrating the logical operators 3import javax.swing.*; 4 5public class LogicalOperators { 6 public static void main( String args[] ) 7 { 8 JTextArea outputArea = new JTextArea( 17, 20 ); 9 JScrollPane scroller = new JScrollPane( outputArea ); 10 String output = ""; output += "Logical AND (&&)" + 13 "\nfalse && false: " + ( false && false ) + 14 "\nfalse && true: " + ( false && true ) + 15 "\ntrue && false: " + ( true && false ) + 16 "\ntrue && true: " + ( true && true ); output += "\n\nLogical OR (||)" + 19 "\nfalse || false: " + ( false || false ) + 20 "\nfalse || true: " + ( false || true ) + 21 "\ntrue || false: " + ( true || false ) + 22 "\ntrue || true: " + ( true || true ); output += "\n\nBoolean logical AND (&)" + 25 "\nfalse & false: " + ( false & false ) + 26 "\nfalse & true: " + ( false & true ) + 27 "\ntrue & false: " + ( true & false ) + 28 "\ntrue & true: " + ( true & true ); output += "\n\nBoolean logical inclusive OR (|)" +

 2000 Prentice Hall, Inc. All rights reserved. Outline 2. Add output to outputArea 2.1 showMessageDialog (notice second argument) 2.2 System.exit required for programs with GUIs 31 "\nfalse | false: " + ( false | false ) + 32 "\nfalse | true: " + ( false | true ) + 33 "\ntrue | false: " + ( true | false ) + 34 "\ntrue | true: " + ( true | true ); output += "\n\nBoolean logical exclusive OR (^)" + 37 "\nfalse ^ false: " + ( false ^ false ) + 38 "\nfalse ^ true: " + ( false ^ true ) + 39 "\ntrue ^ false: " + ( true ^ false ) + 40 "\ntrue ^ true: " + ( true ^ true ); output += "\n\nLogical NOT (!)" + 43 "\n!false: " + ( !false ) + 44 "\n!true: " + ( !true ); outputArea.setText( output ); 47 JOptionPane.showMessageDialog( null, scroller, 48 "Truth Tables", JOptionPane.INFORMATION_MESSAGE ); 49 System.exit( 0 ); 50 } 51}

 2000 Prentice Hall, Inc. All rights reserved. Outline Program Output

 2000 Prentice Hall, Inc. All rights reserved. 25.4Method Definitions Method definition format return-value-type method-name ( parameter-list ) { declarations and statements } –Method-name: any valid identifier –Return-value-type: data type of the result void - method returns nothing Can return at most one value –Parameter-list: comma separated list, declares parameters Method call must have proper number and type of parameters –Declarations and statements: method body (block) Variables can be declared inside blocks (can be nested) Method cannot be defined inside another function

 2000 Prentice Hall, Inc. All rights reserved. 25.4Method Definitions (II) Program control –When method call encountered Control transferred from point of invocation to method –Returning control If nothing returned: return; –Or until reaches right brace If value returned: return expression ; –Returns the value of expression –Example user-defined method: public int square( int y ) { return y * y }

 2000 Prentice Hall, Inc. All rights reserved. 25.4Method Definitions (III) Calling methods –Three ways Method name and arguments –Can be used by methods of same class –square( 2 ); Dot operator - used with objects –g.drawLine( x1, y1, x2, y2 ); Dot operator - used with static methods of classes –Integer.parseInt( myString ); –More Chapter 26

 2000 Prentice Hall, Inc. All rights reserved. 25.4Method Definitions (IV) More GUI components –Content Pane - on-screen display area Attach GUI components to it to be displayed Object of class Container ( java.awt ) –getContentPane Method inherited from JApplet Returns reference to Content Pane Container c = getContentPane(); –Container method add Attaches GUI components to content pane, so they can be displayed For now, only attach one component (occupies entire area) Later, learn how to add and layout multiple components c.add( myTextArea );

 2000 Prentice Hall, Inc. All rights reserved. Outline 1. init 1.1 Initialize variables 1.2 JTextArea object 1.3 Container object 1.4 Attach outputArea to Content Pane 2. Call method 2.1 Set text of output 1// Fig. 25.8: SquareInt.java 2// A programmer-defined square method 3import java.awt.Container; 4import javax.swing.*; 5 6public class SquareInt extends JApplet { 7 public void init() 8 { 9 String output = ""; JTextArea outputArea = new JTextArea( 10, 20 ); // get the applet's GUI component display area 14 Container c = getContentPane(); // attach outputArea to Container c 17 c.add( outputArea ); int result; for ( int x = 1; x <= 10; x++ ) { 22 result = square( x ); 23 output += "The square of " + x + 24 " is " + result + "\n"; 25 } outputArea.setText( output ); 28 } // square method definition

 2000 Prentice Hall, Inc. All rights reserved. Outline 3. Method definition Program Output 31 public int square( int y ) 32 { 33 return y * y; 34 } 35}

 2000 Prentice Hall, Inc. All rights reserved. 25.5Java API Packages As we have seen –Java has predefined, grouped classes called packages –Together, all the packages are the Applications Programming Interface (API) –Fig has a list of the packages in the API Import –Import statements specify location of classes –Large number of classes, avoid reinventing the wheel

 2000 Prentice Hall, Inc. All rights reserved. 25.6Random Number Generation Math.random() –Returns a random double, greater than or equal to 0.0, less than 1.0 Scaling and shifting n = a + (int) ( Math.random() * b ) n = random number a = shifting value b = scaling value In C we used %, but in Java we can use * For a random number between 1 and 6, n = 1 + (int) ( Math.random() * 6 )

 2000 Prentice Hall, Inc. All rights reserved. 25.7Example: A Game of Chance Redo "craps" simulator from Chapter 5 Rules –Roll two dice 7 or 11 on first throw, player wins 2, 3, or 12 on first throw, player loses 4, 5, 6, 8, 9, 10 - value becomes player's "point" –player must roll his point before rolling 7 to win

 2000 Prentice Hall, Inc. All rights reserved. 25.7Example: A Game of Chance (II) User input –Till now, used message dialog and input dialog Tedious, only show one message/ get one input at a time –Now, we will use event handling for more complex GUI extends keyword –Class inherits data and methods from another class –A class can also implement an interface Keyword implements Interface - specifies methods you must define in your class Event handling –Event: user interaction (i.e., user clicking a button) –Event handler: method called in response to an event

 2000 Prentice Hall, Inc. All rights reserved. 25.7Example: A Game of Chance (III) Interface ActionListener –Requires that you define method actionPerformed actionPerformed is the event handler Class JTextField –Can display or input a line of text Class JButton –Displays a button which can perform an action if pushed –Method addActionListener( this ); Specifies this applet should listen for events from the JButton object –Each component must know which method will handle its events Registering the event handler

 2000 Prentice Hall, Inc. All rights reserved. 25.7Example: A Game of Chance (IV) Class JButton (continued) –We registered this applet with our JButton The applet "listens" for events from the –actionPerformed is the event handler Event-driven programming –User's interaction with GUI drives program final –Declares a variable constant Cannot be modified Must be initialized at declaration const int MYINT = 3; Use all uppercase for final variables

 2000 Prentice Hall, Inc. All rights reserved. 25.7Example: A Game of Chance (V) Methods of class Container –Recall that the Content Pane is of class Container –Method setLayout Define layout managers (determine position and size of all components attached to container) FlowLayout - Most basic layout manager –Items placed left to right in order added to container –When end of line reached, continues on next line c = getContentPane(); c.setLayout( new FlowLayout() ); Initialized with object of class FlowLayout

 2000 Prentice Hall, Inc. All rights reserved. Outline 1. import 2. Define class ( implements ) 2.1 Initialize variables and objects 2.2 setLayout 1// Fig : Craps.java 2// Craps 3import java.awt.*; 4import java.awt.event.*; 5import javax.swing.*; 6 7public class Craps extends JApplet implements ActionListener { 8 // constant variables for status of game 9 final int WON = 0, LOST = 1, CONTINUE = 2; // other variables used in program 12 boolean firstRoll = true; // true if first roll 13 int sumOfDice = 0; // sum of the dice 14 int myPoint = 0; // point if no win/loss on first roll 15 int gameStatus = CONTINUE; // game not over yet // graphical user interface components 18 JLabel die1Label, die2Label, sumLabel, pointLabel; 19 JTextField firstDie, secondDie, sum, point; 20 JButton roll; // setup graphical user interface components 23 public void init() 24 { 25 Container c = getContentPane(); 26 c.setLayout( new FlowLayout() ); die1Label = new JLabel( "Die 1" ); 29 c.add( die1Label ); 30 firstDie = new JTextField( 10 );

 2000 Prentice Hall, Inc. All rights reserved. Outline 2.3 add components to GUI 2.4 addActionListener 3. Define actionPerformed (event handler) 31 firstDie.setEditable( false ); 32 c.add( firstDie ); die2Label = new JLabel( "Die 2" ); 35 c.add( die2Label ); 36 secondDie = new JTextField( 10 ); 37 secondDie.setEditable( false ); 38 c.add( secondDie ); sumLabel = new JLabel( "Sum is" ); 41 c.add( sumLabel ); 42 sum = new JTextField( 10 ); 43 sum.setEditable( false ); 44 c.add( sum ); pointLabel = new JLabel( "Point is" ); 47 c.add( pointLabel ); 48 point = new JTextField( 10 ); 49 point.setEditable( false ); 50 c.add( point ); roll = new JButton( "Roll Dice" ); 53 roll.addActionListener( this ); 54 c.add( roll ); 55 } // call method play when button is pressed 58 public void actionPerformed( ActionEvent e ) 59 { 60 play();

 2000 Prentice Hall, Inc. All rights reserved. Outline 3.1 Define play 3.2 switch 61 } // process one roll of the dice 64 public void play() 65 { 66 if ( firstRoll ) { // first roll of the dice 67 sumOfDice = rollDice(); switch ( sumOfDice ) { 70 case 7: case 11: // win on first roll 71 gameStatus = WON; 72 point.setText( "" ); // clear point text field 73 break; 74 case 2: case 3: case 12: // lose on first roll 75 gameStatus = LOST; 76 point.setText( "" ); // clear point text field 77 break; 78 default: // remember point 79 gameStatus = CONTINUE; 80 myPoint = sumOfDice; 81 point.setText( Integer.toString( myPoint ) ); 82 firstRoll = false; 83 break; 84 } 85 } 86 else { 87 sumOfDice = rollDice(); if ( sumOfDice == myPoint ) // win by making point 90 gameStatus = WON;

 2000 Prentice Hall, Inc. All rights reserved. Outline 3.3 Define rollDice 91 else 92 if ( sumOfDice == 7 ) // lose by rolling 7 93 gameStatus = LOST; 94 } if ( gameStatus == CONTINUE ) 97 showStatus( "Roll again." ); 98 else { 99 if ( gameStatus == WON ) 100 showStatus( "Player wins. " "Click Roll Dice to play again." ); 102 else 103 showStatus( "Player loses. " "Click Roll Dice to play again." ); firstRoll = true; 107 } 108 } // roll the dice 111 public int rollDice() 112 { 113 int die1, die2, workSum; die1 = 1 + ( int ) ( Math.random() * 6 ); 116 die2 = 1 + ( int ) ( Math.random() * 6 ); 117 workSum = die1 + die2; firstDie.setText( Integer.toString( die1 ) ); 120 secondDie.setText( Integer.toString( die2 ) );

 2000 Prentice Hall, Inc. All rights reserved. Outline Program Output 121 sum.setText( Integer.toString( workSum ) ); return workSum; 124 } 125}

 2000 Prentice Hall, Inc. All rights reserved. 25.8Methods of Class JApplet Methods of Class JApplet –init, start, stop, paint, destroy –Called automatically during execution –By default, have empty bodies –Must define yourself, using proper first line Otherwise, will not be called automatically See Figure for proper first lines Method repaint –Dynamically change appearance of applet –Cannot call paint (do not have a Graphics object) –repaint(); calls update which passes Graphics object for us Erases previous drawings and calls paint

 2000 Prentice Hall, Inc. All rights reserved. 25.8Methods of Class JApplet (II) First line of JApplet methods (descriptions Fig ) public void init() public void start() public void paint( Graphics g ) public void stop() public void destroy()

 2000 Prentice Hall, Inc. All rights reserved. 25.9Declaring and Allocating Arrays Arrays –Specify type, use new operator –Two steps: int c[]; //declaration c = new int[ 12 ]; //initialization –One step: int c[] = new int[12]; –Primitive elements initialized to zero or false Non-primitive references are null –Multiple declarations: String b[] = new String[ 100 ], x[] = new String[ 27 ]; Also: double[] array1, array2; Put brackets after data type

 2000 Prentice Hall, Inc. All rights reserved Examples Using Arrays new –Dynamically creates arrays Method length –Returns length of the array myArray.length Initializer lists int myArray[] = { 1, 2, 3, 4, 5 }; new operator not needed, provided automatically

 2000 Prentice Hall, Inc. All rights reserved. Outline 1. Initialize array 1.1 Loop and generate random numbers (note scaling) 1.2 Append output 1.3 Initialize outputArea 2. showMessageDialog 1// Fig : RollDie.java 2// Roll a six-sided die 6000 times 3import javax.swing.*; 4 5public class RollDie { 6 public static void main( String args[] ) 7 { 8 int face, frequency[] = new int[ 7 ]; 9 String output = ""; for ( int roll = 1; roll <= 6000; roll++ ) { 12 face = 1 + ( int ) ( Math.random() * 6 ); 13 ++frequency[ face ]; 14 } output += "Face\tFrequency"; for ( face = 1; face < frequency.length; face++ ) 19 output += "\n" + face + "\t" + frequency[ face ]; JTextArea outputArea = new JTextArea( 7, 10 ); 22 outputArea.setText( output ); JOptionPane.showMessageDialog( null, outputArea, 25 "Rolling a Die 6000 Times", 26 JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); 29 } 30}

 2000 Prentice Hall, Inc. All rights reserved. Outline Program Output

 2000 Prentice Hall, Inc. All rights reserved References and Reference Parameters Passing arguments to methods –Call-by-value: pass copy of argument –Call-by-reference: pass original argument Improve performance, weaken security In Java, cannot choose how to pass arguments –Primitive data types passed call-by-value –References to objects passed call-by-reference Original object can be changed in method –Arrays in Java treated as objects Passed call-by-reference

 2000 Prentice Hall, Inc. All rights reserved Multiple-Subscripted Arrays Multiple-Subscripted Arrays –Represent tables Arranged by m rows and n columns (m by n array) Can have more than two subscripts –Java does not support multiple subscripts directly Create an array with arrays as its elements Array of arrays Declaration –Double brackets int b[][]; b = new int[ 3 ][ 3 ]; Declares a 3 by 3 array

 2000 Prentice Hall, Inc. All rights reserved Multiple-Subscripted Arrays (II) Declaration (continued) –Initializer lists int b[][] = { { 1, 2 }, { 3, 4 } }; –Each row can have a different number of columns: int b[][]; b = new int[ 2 ][ ]; // allocate rows b[ 0 ] = new int[ 5 ]; // allocate columns for row 0 b[ 1 ] = new int[ 3 ]; // allocate columns for row 1 –Notice how b[ 0 ] is initialized as a new int array 12 34

 2000 Prentice Hall, Inc. All rights reserved. Outline 1. Define class 1.1 init 1.2 Initialize double- scripted arrays 1// Fig : InitArray.java 2// Initializing multidimensional arrays 3import java.awt.Container; 4import javax.swing.*; 5 6public class InitArray extends JApplet { 7 JTextArea outputArea; 8 9 // initialize the applet 10 public void init() 11 { 12 outputArea = new JTextArea(); 13 Container c = getContentPane(); 14 c.add( outputArea ); int array1[][] = { { 1, 2, 3 }, { 4, 5, 6 } }; 17 int array2[][] = { { 1, 2 }, { 3 }, { 4, 5, 6 } }; outputArea.setText( "Values in array1 by row are\n" ); 20 buildOutput( array1 ); outputArea.append( "\nValues in array2 by row are\n" ); 23 buildOutput( array2 ); 24 } public void buildOutput( int a[][] ) 27 { 28 for ( int i = 0; i < a.length; i++ ) { for ( int j = 0; j < a[ i ].length; j++ )

 2000 Prentice Hall, Inc. All rights reserved. Outline Program Output 31 outputArea.append( a[ i ][ j ] + " " ); outputArea.append( "\n" ); 34 } 35 } 36}