1 / 41

Chapter 25 - Beyond C & C++: Operators, Methods, and Arrays in Java

Chapter 25 - Beyond C & C++: Operators, Methods, and Arrays in Java. Outline 25.1 Introduction 25.2 Primitive Data Types and Keywords 25.3 Logical Operators 25.4 Method Definitions 25.5 Java API Packages 25.6 Random Number Generation 25.7 Example: A Game of Chance

jela
Download Presentation

Chapter 25 - Beyond C & C++: Operators, Methods, and Arrays in Java

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. 25.1 Introduction • 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

  3. 25.2 Primitive 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 • ints may be 2 or 4 bytes, depending on system • WORA - Write once, run anywhere • Default values • boolean gets false, all other types are 0

  4. 25.2 Primitive Data Types and Keywords (II)

  5. 25.2 Primitive Data Types and Keywords (III) • Keywords • Reserved names, cannot be used as identifiers • Used to implement features

  6. 25.3 Logical 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

  7. 25.3 Logical 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)

  8. 25.3 Logical 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

  9. 25.3 Logical Operators (IV) • More GUI classes • showMessageDialog(null, myScroller, titleString, type); • Second argument indicates that myScroller (and attached myArea) should be displayed in message dialog

  10. 1 // Fig. 25.7: LogicalOperators.java 2 // Demonstrating the logical operators 3 import javax.swing.*; 4 5 publicclass LogicalOperators { 6 publicstaticvoid main( String args[] ) 7 { 8 JTextArea outputArea = new JTextArea( 17, 20 ); 9 JScrollPane scroller = new JScrollPane( outputArea ); 10 String output = ""; 11 12 output += "Logical AND (&&)" + 13 "\nfalse && false: " + ( false && false ) + 14 "\nfalse && true: " + ( false && true ) + 15 "\ntrue && false: " + ( true && false ) + 16 "\ntrue && true: " + ( true && true ); 17 18 output += "\n\nLogical OR (||)" + 19 "\nfalse || false: " + ( false || false ) + 20 "\nfalse || true: " + ( false || true ) + 21 "\ntrue || false: " + ( true || false ) + 22 "\ntrue || true: " + ( true || true ); 23 24 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 ); 29 30 output += "\n\nBoolean logical inclusive OR (|)" + 1. Class definition 1.1 Initialize objects (JTextArea, JScrollPane) 1.2 Declare String 1.3 Append logical operator statements

  11. 31 "\nfalse | false: " + ( false | false ) + 32 "\nfalse | true: " + ( false | true ) + 33 "\ntrue | false: " + ( true | false ) + 34 "\ntrue | true: " + ( true | true ); 35 36 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 ); 41 42 output += "\n\nLogical NOT (!)" + 43 "\n!false: " + ( !false ) + 44 "\n!true: " + ( !true ); 45 46 outputArea.setText( output ); 47 JOptionPane.showMessageDialog( null, scroller, 48 "Truth Tables", JOptionPane.INFORMATION_MESSAGE ); 49 System.exit( 0 ); 50 } 51 } 2. Add output to outputArea 2.1 showMessageDialog (notice second argument) 2.2 System.exit required for programs with GUIs

  12. Program Output

  13. 25.4 Method 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

  14. 25.4 Method 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 }

  15. 25.4 Method 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

  16. 25.4 Method 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 );

  17. 1 // Fig. 25.8: SquareInt.java 2 // A programmer-defined square method 3 import java.awt.Container; 4 import javax.swing.*; 5 6 publicclass SquareInt extends JApplet { 7 publicvoid init() 8 { 9 String output = ""; 10 11 JTextArea outputArea = new JTextArea( 10, 20 ); 12 13 // get the applet's GUI component display area 14 Container c = getContentPane(); 15 16 // attach outputArea to Container c 17 c.add( outputArea ); 18 19 int result; 20 21 for ( int x = 1; x <= 10; x++ ) { 22 result = square( x ); 23 output += "The square of " + x + 24 " is " + result + "\n"; 25 } 26 27 outputArea.setText( output ); 28 } 29 30 // square method definition 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

  18. 31 publicint square( int y ) 32 { 33 return y * y; 34 } 35 } 3. Method definition Program Output

  19. 25.5 Java API Packages • As we have seen • Java has predefined, grouped classes called packages • Together, all the packages are the Applications Programming Interface (API) • Fig 25.10 has a list of the packages in the API • Import • Import statements specify location of classes • Large number of classes, avoid reinventing the wheel

  20. 25.6 Random 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 )

  21. 25.7 Example: 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

  22. 25.7 Example: 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

  23. 25.7 Example: 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

  24. 25.7 Example: 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

  25. 25.7 Example: 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

  26. 1 // Fig. 25.13: Craps.java 2 // Craps 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 publicclass Craps extends JApplet implements ActionListener { 8 // constant variables for status of game 9 finalint WON = 0, LOST = 1, CONTINUE = 2; 10 11 // 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 16 17 // graphical user interface components 18 JLabel die1Label, die2Label, sumLabel, pointLabel; 19 JTextField firstDie, secondDie, sum, point; 20 JButton roll; 21 22 // setup graphical user interface components 23 publicvoid init() 24 { 25 Container c = getContentPane(); 26 c.setLayout( new FlowLayout() ); 27 28 die1Label = new JLabel( "Die 1" ); 29 c.add( die1Label ); 30 firstDie = new JTextField( 10 ); 1. import 2. Define class(implements) 2.1 Initialize variables and objects 2.2 setLayout

  27. 31 firstDie.setEditable( false ); 32 c.add( firstDie ); 33 34 die2Label = new JLabel( "Die 2" ); 35 c.add( die2Label ); 36 secondDie = new JTextField( 10 ); 37 secondDie.setEditable( false ); 38 c.add( secondDie ); 39 40 sumLabel = new JLabel( "Sum is" ); 41 c.add( sumLabel ); 42 sum = new JTextField( 10 ); 43 sum.setEditable( false ); 44 c.add( sum ); 45 46 pointLabel = new JLabel( "Point is" ); 47 c.add( pointLabel ); 48 point = new JTextField( 10 ); 49 point.setEditable( false ); 50 c.add( point ); 51 52 roll = new JButton( "Roll Dice" ); 53 roll.addActionListener( this ); 54 c.add( roll ); 55 } 56 57 // call method play when button is pressed 58 publicvoid actionPerformed( ActionEvent e ) 59 { 60 play(); 2.3 add components to GUI 2.4 addActionListener 3. Define actionPerformed (event handler)

  28. 61 } 62 63 // process one roll of the dice 64 publicvoid play() 65 { 66 if ( firstRoll ) { // first roll of the dice 67 sumOfDice = rollDice(); 68 69 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(); 88 89 if ( sumOfDice == myPoint ) // win by making point 90 gameStatus = WON; 3.1 Define play 3.2 switch

  29. 91 else 92 if ( sumOfDice == 7 ) // lose by rolling 7 93 gameStatus = LOST; 94 } 95 96 if ( gameStatus == CONTINUE ) 97 showStatus( "Roll again." ); 98 else { 99 if ( gameStatus == WON ) 100 showStatus( "Player wins. " + 101 "Click Roll Dice to play again." ); 102 else 103 showStatus( "Player loses. " + 104 "Click Roll Dice to play again." ); 105 106 firstRoll = true; 107 } 108 } 109 110 // roll the dice 111 publicint rollDice() 112 { 113 int die1, die2, workSum; 114 115 die1 = 1 + ( int ) ( Math.random() * 6 ); 116 die2 = 1 + ( int ) ( Math.random() * 6 ); 117 workSum = die1 + die2; 118 119 firstDie.setText( Integer.toString( die1 ) ); 120 secondDie.setText( Integer.toString( die2 ) ); 3.3 Define rollDice

  30. 121 sum.setText( Integer.toString( workSum ) ); 122 123 return workSum; 124 } 125 } Program Output

  31. 25.8 Methods 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 25.14 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

  32. 25.8 Methods of Class JApplet(II) First line of JApplet methods (descriptions Fig. 25.14) public void init() public void start() public void paint( Graphics g ) public void stop() public void destroy()

  33. 25.9 Declaring 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

  34. 25.10 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

  35. 1 // Fig. 25.21: RollDie.java 2 // Roll a six-sided die 6000 times 3 import javax.swing.*; 4 5 publicclass RollDie { 6 publicstaticvoid main( String args[] ) 7 { 8 int face, frequency[] = newint[ 7 ]; 9 String output = ""; 10 11 for ( int roll = 1; roll <= 6000; roll++ ) { 12 face = 1 + ( int ) ( Math.random() * 6 ); 13 ++frequency[ face ]; 14 } 15 16 output += "Face\tFrequency"; 17 18 for ( face = 1; face < frequency.length; face++ ) 19 output += "\n" + face + "\t" + frequency[ face ]; 20 21 JTextArea outputArea = new JTextArea( 7, 10 ); 22 outputArea.setText( output ); 23 24 JOptionPane.showMessageDialog( null, outputArea, 25 "Rolling a Die 6000 Times", 26 JOptionPane.INFORMATION_MESSAGE ); 27 28 System.exit( 0 ); 29 } 30 } 1. Initialize array 1.1 Loop and generate random numbers (note scaling) 1.2 Append output 1.3 Initialize outputArea 2. showMessageDialog

  36. Program Output

  37. 25.11 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

  38. 25.12 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

  39. 25.12 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 rowsb[ 0 ] = new int[ 5 ]; // allocate columns for row 0b[ 1 ] = new int[ 3 ]; // allocate columns for row 1 • Notice how b[ 0 ] is initialized as a new int array

  40. 1 // Fig. 25.23: InitArray.java 2 // Initializing multidimensional arrays 3 import java.awt.Container; 4 import javax.swing.*; 5 6 publicclass InitArray extends JApplet { 7 JTextArea outputArea; 8 9 // initialize the applet 10 publicvoid init() 11 { 12 outputArea = new JTextArea(); 13 Container c = getContentPane(); 14 c.add( outputArea ); 15 16 int array1[][] = { { 1, 2, 3 }, { 4, 5, 6 } }; 17 int array2[][] = { { 1, 2 }, { 3 }, { 4, 5, 6 } }; 18 19 outputArea.setText( "Values in array1 by row are\n" ); 20 buildOutput( array1 ); 21 22 outputArea.append( "\nValues in array2 by row are\n" ); 23 buildOutput( array2 ); 24 } 25 26 publicvoid buildOutput( int a[][] ) 27 { 28 for ( int i = 0; i < a.length; i++ ) { 29 30 for ( int j = 0; j < a[ i ].length; j++ ) 1. Define class 1.1 init 1.2 Initialize double-scripted arrays

  41. 31 outputArea.append( a[ i ][ j ] + " " ); 32 33 outputArea.append( "\n" ); 34 } 35 } 36 } Program Output

More Related