Java Programming From Problem Analysis To Program Design 4th Edition

1K 1.4K 0
Java Programming From Problem Analysis To Program Design 4th Edition

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Apago PDF Enhancer www.traintelco.com JAVA PROGRAMMING FROM PROBLEM ANALYSIS TO PROGRAM DESIGN FOURTH EDITION D.S MALIK Apago PDF Enhancer Australia  Brazil  Japan  Korea  Mexico  Singapore  Spain  United Kingdom  United States www.traintelco.com Java Programming: From Problem Analysis to Program Design, Fourth Edition D.S Malik Executive Editor: Marie Lee Acquisitions Editor: Amy Jollymore For product information and technology assistance, contact us at Cengage Learning Customer & Sales Support, 1-800-354-9706 For permission to use material from this text or product, submit all requests online at cengage.com/permissions Further permissions questions can be emailed to permissionrequest@cengage.com Senior Product Manager: Alyssa Pratt Editorial Assistant: Julia Leroux-Lindsey Marketing Manager: Bryant Chrzan Senior Content Project Manager: Catherine DiMassa ISBN-13: 978-1-4390-3566-5 ISBN-10: 1-4390-3566-0 Compositor: Integra Course Technology 20 Channel Center Boston, MA 02210 USA ª 2010 Course Technology, Cengage Learning Cengage Learning is a leading provider of customized learning solutions with office locations around the globe, including Singapore, the United Kingdom, Australia, Mexico, Brazil, and Japan Locate your local office at: international.cengage.com/region Art Director: Marissa Falco ALL RIGHTS RESERVED No part of this work covered by the copyright herein may be reproduced, transmitted, stored or used in any form or by any means graphic, electronic, or mechanical, including but not limited to photocopying, recording, scanning, digitizing, taping, Web distribution, information networks, or information storage and retrieval systems, except as permitted under Section 107 or 108 of the 1976 United States Copyright Act, without the prior written permission of the publisher Cengage Learning products are represented in Canada by Nelson Education, Ltd For your lifelong learning solutions, visit course.cengage.com Visit our corporate website at cengage.com Apago Some PDF Enhancer of the product names and company names used in this book have been used for identification purposes only and may be trademarks or registered trademarks of their respective manufacturers and sellers Any fictional data related to persons or companies or URLs used throughout this book is intended for instructional purposes only At the time this book was printed, any such data was fictional and not belonging to any real persons or companies Course Technology, a part of Cengage Learning, reserves the right to revise this publication and make changes from time to time in its content without notice The programs in this book are for instructional purposes only They have been tested with care, but are not guaranteed for any particular intent beyond educational purposes The author and the publisher not offer any warranties or representations, nor they accept any liabilities with respect to the programs Printed in Canada 12 11 10 09 www.traintelco.com TO Daughter Apago My PDF Enhancer Shelly Malik www.traintelco.com This page intentionally left blank Apago PDF Enhancer www.traintelco.com BRIEF CONTENTS PREFACE xix An Overview of Computers and Programming Languages Basic Elements of Java 25 Introduction to Objects and Input/Output 107 Control Structures I: Selection 165 Control Structures II: Repetition 225 Graphical User Interface (GUI) and Object-Oriented Design (OOD) 295 User-Defined Methods 351 Apago PDF Enhancer User-Defined Classes and ADTs 425 Arrays 509 10 Inheritance and Polymorphism 591 11 Handling Exceptions and Events 673 12 Advanced GUIs and Graphics 733 13 Recursion 823 14 Searching and Sorting 855 APPENDIX A Java Reserved Words 891 APPENDIX B Operator Precedence 893 APPENDIX C Character Sets 897 APPENDIX D Additional Java Topics 901 APPENDIX E Answers to Odd-Numbered Exercises 949 INDEX 973 www.traintelco.com TABLE CONTENTS OF Preface xix AN OVERVIEW OF COMPUTERS AND PROGRAMMING LANGUAGES Introduction An Overview of the History of Computers Elements of a Computer System Hardware Software Language of a Computer Evolution of Programming Languages Apago Enhancer Processing PDF a Java Program Internet, World Wide Web, Browser, and Java 10 13 Programming with the Problem Analysis–Coding– Execution Cycle 13 Programming Methodologies Structured Programming Object-Oriented Programming 19 19 19 Quick Review 21 Exercises 23 BASIC ELEMENTS OF JAVA 25 A Java Program 26 Basics of a Java Program 28 Comments 29 Special Symbols Reserved Words (Keywords) 30 30 Identifiers 31 www.traintelco.com Table of Contents Data Types Primitive Data Types | vii 32 32 Arithmetic Operators and Operator Precedence Order of Precedence 36 39 Expressions 40 Mixed Expressions 41 Type Conversion (Casting) 43 class String 45 Strings and the Operator + Input Allocating Memory with Named Constants and Variables 46 48 48 Putting Data into Variables Declaring and Initializing Variables 51 55 Input (Read) Statement 56 Reading a Single Character 61 Increment and Decrement Operators Apago PDF Enhancer 63 Output 66 Packages, Classes, Methods, and the import Statement 71 Creating a Java Application Program 72 Programming Style and Form Syntax 77 77 Avoiding Bugs: Consistent, Proper Formatting 81 Debugging—Code Walk-throughs 81 More on Assignment Statements (Optional) 82 Programming Example: Convert Length 84 Programming Example: Make Change 88 Debugging: Understanding Error Messages 91 Quick Review 91 Exercises 94 Programming Exercises www.traintelco.com 102 viii | Java Programming: From Problem Analysis to Program Design, Fourth Edition INTRODUCTION TO OBJECTS AND INPUT/OUTPUT 107 Objects and Reference Variables 108 Using Predefined Classes and Methods in a Program 112 Dot Between Class (Object) Name and Class Member: A Precaution 114 class String 115 Input/Output 123 Formatting Output with printf 123 Using Dialog Boxes for Input/Output Formatting the Output Using the String Method format 132 139 File Input/Output Storing (Writing) Output to a File 145 Programming Example: Movie Ticket Sale and Donation to Charity 147 Programming Example: Student Grade 153 Apago PDF Enhancer Debugging—Understanding Error Messages 142 156 Quick Review 156 Exercises 158 Programming Exercises 161 CONTROL STRUCTURES I: SELECTION 165 Control Structures 166 Relational Operators 168 Relational Operators and Primitive Data Types 169 Logical (Boolean) Operators and Logical Expressions 172 Order of Precedence 174 Short-Circuit Evaluation boolean Data Type and Logical (Boolean) Expressions www.traintelco.com 178 179 Table of Contents Selection: if and if else | 180 One-Way Selection Two-Way Selection 180 183 Compound (Block of) Statements Multiple Selections: Nested if 187 188 Comparing if else Statements with a Series of if Statements Conditional Operator (? :) (Optional) switch Structures 191 192 193 Avoiding Bugs by Avoiding Partially Understood Concepts and Techniques 199 Programming Example: Cable Company Billing 201 Comparing Strings Strings, the Assignment Operator, and the Operator new Quick Review Exercises Apago PDF Enhancer 207 211 213 215 Programming Exercises 221 CONTROL STRUCTURES II: REPETITION 225 Why Is Repetition Needed? 226 while Looping (Repetition) Structure 227 Designing while Loops 230 Counter-Controlled while Loops Sentinel-Controlled while Loops 231 233 Flag-Controlled While Loops EOF-Controlled while Loops 239 243 More on Expressions in while Statements 247 Programming Example: Fibonacci Number 248 for Looping (Repetition) Structure 254 Programming Example: Classify Numbers 259 while Looping (Repetition) Structure Choosing the Right Looping Structure 263 268 www.traintelco.com ix This page intentionally left blank Apago PDF Enhancer www.traintelco.com INDEX Note: Boldface type indicates key terms Special Characters, 30 \ (backslash), 34, 67–70 < (left angle bracket), 168 > (right angle bracket), 168 () (parentheses), 175 (braces), 78 ! (exclamation point), 168, 172 $ (dollar sign), 31 % (percent sign), 36, 124–130 & (ampersand), 172 * (asterisk), 36 ỵ (plus sign), 36, 37, 4648, 63–65 - (minus sign), 36, 64, 65 / (forward slash), 36 ¼ (equal sign), 51, 168, 169 ? (question mark), 192–193 [] (square brackets), 513 _ (underscore), 31 | (pipe), 172, 173–174 , (comma), 78 (dot), 114–115, 435 ; (semicolon), 78 action events, 316, 317 action listener, 316 action statements, 180 ActionListener interface, 711–712 actual parameters, 361 syntax, 362–363 void methods, 377 addition operator (ỵ), 36, 37 strings, 4648 addresses base, arrays, 522 memory cells, ADTs (abstract data types), 477–478 Advanced Research Projects Agency (ARPA), 13 aggregation, 636–641 Aiken, Howard, algorithms, 14, 15, 16–19, 469 methods, 20 recursive, 825 American Standard Code for Information Interchange (ASCII), 7, 34 character set, 897–898 ampersand (&), and operator (&&), 172 analog signals, and operator (&&), 172 Apple computers, first, applets, 13, 734, 737–741 converting application programs to, 758–761 application programs, 6, 13 converting to applets, 758–761 creating, 72–76 arguments, 353 See also actual parameters; formal parameters; parameters arithmetic expressions, 36 arithmetic operations, char data type, 40 arithmetic operators, 36–40 associativity, 40, 893 order of precedence, 39–40, 174, 893 ArithmeticException method, 687 ARPA (Advanced Research Projects Agency), 13 ARPANET, 13 array(s), 20, 509–573 accessing elements, 513–515 assignment operator and relational operators, 523–525 base address, 522 declaring See declaring arrays definition, 511 elements (components) See array elements finding largest element, 828–831 functions, 510–511 index, 513 Apago PDF Enhancer A abs(x) method, 353 abstract classes, 626–632 abstract data types (ADTs), 477–478 abstract methods, 626–632 accessor methods, 430, 465–468 www.traintelco.com 974 | Index array(s), (Continued) initialization, 516, 552–553, 555 instance variable length, 516–517 instantiation, 512 multidimensional, 561–562 of objects, 532–539 one-dimensional See onedimensional arrays out of bounds exception, 522 as parameters to methods, 525–529 searching for specific items, 530–532 size after initialization, 517 specifying size during execution, 515 two-dimensional See twodimensional arrays variable length parameter list, 539–547 array elements, 511 accessing, 513–515 as parameters to methods, 527–529 two-dimensional arrays, accessing, 549–552 array subscripting operator ([]), 513 ArrayIndexOutOfBounds Exception method, 687 ASCII See American Standard Code for Information Interchange (ASCII) assemblers, assembly languages, 6–8 assignment operator (=), 51 arrays, 523–525 associativity, 55 operation with reference variables and objects, 436–438 assignment statements, 82–83 putting data into variables, 51–55 associativity, operators, 40, 55, 175, 893 asterisk (*), multiplication operator, 36 Augusta, Ada, autoboxing, 340–342 auto-unboxing, 340–342 avoiding bugs by avoiding partially understood concepts and techniques, 199–201 by avoiding patches, 270–272 consistent, proper formatting for, 81–82 developing test suites in advance for, 871–873 method stubs for, 407 one-piece-at-a-time coding for, 406–407 base address, arrays, 522 base case, 824 base classes See superclasses base numbers, converting binary numbers to, 904–906 base 16 numbers, converting binary numbers to, 904–906 base 10 system, See also decimal number(s) base representation, 901 base system, See also binary number(s) Basic, binary code, binary digits, binary number(s), converting base 10 numbers to, 901–903 converting to base 10, 903–904 converting to octal and hexadecimal numbers, 904–906 binary number system, 901 binary operators, 36, 37 binary representation, 901 binary searches, 867–871 blanks, syntax, 77 blocks, statements, 187 BlueJ, 12 body, methods, 74, 360 boolean data type, 34 logical (boolean) expressions, 179 Boolean data types, 32, 34 Boolean expressions See logical (boolean) expressions BooleanClass class, 931–932 BorderLayout manager, 793–794 Apago PDF Enhancer B Babbage, Charles, backslash (\), 70 backslash escape sequence (\), 70 backspace escape sequence (\b), 70 double quotation escape sequence (\’’), 70 escape character, 67, 70 newline escape sequence (\n), 34, 67, 68–69, 70 return escape sequence (\r), 70 single quotation escape sequence (\’) 70 tab escape sequence (\y), 70 backslash escape sequence (\), 70 backspace escape sequence (\b), 70 www.traintelco.com Index bottom-up design See structured programming Box class, 597–600, 600–602 BoxFigure class, 619 BoxShape class, 623–626 braces ({}), 78 branches, program processing, 166, 167 break statement, 268–270 browsers, 13 bugs See avoiding bugs; debugging build command, 921 built-in operations, classes, 436 buttons creating using class JButton, 315–322 event handling, 316–322 byte(s), 6–7 byte data type, 32, 33 bytecode, 9, 10 bytecode verifier, 11 cell phones, central processing unit (CPU), 4–5 change making programming example, 88–91 char data type, 32, 33–34 arithmetic operations, 40 char variables reading a single character, 61–63 storing characters into using input statements, 61 Character class, predefined methods, 355–356 character literals (characters; character constants), 36 character strings, 45 charAt method, exceptions thrown by, 691 CharClass class, 929 check boxes, 766–773 checked exceptions, 691–692 chips, Circle class definition, 427, 454–455 using in programs, 455–456 class(es), 20, 28, 71, 426–452 See also specific class names abstract, 626–632 assignment operator, 436–438 built-in operations, 436 clients, 450 composition (aggregation), 636–641 constructors, 431–432 to create application programs, syntax, 73 declaring final, 620 derived See subclasses designing, 468–470 documenting design, 468–470 exception, creating, 708–710 fields, 428 inner, 477 instances, 110, 435 interfaces, 632–636 members, 428 See also class members methods See method(s); specific method names objects See object(s) predefined, 71, 112 primitive type, 924–933 scope, 438 scope of identifiers within, 390–392 stream, 614–615 syntax, 428 UML, 432–433 variable declaration, 433–435 class libraries, 112, 353 class members, 429 accessing, 435–436 member access operator, 114–115 protected, 609–612 static, 459–465 static data members, 461–465 class reserved word, 73, 428 clients, 450 Clock class, 439–452 constructors, 446–447 data members, 429 definition, 429, 447–452 instance variables, 439 members, 429 methods, 430–431, 439–446 COBOL, 3, code detection programming example, 562–567 Code Warrior, 12 coding one-piece-at-a-time, 406–407 Apago PDF Enhancer C C programming language, 9, 10 cable company billing programming example, 201–206 calculator programming example, 716–725 candy machine programming example, 479–496 cascaded method calls, 474–477 case sensitivity, 31 cast operators, 43–45 floating-point expressions, 63 casting See cast operators catch blocks, throwing exceptions caught by, 700–701 ceil method, 354 www.traintelco.com | 975 976 | Index collating sequences, 34 Color class, 744–749 column processing, 553 combo boxes, 778–783 command-line statements, executing Java programs using, 906–915 comma (,), 78 comments, 29–30 multiple-line, 30 single-line, 29–30 compareTo method, 207–211 comparing strings, 207–213 compilers, 9–10 Component class, 735–736 components See array elements composition, 592, 636–641 compound operators, 82–83 compound statements, 187 computer(s) history, 2–3 machine language, 6–8 computer programs, 26 computer system elements, 3–6 condition(s), 180, 227 See also while loops conditional expressions, 192 conditional operator (?), 192–193 constants character, 36 floating-point, 36 integer, 36, 50 named, 48–50, 353 string, 45 constructors, 302, 431–432 See also specific class names copy, 458–459 default, 431–432 superclass and subclass, 600–609 Container class, 736–737 content pane, 300 access, 306–307 labels, 307–311 continue statement, 268–270 control expressions, for loops, 254 control structures, 165–214, 225–278 break and continue statements, 268–270 comparing strings, 207–213 logical (boolean) operators and logical expressions, 172–174 nested, 188–191, 272–277 order of precedence, 174–179 primitive data types, 169–172 relational operators, 168–172 repetition See repetition; while loops selection See selection switch structures, 193–199 conversions, printf method, 125 coordinate system, 752 copy constructors, 458–459 cos(x) method, 355 counted for loops, 255 counter-controlled while loops, 231233 Cỵỵ programming language, 9, 10 data types, 32–36 abstract, 477–478 Boolean, 32, 34 boolean, 34, 179 byte, 32, 33 char, 32, 33–34, 40 double, 35, 49 enumeration (enum), 933–938 false, 35 float, 35, 49 floating-point, 32, 34–35 implicit type coercion, 43 int, 32, 33 integral, 32–34 long, 32, 33 primitive See primitive data types short, 32, 33 type conversion (casting), 43–45 Date class, 636–638 debugging, 81–82 design walk-throughs, 471–472 designing classes and documenting design, 468–470 error messages, 91, 156 decimal expressions See floating-point expressions decimal number(s) converting binary numbers to, 903–904 converting to binary numbers, 901–903 formatting using class DecimalFormat, 921–924 decimal number system, 7, 901 decimal to binary conversion programming example, 839–842 DecimalFormat class, 921–924 formatting output, 139, 921–924 Apago PDF Enhancer D data comparison programming example, 395–405 data members, static, 461–465 www.traintelco.com Index declaration statements, 74 declaring arrays See declaring arrays classes as final, 620 identifiers, 51 methods as final, 620 variables, 55–56, 433–435 declaring arrays, 513 array initialization during declaration, 516, 552–553 as formal parameters to methods, 522–523 methods, 513 decrement operator ( ), 64, 65 deep copying, 438, 524 default constructor, 431–432 definitions methods, 360 void methods, 375 derived classes See subclasses dialog boxes, 132–138 digital signals, direct recursion, 826–827 displaying lines of text, 761–766 lists, 783–789 division operator (/), 36 divisors, 266 documentation, 915–918 dollar sign ($), identifier, 31 dot (.), member access operator, 114–115, 435 Double class, 132 exceptions thrown by methods of, 690 double data type, 35, 49 double precision, 35 double quotation escape sequence (), 70 DoubleClass class, 930–931 while loops, 263–268 DrJava, 12 drop-down lists, 778–783 dynamic binding, 616 E EBs (exabytes), Eclipse, 12 election results programming example, 874–886 elements, arrays, 511 See also array elements empty strings, 45 encapsulation, 331, 426 ENIAC (Electronic Numerical Integrator and Calculator), enumeration (enum) data types, 933–938 EOF (End Of File)-controlled while loops, 243–247 equal sign (¼) assignment operator, 51 equal to operator (¼¼), 168, 169 greater than or equal to operator (>¼), 168 less than or equal to operator (), 168 greater than or equal to operator (>¼), 168 GUIs See graphical user interfaces (GUIs) Apago PDF Enhancer G garbage collection, 111 GBs (gigabytes), general case, 824 getCopy method, 444–446 getHeight method, 599–600 getHours method, 430, 441 getMessage method, 687 getMinutes method, 441 www.traintelco.com H hardware components, 4–5 Harvard University, hasNext method, exceptions thrown by, 689 headings, methods, 74, 360 hexadecimal numbers, converting binary numbers to, 904–906 Index high-level languages, history of computers, 2–3 Hollereith, Herman, 2–3 horizontal tab character (\t), 34 Hypertext Markup Language (HTML), 13 I IBM, IBM PC, introduction, identifiers, 31 declaring, 51 local, 390 scope within classes, 390–392 if statements, 180–183 nested, 189–191 series of, if else statements compared, 191–192 if else statements, 183–187 nested, 188–191 series of if statements compared, 191–192 switch structures versus, 199 IllegalArgument Exception method, 687 IllegalStateException exception, 688, 689 Illustrate class, 460–461 immutability, 340 implicit type coercion, 43 in bounds, 522 increment operator (++), 63–65 incrementHours method, 441 incrementMinutes method, 441 incrementSeconds method, 442 index, arrays, 513 in bounds, 522 out of bounds exception, 522 index, strings, 116 indexed for loops, 255 indexOf method, exceptions thrown by, 691 IndexOutOfBounds Exception method, 687 indirect recursion, 826–827 infinite loops, 228–229 information hiding, 478 inheritance, 302, 592–612 hierarchy, 593 multiple, 594 single, 594 initial values, 516 initialization, 51 arrays See initializing arrays Scanner objects, 142 variables, 51, 53, 55–56, 60–61 initializer list, 516 initializing arrays array size after initialization, 517 during declaration, 516, 552–553 two-dimensional arrays, during declaration, 552–553 inner classes, 477 input, 48–63 allocating memory with named constants and variables, 48–51 declaring and initializing variables, 55–56 into files, 142–143 input (read) statements, 56–61 putting data into variables, 51–55 reading a single character, 61–63 input devices, input statements, 56–61 storing characters into char variables, 61 variable initialization, 60–61 InputMismatchException exception, 688 InputMismatchException method, 688 insertion point, 66 insertion sorts, 861–867 instance(s), 110, 435 instance methods, 431 instance variables, 429 class Clock, 439 declaration, 433–434 instanceof operator, 621–626, 696–699 instantiating arrays, 512 objects, 110 int data type, 32, 33 IntClass class, 924–927 integer(s) See integer literals (constants) Integer class, 132 exceptions thrown by methods of, 690 integer literals (constants), 36 invalid, 50 integral data types, 32–34 integral expressions, 40, 41 integrated circuits See chips integrated development environments (IDEs), 11, 12 interfaces, 632–636 See also graphical user interfaces (GUIs) event handling, 711 polymorphism via, 634–636 Internet, development, 13 Internet Explorer, 13 interpreters, 11–12 Apago PDF Enhancer www.traintelco.com | 979 980 | Index invalid integers, 50 isDigit method, 355 isLetter method, 355 isLowerCase method, 356 isUpperCase method, 356 item comparisons, 856 iterative control structures, 838 recursion versus, 838–839 J Jacquard, Joseph, JApplet class, 737–738 Java, Java applets See applets Java applications, 13 Java programs basics, 28–31 example, 26–28 processing, 10–12 Java Virtual Machine (JVM), 10 JBuilder, 12 JButton class, 315–322 JCheckBox class, 766–773 JComboBox class, 778–783 JCreator, 12 JFrame class, 300–306 jGrasp, 12 JLabel class, 307–311 JList class, 783–789 Jobs, Steven, JOptionPane class, 132–138 JRadioButton class, 773–778 JTextArea class, 761–766 JTextField class, 311–314 keywords, 30 See also reserved words; specific reserved words kilobytes (KBs), 6–7 kiosk programming example, 807–815 L labels, content pane, 307–311 largest element, in array, finding, 828–831 largest number programming example, 373–374 lastIndexOf method, exceptions thrown by, 691 late binding, 616 layout managers, 789–794 BorderLayout, 793–794 FlowLayout, 790–792 left angle bracket (

Ngày đăng: 12/10/2016, 12:31

Từ khóa liên quan

Mục lục

  • Front Cover

  • Title Page

  • Copyright

  • Brief Contents

  • Table of Contents

  • Preface

  • 1 AN OVERVIEW OF COMPUTERS AND PROGRAMMING LANGUAGES

    • Introduction

    • An Overview of the History of Computers

    • Elements of a Computer System

      • Hardware

      • Software

      • Language of a Computer

      • Evolution of Programming Languages

      • Processing a Java Program

      • Internet, World Wide Web, Browser, and Java

      • Programming with the Problem Analysis–Coding–Execution Cycle

      • Programming Methodologies

        • Structured Programming

        • Object-Oriented Programming

        • Quick Review

        • Exercises

        • 2 BASIC ELEMENTS OF JAVA

          • A Java Program

Tài liệu cùng người dùng

Tài liệu liên quan