Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java...

88
Fundamentals of Computer Programming Using Java Student Workbook

Transcript of Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java...

Page 1: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Fundamentals ofComputer Programming

Using Java

Student Workbook

Page 2: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Fundamentals of Computer Programming Using Java

Page ii Rev 4.1.2 © 2002 ITCourseware, LLC

Fundamentals of Computer Programming Using Java

William A. Parette

Published by ITCourseware, LLC, 7245 South Havana Street, Suite 100, Englewood, CO 80112

Editor: Rob Roselius, Rick Sussenbach.

Editorial Staff: Jan Waleri, Mark Walters

Special thanks to: Several instructors whose ideas and careful review have contributed to the quality ofthis workbook, including Andrew Boardman, Brandon Caldwell, Roger Jones, John Roach, Jamie Romeroand Danielle Waleri, and the many students who have offered comments, suggestions, criticisms, andinsights.

Copyright © 2002 by ITCourseware, LLC. All rights reserved. No part of this book may be reproducedor utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or byan information storage retrieval system, without permission in writing from the publisher. Inquiries should beaddressed to ITCourseware, LLC, 7245 South Havana Street, Suite 100, Englewood, CO 80112. (303)302-5280.

All brand names, product names, trademarks, and registered trademarks are the property of their respectiveowners.

Page 3: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Fundamentals of Computer Programming Using Java

© 2002 ITCourseware, LLC Rev 4.1.2 Page iii

Contents

Chapter 1 - Course Introduction ............................................................................................................... 9

Course Objectives ............................................................................................................................ 10Course Overview .............................................................................................................................. 12Using the Workbook ......................................................................................................................... 13Suggested References ....................................................................................................................... 14

Chapter 2 - Basic Concepts and Definitions ............................................................................................ 17

What is a Program?........................................................................................................................... 18"Hello, world!" .................................................................................................................................. 20The Programming Process ................................................................................................................. 22Program Files and Program Execution ............................................................................................... 24System Programs vs. Application Programs ....................................................................................... 26Input - Process - Output ................................................................................................................... 28Programming Languages ................................................................................................................... 30Compiler Errors vs. Runtime Errors ................................................................................................... 32Development Environments ............................................................................................................... 34Review Questions ............................................................................................................................. 36Labs ................................................................................................................................................. 38

Chapter 3 - Writing Simple Programs ...................................................................................................... 41

Reading Input .................................................................................................................................... 42Performing Numeric Calculations ...................................................................................................... 44Formatting Output ............................................................................................................................. 46Decision Making ............................................................................................................................... 48Iteration ............................................................................................................................................ 50Commenting Your Source Code ........................................................................................................ 52Good Programming Style .................................................................................................................. 54Labs ................................................................................................................................................. 56

Page 4: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Fundamentals of Computer Programming Using Java

Page iv Rev 4.1.2 © 2002 ITCourseware, LLC

Chapter 4 - Data Types, Constants, and Variables ................................................................................... 59

A Program's Purpose is to Process Data ........................................................................................... 60Computer Memory ........................................................................................................................... 62Data Can Be of Different Types ........................................................................................................ 64Named Data: Variables ..................................................................................................................... 66Literal Data ....................................................................................................................................... 68Assignment........................................................................................................................................ 70Printing Variables ............................................................................................................................... 72Review Questions ............................................................................................................................. 74Labs ................................................................................................................................................. 76

Chapter 5 - Screen Output and Keyboard Input ..................................................................................... 79

Writing to the Screen ......................................................................................................................... 80Characters That Have Special Meaning ............................................................................................. 82Some Simple Formatting ................................................................................................................... 84Reading from the Keyboard .............................................................................................................. 86Prompting and Validating ................................................................................................................... 88Example 5 - Formatting Output Data ................................................................................................. 90Review Questions ............................................................................................................................. 92Labs ................................................................................................................................................. 94

Chapter 6 - Expressions .......................................................................................................................... 99

Expressions: Where the Work Gets Done ....................................................................................... 100Expression Evaluation: The Result ................................................................................................... 102Arithmetic Expressions .................................................................................................................... 104Relational Expressions ..................................................................................................................... 106Where are Relational Expressions Used?......................................................................................... 108And? . . . Or? . . . ........................................................................................................................... 110Precedence and Associativity .......................................................................................................... 112Example 6 - Calculating Miles Per Gallon ........................................................................................ 114Review Questions ........................................................................................................................... 116Labs ............................................................................................................................................... 118

Page 5: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Fundamentals of Computer Programming Using Java

© 2002 ITCourseware, LLC Rev 4.1.2 Page v

Chapter 7 - Decision Making ................................................................................................................ 123

Sequential Execution ....................................................................................................................... 124What is Decision Making? ............................................................................................................... 126Simple Decisions: if ......................................................................................................................... 128Two-Way Decisions: else ................................................................................................................ 130Code Blocks ................................................................................................................................... 132Nesting Control Statements ............................................................................................................. 134Multi-Way Decisions: switch ........................................................................................................... 136Example 7 - Printing Letter Grades Based On Scores ..................................................................... 138Review Questions ........................................................................................................................... 140Labs ............................................................................................................................................... 142

Chapter 8 - Looping ............................................................................................................................. 147

Kinds of Loops ............................................................................................................................... 148Iterative Loops ................................................................................................................................ 150Code Blocks and Loops ................................................................................................................. 152Nested Loops ................................................................................................................................. 154Conditional Loops ........................................................................................................................... 156Infinite Loops .................................................................................................................................. 158Example 8 - A Simple Menu Program ............................................................................................. 160Review Questions ........................................................................................................................... 162Labs ............................................................................................................................................... 164

Chapter 9 - Subroutines ........................................................................................................................ 173

Programming Without Subroutines ................................................................................................... 174Reusable Code in a Subroutine........................................................................................................ 176The Starting Point ............................................................................................................................ 178Variable Visibility: Scope ................................................................................................................. 180Parameters ...................................................................................................................................... 182Returning a Value ............................................................................................................................ 184Method Stubs ................................................................................................................................. 186Libraries .......................................................................................................................................... 188Example 9 – Square and Square Root ............................................................................................. 190Review............................................................................................................................................ 192Labs ............................................................................................................................................... 194

Page 6: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Fundamentals of Computer Programming Using Java

Page vi Rev 4.1.2 © 2002 ITCourseware, LLC

Chapter 10 - Debugging ........................................................................................................................ 199

What is Debugging? ........................................................................................................................ 200Commenting Out Code ................................................................................................................... 202Simple Debugging with Print Statements .......................................................................................... 204Making Debugging Print Statements Conditional .............................................................................. 206Programs that Help You Debug Programs ....................................................................................... 208Example 10 - Debug Statements ..................................................................................................... 210Review Questions ........................................................................................................................... 212Labs ............................................................................................................................................... 214

Chapter 11 - Data Collections – Arrays ................................................................................................. 217

Scalar Data vs. Data Collections ..................................................................................................... 218What is an Array? ........................................................................................................................... 220Accessing Array Elements ............................................................................................................... 222Multidimensional Arrays .................................................................................................................. 224Array Initialization ........................................................................................................................... 226Example 11 - Calculating Average Rainfall ....................................................................................... 228Review Questions ........................................................................................................................... 230Labs ............................................................................................................................................... 232

Chapter 12 - Data Collections - Classes ............................................................................................... 237

What is a Class? ............................................................................................................................. 238Object vs. Class .............................................................................................................................. 240Accessing Object Members ............................................................................................................ 242Using Arrays with Classes ............................................................................................................... 244Example 12 - A Customer Record .................................................................................................. 246Review Questions ........................................................................................................................... 248Labs ............................................................................................................................................... 250

Page 7: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Fundamentals of Computer Programming Using Java

© 2002 ITCourseware, LLC Rev 4.1.2 Page vii

Chapter 13 - Working with Files ........................................................................................................... 253

Terminal I/O and File I/O ................................................................................................................ 254Opening Files .................................................................................................................................. 256Opening a File for Writing ............................................................................................................... 258Opening a File for Reading .............................................................................................................. 260Checking for File Open Errors ........................................................................................................ 262Closing a File .................................................................................................................................. 264Text Files vs. Binary Files ................................................................................................................ 266Example 13 - A Customer Record in a File ..................................................................................... 268Review Questions ........................................................................................................................... 270Labs ............................................................................................................................................... 272

Solutions - Fundamentals of Computer Programming Using Java ........................................................... 275

Index..................................................................................................................................................... 349

Page 8: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Fundamentals of Computer Programming Using Java

Page viii Rev 4.1.2 © 2002 ITCourseware, LLC

Page 9: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Course IntroductionChapter 1

© 2002 ITCourseware, LLC Rev 4.1.2 Page 9

Chapter 1 - Course Introduction

Page 10: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Fundamentals of Computer Programming Using Java

Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC

� Explain what computer programs are and what computer programming is about.

� Discuss the terminology and concepts of computer programming.

� Write and compile simple computer programs.

� Describe basic computer language data types.

� Interact with computer programs using your terminal screen and keyboard.

� Evaluate expressions used in computer programs.

� Design the sequential execution, and flow of decision making, in a program.

� Write programs that use loops to perform repetitive tasks.

� Design and write procedural programs that use subroutines.

� Use basic debugging techniques to solve programming problems and increaseprogram quality.

� Use arrays and classes for managing program data.

� Write programs that use files to store and retrieve data.

� Begin professional-level training in computer programming languages.

Course Objectives

Page 11: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Course IntroductionChapter 1

© 2002 ITCourseware, LLC Rev 4.1.2 Page 11

This course introduces you to the fundamental concepts, semantic elements, and vocabulary of computerprogramming.

The material you learn here is illustrated using Java language examples; most of these same examples caneasily be converted to the C or C++ languages. Upon completion of this course, you will be prepared fortraining, or introductory self-study, in these languages and others.

Initially, the programs you write will simply be typed in from the many examples presented in this studentnotebook. However, you will also be asked to code some programs "from scratch." These programs willstart out small and simple as you are carefully guided through the concepts and facilities that will allow youto make your programs more interesting and complex.

Page 12: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Fundamentals of Computer Programming Using Java

Page 12 Rev 4.1.2 © 2002 ITCourseware, LLC

� Audience: People with no computer programming background who want tolearn the basics. This is a "first course" in computer programming.

� Prerequisites: Although no programming experience is required, it is assumedthat you have used a computer before, whether for word processing,spreadsheets, or even playing games. You should know what a file is — how tocreate one, how to put data in it, where the file is stored, and how to find it at alater time. Basic arithmetic skills and the ability to think logically are necessaryfor programming. Reasonable typing skills are critical.

� Classroom Environment:

� One workstation per student. However, you are strongly encouraged toteam up, share ideas, and work on some of the later exercises in smallgroups.

Course Overview

Page 13: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Course IntroductionChapter 1

© 2002 ITCourseware, LLC Rev 4.1.2 Page 13

Using the Workbook

Chapter 2 Servlet Basics

© 2002 ITCourseware, LLC Rev 2.0.0 Page 17

Add an init() method to your Today servlet that initializes a bornOn date, then print the bornOn date

along with the current date:

Today.java

...

public class Today extends GenericServlet {

private Date bornOn;public void service(ServletRequest request,

ServletResponse response) throws ServletException, IOException

{

...

// Write the document

out.println("This servlet was born on " + bornOn.toString());out.println("It is now " + today.toString());

}

public void init() {bornOn = new Date();

}

}

Hands On:

The init() method iscalled when the servlet isloaded into the container.

This workbook design is based on a page-pair, consisting of a Topic page and a Support page. When youlay the workbook open flat, the Topic page is on the left and the Support page is on the right. The Topicpage contains the points to be discussed in class. The Support page has code examples, diagrams, screenshots and additional information. Hands On sections provide opportunities for practical application of keyconcepts. Try It and Investigate sections help direct individual discovery.

In addition, there is an index for quick look-up. Printed lab solutions are in the back of the book as well ason-line if you need a little help.

Java Servlets

Page 16 Rev 2.0.0 © 2002 ITCourseware, LLC

� The servlet container controls the life cycle of the servlet.

� When the first request is received, the container loads the servlet class

and calls the init() method.

� For every request, the container uses a separate thread to call

the service() method.

� When the servlet is unloaded, the container calls the destroy()

method.

� As with Java’s finalize() method, don’t count on this being

called.

� Override one of the init() methods for one-time initializations, instead of

using a constructor.

� The simplest form takes no parameters.

public void init() {...}

� If you need to know container-specific configuration information, use

the other version.

public void init(ServletConfig config) {...

� Whenever you use the ServletConfig approach, always call the

superclass method, which performs additional initializations.

super.init(config);

The Servlet Life Cycle

The Topic page providesthe main topics for

classroom discussion.

The Support page hasadditional information,

examples and suggestions.

Code examples are in afixed font and shaded. Theon-line file name is listedabove the shaded area.

Screen shots showexamples of what youshould see in class.

Topics are organized intofirst (�), second (�) and

third (�) level points.

Pages are numberedsequentially throughout

the book, making lookupeasy.

Callout boxes point outimportant parts of the

example code.

Page 14: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Fundamentals of Computer Programming Using Java

Page 14 Rev 4.1.2 © 2002 ITCourseware, LLC

Flanagan, David. 2000. Java Examples In a Nutshell, 2nd Edition. O’Reilly & Associates,Sebastopol, CA. ISBN 0596000391.

Grand, Mark. 1997. Java Language Reference. O’Reilly & Associates, Sebastopol, CA.ISBN 1565922042.

Horton, Ivor. 1999. Beginning Java 2. Wrox Press, Inc, Chicago, IL. ISBN 1861002238.

Kelley, Al and Ira Pohl. 1997. A Book on C, 4th Edition. Addison-Wesley, Menlo Park, CA.ISBN 0201183994.

Kernighan, Brian and Dennis Ritchie. 1988. C Programming Language, 2nd Edition. Prentice Hall,Englewood Cliffs, NJ. ISBN 0131103628.

Oualline, Steve. 1995. Practical C++ Programming. O’Reilly & Associates, Sebastopol, CA.ISBN 1565921399.

Rosenblatt, Bill and Arnold Robbins. 2002. Learning the Korn Shell, 2nd Edition. O’Reilly &Associates, Sebastopol, CA. ISBN 0596001959.

Savitch, Walter. 2000. Java: An Introduction to Computer Science and Programming, 2ndEdition. Prentice Hall, Englewood Cliffs, NJ. ISBN 0130316970.

Schwartz, Randal and Tom Phoenix. 2001. Learning Perl, 3rd Edition. O’Reilly & Associates,Sebastopol, CA. ISBN 0596001320.

Shackleford, Russell L. 1997. Introduction to Computing and Algorithms. Addison-WesleyPublishing Co. Menlo Park, CA. ISBN 0201314517.

Tucker, Allen B. (Editor), et al. 1994. Fundamentals of Computing I: Logic, Problem Solving,Programs and Computers. McGraw-Hill, New York, NY. ISBN 0070654964.

Suggested References

Page 15: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Course IntroductionChapter 1

© 2002 ITCourseware, LLC Rev 4.1.2 Page 15

Page 16: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Fundamentals of Computer Programming Using Java

Page 16 Rev 4.1.2 © 2002 ITCourseware, LLC

Page 17: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Basic Concepts and DefinitionsChapter 2

© 2002 ITCourseware, LLC Rev 4.1.2 Page 17

Chapter 2 - Basic Concepts and Definitions

Objectives

� Define computer programming.

� Describe the purpose of a computer program.

� Describe the steps involved in writing a computerprogram.

� List some of the files created during theprogramming process and where they are stored.

� Differentiate between system programs andapplication programs.

� Diagram the flow of information through acomputer program.

� List several popular programming languages.

� Differentiate between a programming languageand a development environment.

Page 18: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Fundamentals of Computer Programming Using Java

Page 18 Rev 4.1.2 © 2002 ITCourseware, LLC

� A computer program is a set of detailed instructions that tell a computer toperform some specific task.

� How would you tell someone how to do something as simple as picking up aglass that is sitting on a table in front of them?

1. Extend your arm to bring the forearm parallel to the table.

2. Open the fingers of the hand.

3. Move the arm and hand such that the fingers of the hand gently encirclethe glass.

4. Close the fingers firmly, but gently, around the glass.

5. Raise the arm so that the glass rises off the table.

� And so on . . .

� How do you tell a computer to add two numbers?

1. Retrieve the first number from its memory location.

2. Retrieve the second number from its memory location.

3. Add the two numbers.

4. Store the result of the computation in some other memory location.

� And so on . . .

� Did you notice the detail? The logic? The careful sequencing?

What is a Program?

Page 19: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Basic Concepts and DefinitionsChapter 2

© 2002 ITCourseware, LLC Rev 4.1.2 Page 19

Computer programming is the art of communicating algorithms to computers. An algorithm is acomputational procedure whose steps are completely specified and elementary.1

A program has the instructions that tell the computer what we need done. Each time a computer needs toperform a specific task, it has to follow the same instructions — the computer program — over and overagain.

Also, computers must be given their instructions at a very low level of detail. You can’t just tell thecomputer to perform some task. Instead, you have to give very detailed, specific instructions on how toperform every step of the task.

1Al Kelley & Ira Pohl, A Book on C.

Page 20: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Fundamentals of Computer Programming Using Java

Page 20 Rev 4.1.2 © 2002 ITCourseware, LLC

� The best way to learn about programming is by writing programs.

� The classic program to write, no matter what language you're using, is a programthat prints the words "Hello, world!" on your screen:

// A simple Hello, world program// File: Hello.java// Note: The file name must be the same as the// class name, with .java.

public class Hello {public static void main(String[] args) {

System.out.println("Hello, world");}

}

"Hello, world!"

Page 21: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Basic Concepts and DefinitionsChapter 2

© 2002 ITCourseware, LLC Rev 4.1.2 Page 21

Hands On:

The instructor will lead you through the steps required for the particular programming environment used inthe classroom to write, compile, and execute this program. You'll finish writing, compiling, and running thisprogram before continuing on to the next page.

For each language there are certain rules you, the programmer, must follow.

� For Java programs, you must write your program statements (called "source code") in a file whosename ends in .java.

� Name your source code file for this example Hello.java.

� Java programs are case sensitive: it makes a difference whether you use uppercase (capital) lettersor lowercase letters. Make sure your keyboard's <Caps Lock> key isn't on, and enter thestatements exactly as they're shown on the facing page.

� As you create your program, notice that each statement ends with a semicolon, ; , which marks theend of (terminates) the statement.

� Java is an object-oriented language. In such a language, all of your program code will be placed ina class. The Java programs shown in the examples all use a class, but an explanation of classes willnot be presented until later.

Page 22: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Fundamentals of Computer Programming Using Java

Page 22 Rev 4.1.2 © 2002 ITCourseware, LLC

� The programmer performs several steps when writing a computer program.

1. Write the source code for your program.

2. Compile the source code with an appropriate compiler.

3. Execute the compiled, executable program to test it.

4. Debug the program — find the errors and fix them.

5. Repeat the process as needed.

The Programming Process

Page 23: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Basic Concepts and DefinitionsChapter 2

© 2002 ITCourseware, LLC Rev 4.1.2 Page 23

Source code: the statements of the programming language (the instructions) that you have written to performyour specific application task. You put your source code in a file using any text editor or word processor(make sure you save the file in a text-only mode!).

Executable code: the instructions that have been translated from your source code statements down to themost elementary level — machine instructions — that the computer executes directly.

Source code is much closer to human language than executable code is. Programming languages aredesigned with this in mind. Some languages are terse and somewhat hard to read and are intended forexpert programmers. Others are verbose and more like human languages, with nouns and verbs, and areintended to help nonexpert programmers get started. But when a program is compiled, the compilertranslates the program statements into the same numeric machine instructions, no matter which language wasused for the source code.

The process of writing, compiling, running, changing, compiling, running, changing, compiling, running, etc.will quickly become very natural as you write more programs.

Page 24: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Fundamentals of Computer Programming Using Java

Page 24 Rev 4.1.2 © 2002 ITCourseware, LLC

� Many different files will be created, used, and (sometimes) removed during thecompilation process.

� For languages like Java:

� You will write your program instructions (called statements) in a sourcecode file.

� The compiler will put the translated instructions (called byte code) intowhat is called a class file.

� Your own class file is combined with other class files written by otherprogrammers in your company or with class files that were installed aspart of the Java system.

� To run a Java program, you must use the Java Virtual Machine (VM).The VM reads the byte code produced by the compiler, combines it withbyte code from other classes and executes the program that they contain.

Program Files and Program Execution

Page 25: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Basic Concepts and DefinitionsChapter 2

© 2002 ITCourseware, LLC Rev 4.1.2 Page 25

You have control over the location of the source code and the executable code files. You tell the compilerwhere your source code is and you also tell it where you want it to put the executable file.

Typically these files will be kept in your current working directory or your current folder.

In Java, while the source code file contains the text of the program you have written, the executable codefile contains something called byte code and the file name will have .class on the end. The Java VirtualMachine executes the byte code to run your program.

All other files are located in directories that are known to the compiler. You generally don’t have to worryabout these files; we just want to introduce you to a few terms that you'll encounter again if you continue tolearn about programming languages.

Page 26: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Fundamentals of Computer Programming Using Java

Page 26 Rev 4.1.2 © 2002 ITCourseware, LLC

� System programs are used by the computer for its own operations.

� Operating system programs.

� Language compiler programs.

� Utility programs: editors, sort utilities, text search tools, file displayprograms, etc.

� Application programs perform some user-oriented data processing task.

� Payroll programs.

� Customer tracking programs.

� Inventory programs.

� Accounting programs: accounts receivable programs, accounts payableprograms, etc.

� Game programs.

System Programs vs. Application Programs

Page 27: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Basic Concepts and DefinitionsChapter 2

© 2002 ITCourseware, LLC Rev 4.1.2 Page 27

System programs are written by the computer manufacturer, or some third-party company, to make thecomputer useful to users. Operating system programs allow us to use the computer without having to speakthe binary language that is the computer’s "native tongue," or know the mundane details of its hardwareconfiguration. Language compiler programs take the computer programs we write and translate them intothe language that the computer understands.

Utility programs can be thought of as a subset of system programs. Over the years, programmers havewritten programs for many common tasks that are performed so frequently — sorting, searching, editingtext, and such — that many computer manufacturers include these system utility programs with theircomputers.

Application programs are the programs we write on the user side. We want to use the computer to helpour company do its business better and faster. So, we write computer programs to track, process, andformat the data in ways that are useful to the business goals. Whether it is to process employee data,customer data, corporate data, whatever, these programs typically perform an application — or process —that is useful to our company and are written by the programmers employed by the company.

Page 28: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Fundamentals of Computer Programming Using Java

Page 28 Rev 4.1.2 © 2002 ITCourseware, LLC

� Regardless of the type of application, a computer program almost alwaysperforms three basic functions:

1. Input some data.

� From a file.

� From the keyboard.

2. Process the data.

� Formatting.

� Calculating.

� Searching.

� Sorting.

3. Output the processed data.

� To a file.

� To the screen.

� To a printer.

Input - Process - Output

Page 29: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Basic Concepts and DefinitionsChapter 2

© 2002 ITCourseware, LLC Rev 4.1.2 Page 29

Input involves gathering data from where it is stored and bringing it into your application program so that itcan be manipulated. The payroll program will input the employee data from the employee file on the disk.Other data about the employee may be input from the keyboard where the user is running the program. Thepayroll program may "pass" data as an input to other parts of the payroll program during the payrollprogram’s normal operation.

Process involves manipulating the data in a variety of different ways. The payroll program will process thehours worked and the pay rate for an employee to determine his or her gross pay. The gross pay will befurther processed, along with tax rates, to determine his or her net pay.

Output involves taking the results of the process — and, perhaps, even some of the original input data —and giving it back to the user. The payroll program will output some of its data back to the employee file;other data may be output to the user’s screen; while still other data will be output in the form of paycheckson a printer.

Page 30: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Fundamentals of Computer Programming Using Java

Page 30 Rev 4.1.2 © 2002 ITCourseware, LLC

� Programming languages are to a computer as English, French, Dutch, andGerman are to a human — they're used to communicate.

� The communication we send to the computer is simply a series ofinstructions on how to perform a specific task.

� Different languages can be used to instruct the computer to do the same task.

� Assembly language (or just Assembler): One step away from the numericmachine language the computer uses for its most basic operation;suitable for system-level programs.

� Fortran (FORmula TRANslation): Developed by scientists to help writescientific, or "number crunching," programs.

� COBOL (COmmon Business-Oriented Language): Originally developedby the U.S. Navy to write business programs.

� PL/1 (Programming Language/1): Developed by IBM as a "best of bothworlds" language; supports features of both Fortran and COBOL, as wellas others.

� C (based on an old language named B): Developed at Bell Laboratories;used originally to write system-level software, but later used for all kindsof programs.

� C++ (beyond C): Also developed at Bell Labs as a "better C" withextensions to support object-oriented features.

� Java (as in coffee, which programmers drink a lot of . . .): Developed bySun Microsystems for distributed programming of all kinds; based on Cand others.

Programming Languages

Page 31: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Basic Concepts and DefinitionsChapter 2

© 2002 ITCourseware, LLC Rev 4.1.2 Page 31

In addition to the languages on the facing page, there are many, many more. BASIC, Smalltalk, Jovial,Snobol, RPG, Algol, BCPL, Ada, Pascal, Mumps, Modula, LISP, Euclid, JOSS, APL, Rexx, Python, Tcl,SQL, Awk, KornShell, Perl and many others were developed with particular types of system andapplication programming in mind.

In this immense programming language landscape, only a handful have persisted in widespread use over theyears. Among these, C and most of its derivatives have proven themselves to be robust, well-rounded, andfeature-full languages that are suited for many different types of programming tasks — both systemprograms and application programs. The C programming language has influenced many other languages,partly because it's available on a wider variety of computer systems than perhaps any other language, andpartly because many of the engineers who design new languages first learned programming in C. C++,Java, Perl, Awk, and many other languages copied their basic syntax features from C.

Page 32: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Fundamentals of Computer Programming Using Java

Page 32 Rev 4.1.2 © 2002 ITCourseware, LLC

� Debugging is simply the process of finding and fixing errors that you haveunknowingly placed in your program; there are two types:

� Compiler errors are generated during the compilation of your program.

� These are mistakes that you've made in using the syntax and grammar ofthe language; the compiler can't understand your instructions.

if ( year > )

� If year is greater than what?

� You can't compile your program if there's a compiler error; if yourprogram isn't compiled, you can't run it.

� Runtime errors are generated when you execute (run) your program.

� These are mistakes that you've made in the design and logic of yourprogram; the compiler and the computer understand your instructions, butyou've told it to do something unintended.

Y2k.javaint year = 98;if ( year < 2000 )

System.out.print("You'll be ");else

System.out.print("You were ");System.out.print(2000 - year + age);System.out.println(" years old in the year 2000.");

� year should have been set to 1998, not just 98!

Compiler Errors vs. Runtime Errors

Page 33: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Basic Concepts and DefinitionsChapter 2

© 2002 ITCourseware, LLC Rev 4.1.2 Page 33

Compiler errors generally indicate that you have a wrong instruction, or that an instruction was typedincorrectly, in your program. These are generally easier to fix because you simply have to type in thecorrect syntax for the instruction in your program and try compiling your program again. Most compilerswill even tell you which line contains the error and what sort of error it is.

Runtime errors are generally harder to fix, because they're harder to find. They indicate a logic error in yourprogram. The program compiles correctly, but it does the wrong thing or ends incorrectly withoutproducing the desired results. The program might even work correctly with some data, but incorrectly withother data.

Try It: Compile and run the Y2k program in your chapter directory. Does the output look correct?

Page 34: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Fundamentals of Computer Programming Using Java

Page 34 Rev 4.1.2 © 2002 ITCourseware, LLC

� On some systems you use separate utilities to perform each of the separate stepsin the programming process:

� An editing program (such as notepad or the UNIX vi editor).

� A compiler program (such as the javac command).

� A virtual machine (such as the java command).

� A debugging program (such as jdb).

� Some software vendors provide for all of the steps of the programming processin a single, combined utility program, called an Integrated DevelopmentEnvironment (IDE).

� WebGain Visual Cafe.

� Borland JBuilder.

� IBM Visual Age for Java.

� All compiler vendors adhere to published language standards defining commonsyntax and semantics.

� The products listed above all adhere to standards defined by Sun.

� You only have to learn the language once and then you can use anydevelopment environment.

� Don't confuse learning the programming language with learning the developmentenvironment.

Development Environments

Page 35: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Basic Concepts and DefinitionsChapter 2

© 2002 ITCourseware, LLC Rev 4.1.2 Page 35

It is very important to notice the difference between a particular computer programming language and aparticular development environment. IBM, Borland, WebGain, and others have come out with programsthat provide a user-friendly environment for writing computer programs. The language that you use towrite your programs is the same for each.

Page 36: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Fundamentals of Computer Programming Using Java

Page 36 Rev 4.1.2 © 2002 ITCourseware, LLC

1. What is computer programming?

2. What is an algorithm?

3. What is the purpose of a computer program?

4. Explain the difference between a system program and an application program.

5. List the three steps that most computer programs perform to accomplish theirtask.

6. What are some popular programming languages?

7. List the steps involved in writing a computer program.

8. Name some of the files created during the programming process and where theyare stored.

9. What's the difference between a compiler error and a runtime error?

10. Explain the difference between a programming language and a developmentenvironment.

Review Questions

Page 37: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Basic Concepts and DefinitionsChapter 2

© 2002 ITCourseware, LLC Rev 4.1.2 Page 37

Page 38: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Fundamentals of Computer Programming Using Java

Page 38 Rev 4.1.2 © 2002 ITCourseware, LLC

❶ Change the "Hello, world!" program to print "Hello, " followed by your first name. Compile and runyour modified program.(Solution: HelloName.java)

❷ Change the "Hello, world!" program again to use separate System.out.println(...) callsto print "Hello," followed by your first name on two different lines Compile and run it again (in fact,in each lab exercise from now on, compile and run your program after making the given change).(Solution: TwoPrints.java)

❸ Change the "Hello, world!" program again by inserting one or more \t in one or both of thecharacter strings being printed and look for any differences in the output.(Solution: HelloTabs.java)

❹ Change the "Hello, world!" program yet again. Have it print a row of asterisks above the text andanother line of asterisks below.

Add an asterisk at the beginning and the end of each line of the message itself. Experiment usingspaces and tabs, and see if you can get the message to appear in the center of a box made up ofasterisks.(Solution: HelloStars.java)

❺ Write a new program that prints the following on the screen:

Testing ...... 1 ...

... 2 ...... 3 ...

Can this program be written with one System.out.println(...) call? . . . with more thanone?(Solution: Testing123.java)

Labs

Page 39: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Basic Concepts and DefinitionsChapter 2

© 2002 ITCourseware, LLC Rev 4.1.2 Page 39

You will find that the labs in this workbook contain more exercises than can be completed during a normallab session in class. There are several reasons for this:

� To provide a selection of exercises from which you can choose.

� To leave many exercises you can work on in your own time, at work or at home.

� To provide additional challenges for students who already have some programming experience.

So, don't worry if you don't finish all, or even most, of the labs in the time available during class. Just start atthe beginning and keep working until the lab session is over.

Page 40: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Fundamentals of Computer Programming Using Java

Page 40 Rev 4.1.2 © 2002 ITCourseware, LLC

Page 41: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

LoopingChapter 8

© 2002 ITCourseware, LLC Rev 4.1.2 Page 147

Chapter 8 - Looping

Objectives

� Explain what looping is.

� Write programs using iterative loops.

� Use code blocks to containstatements in loops.

� Choose when to use nested loops ina program.

� Write programs using conditionalloops.

� Explain what an infinite loop is.

� Use a break to exit a loop early.

Page 42: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Fundamentals of Computer Programming Using Java

Page 148 Rev 4.1.2 © 2002 ITCourseware, LLC

� A loop is a control statement — it controls the execution of other statements.

� A loop executes its controlled statement(s) many times, over and over again.

� There are two types of loops:

� An iterative loop executes its statement(s) a predefined number of times.

� A conditional loop executes its statement(s) as long as some condition istrue, evaluating a conditional expression.

� When your program reaches a loop statement, it stops sequential execution and"loops through" the controlled statements.

� When the looping finishes, your program picks back up with sequentialexecution, starting at the next statement after the loop.

Kinds of Loops

Page 43: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

LoopingChapter 8

© 2002 ITCourseware, LLC Rev 4.1.2 Page 149

An everyday loop:

1. Lather.2. Rinse.3. Repeat (once).

Another:

While there's still at least one dirty dish in the pile:1. Get a dirty dish from the pile and place it in the soapy water.2. Wash the dish clean.3. Place the dish in the rinse water.4. Rinse the dish.5. Remove the dish from the rinse water and place it in the drying rack.6. Check the pile for dirty dishes.

Have a drink (the best wine is in the dusty bottles in the back).

Page 44: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Fundamentals of Computer Programming Using Java

Page 150 Rev 4.1.2 © 2002 ITCourseware, LLC

� An iterative loop executes its controlled statement a specific number of times.

� Iterative loops are often called for loops because they repeat for a certainnumber of times.

� In some languages, the for loop automatically keeps track of whichiteration it's on.

-- Iterative loop in Oracle PL/SQL:FOR i IN 1 .. 10 LOOP

DBMS_OUTPUT.PUT_LINE(i);END LOOP;

� In other languages, like Java, you use expressions to keep the count andto check whether you've reached the end.

// Iterative loop in Java:int i;for ( i = 1; i <= 10; i = i + 1 )

System.out.println(i);

� The variable in which you keep track of the count is called the loopcontrol variable.

� The loop control variable can be incremented (increased by one) ordecremented (decreased by one).

int t;for ( t = 10; t > 0; t = t - 1 )

System.out.println("T minus " + t);System.out.println("Liftoff!");

Iterative Loops

Page 45: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

LoopingChapter 8

© 2002 ITCourseware, LLC Rev 4.1.2 Page 151

The Java for loop is a classic iterative loop. You determine how many times it executes, using threeexpressions and a loop control variable:

int loop-control-variable;for (initialization; test-expression; increment-expression) statement;

The first expression initializes the loop control variable to a beginning value; the second expression tests tosee if the control variable is within limits; and the third expression increments the control variable so that iteventually fails the second test, stopping the loop.

int i;for ( i = 0; i < 10; i = i + 1 )

System.out.println(i);

Note the two semicolons, which separate the three expressions inside the parentheses. You cannot leaveout either of the semicolons. The first expression is executed only once, when your program reaches thefor loop. Then, each time, before the loop's controlled statement is executed, the second expression isevaluated. If it's true, the loop's controlled statement is executed; if false, the loop ends. Finally, if theloop's controlled statement was executed, the for loop then “loops back up” and evaluates the thirdexpression.

Hands On:

Write a new program using a for loop to print the numbers from 1–10 on your terminal screen. Get this towork before you go on to the next page.

Investigate:

In the expression that increments your loop control statement, instead of using syntax like i = i + 1, trychanging the expression to look something like i += 1. If that works, try changing it to i++.

What do you think these new operators do?

Page 46: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Fundamentals of Computer Programming Using Java

Page 152 Rev 4.1.2 © 2002 ITCourseware, LLC

� Loops that need to execute more than one statement per iteration use a block.

for ( n = 1; n < 10; n = n + 1 ){

System.out.print("Value is: " + n);System.out.print("\t Square is: " + (n * n));System.out.println("\t Cube is: " + (n * n * n));

}

� If the loop body contains only one statement, braces may not be needed, but itlooks nice:

for (a = 0; a < 10; a = a + 1){

System.out.println("The count is: " + a);}

Code Blocks and Loops

Page 47: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

LoopingChapter 8

© 2002 ITCourseware, LLC Rev 4.1.2 Page 153

Anywhere you can code a single statement, you can code a block of statements. If you need to have morethan one statement in your loop body, enclose them in braces. Notice that braces themselves are notterminated by a semicolon.

for (i = 10; i >= 0; i = i - 1){

System.out.println("—————");System.out.println("Count down: " + i);

}

The indentation style shown is typical. You may decide to do something else — just be consistent.

Investigate:

Notice also that there's no semicolon after the parentheses containing the loop control expressions. If youmake a mistake and put a semicolon there,

for (i = 10; i >= 0; i = i - 1);{

System.out.println("—————");System.out.println("Count down: " + i);

}

. . . your program will still compile (it's not a compiler error!). But when your program runs, what willhappen? The compiler knows what it will do. Do you? Try it and see if you can figure out what happened.

Page 48: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Fundamentals of Computer Programming Using Java

Page 154 Rev 4.1.2 © 2002 ITCourseware, LLC

� When you put one loop statement, such as a for loop, inside another loopstatement, you have created a nested loop.

� Stated another way, a nested loop is one that is under the control of anotherloop.

for (num = 1; num <= 10; num = num + 1){

for (factor = 1; factor <= 10; factor = factor + 1)System.out.print(num * factor + "\t");

System.out.println();}

� How many times does the second output statement execute?

� Notice how the inner loop's control variable "starts over," i.e., gets re-initialized,every time the outer loop's control variable increments.

� The outer loop is like a big sprocket, and the inner loop like a little sprocket.

� For each turn of the outer loop, the inner loop turns many times.

Nested Loops

Page 49: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

LoopingChapter 8

© 2002 ITCourseware, LLC Rev 4.1.2 Page 155

MultTable.java

public class MultTable {public static void main(String[] args) {

int num = 0;int factor = 0;

for (num = 1; num <= 10; num = num + 1){

for (factor = 1; factor <= 10; factor = factor + 1){

System.out.print((num * factor) + "\t");}System.out.println();

}}

}

Notice how the braces and the indentation style show which statements are controlled by which loop.

Try It: This example prints a multiplication table.

Page 50: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Fundamentals of Computer Programming Using Java

Page 156 Rev 4.1.2 © 2002 ITCourseware, LLC

� Conditional loops are often called while loops because they keep repeatingwhile a condition is true.

� A conditional loop has only one expression — typically a relational expression— to control the operation of the loop.while (number != 0) {

sum = sum + number;System.out.print("Enter another number (0 to quit): ");inputBuffer = buf.readLine();number = Integer.parseInt(inputBuffer);

}

� The loop evaluates its test expression each time it executes:

� The loop continues looping if the result is true.

� The loop stops looping if the result is false.

� The expression is evaluated before the loop is first executed, and it is possiblethat the body of the loop may never execute at all.int number = 0; // Oops, loop will never happen ...while (number != 0) {

sum = sum + number;System.out.print("Enter another number (0 to quit): ");inputBuffer = buf.readLine();number = Integer.parseInt(inputBuffer);

}

� Some languages have loops that do the first test at the bottom, after executingonce.do {

sum = sum + number;System.out.print("Enter another number (0 to quit): ");inputBuffer = buf.readLine();number = Integer.parseInt(inputBuffer);

} while (number != 0); // Note the semicolon here.

Conditional Loops

Page 51: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

LoopingChapter 8

© 2002 ITCourseware, LLC Rev 4.1.2 Page 157

The Java while loop is a classic conditional loop. It loops through and executes the statements it controls— its body — as long as the expression evaluates as true.

while ( expression )statement;

� while is the required keyword.� while is followed by an expression, always enclosed by a pair of parentheses.� The statement after the while expression will be executed if the expression is true.� After the statement is executed, the expression is evaluated again.� This continues until expression is false.

As always, you can use a code block as the statement. It's called the loop body, whether it's a singlestatement or a block.

Sum.javaimport java.io.*;

public class Sum {public static void main(String[] args) throws IOException {

InputStreamReader conv = new InputStreamReader(System.in);BufferedReader buf = new BufferedReader(conv);String inputBuffer;int sum = 0;int number = 0;

System.out.print("Enter a number: ");inputBuffer = buf.readLine();number = Integer.parseInt(inputBuffer);

while (number != 0) {sum = sum + number;System.out.print("Enter another number (zero to quit): ");inputBuffer = buf.readLine();number = Integer.parseInt(inputBuffer);

}System.out.println("The total is: " + sum);

}}

Try It: Compile and run Sum.java. When you're ready for the sum to be displayed, enter 0.

Page 52: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Fundamentals of Computer Programming Using Java

Page 158 Rev 4.1.2 © 2002 ITCourseware, LLC

� An infinite loop is one that doesn’t know when to stop; it loops forever.

� Since an infinite loop will make your program run forever, there has to be a wayto get out of the loop.

� A break statement tells a loop to end, and resume sequential execution atthe next statement after the loop body.

while (true){

...if (choice == 'q' || choice == 'Q')

break;}System.out.println("You’re out of the loop.");

� A break statement is usually controlled by an if statement.

� You may wonder "Why?"; but infinite loops have many uses.

� If a program presents a menu, you choose an option, and then you arepresented with the menu again, you are using an infinite loop.

� The loop will continue until you break out of it by entering the"quit" option.

� Your operating system command interpreter operates in an infinite loopwhile prompting you for commands.

� The loop will continue until you break out of it by entering thecommand to exit.

Infinite Loops

Page 53: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

LoopingChapter 8

© 2002 ITCourseware, LLC Rev 4.1.2 Page 159

You can make an infinite for loop by leaving out all of the expressions:

for (;;) // An infinite for loop has no expressions{

...}

You can make an infinite while loop by using any constant, true value for the conditional expression.

while (1 != 0) // This is always true! 1 is never equal to 0.{

...}

You may see Java infinite while loops written like this:

while (true){

...}

The words true and false are constants in the Java language — essentially keywords or reservedwords. They are the only two values that a boolean variable can be assigned or can result from theevaluation of a boolean expression. Other languages may use integer values such as 1 and 0 to representtrue and false.

A break statement alters the normal execution of the body of the loop by telling the loop to quit — rightnow, right away. Execution will pick back up with the first statement that occurs after the loop.

Page 54: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Fundamentals of Computer Programming Using Java

Page 160 Rev 4.1.2 © 2002 ITCourseware, LLC

SimpleMenu.javaimport java.io.*;

public class SimpleMenu {public static void main(String[] args) throws IOException {

InputStreamReader conv = new InputStreamReader(System.in);BufferedReader buf = new BufferedReader(conv);String inputBuffer = "";int resp = 0;float num1 = 0.0F, num2 = 0.0F;String cont;

while(true) {System.out.println(" Arithmetic Menu");System.out.println(" ———————");System.out.println(" Option Description");System.out.println(" ——— ————————————");System.out.println(" 0 Exit");System.out.println(" 1 Add two numbers");System.out.println(" 2 Subtract two numbers");System.out.println(" 3 Multiply two numbers");System.out.println(" 4 Divide two numbers\n");

System.out.print(" Please choose an option: ");resp = Integer.parseInt(buf.readLine());

if(resp == 0)break;

switch(resp) {case 1:

System.out.println("Adding two numbers ...");System.out.print("Enter the first number: ");num1 = Float.parseFloat(buf.readLine());System.out.print("Enter the second number: ");num2 = Float.parseFloat(buf.readLine());System.out.println(num1 + " + " + num2 + " = "

+(num1+num2));break; // only breaks out of the switch

Example 8 - A Simple Menu Program

Page 55: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

LoopingChapter 8

© 2002 ITCourseware, LLC Rev 4.1.2 Page 161

case 2:System.out.println("Subtracting two numbers ..");System.out.print("Enter the first number: ");num1 = Float.parseFloat(buf.readLine());System.out.print("Enter the second number: ");num2 = Float.parseFloat(buf.readLine());System.out.println(num1 + " - " + num2 + " = "

+(num1-num2));break;

case 3:System.out.println("Multiplying two numbers ...");System.out.print("Enter the first number: ");num1 = Float.parseFloat(buf.readLine());System.out.print("Enter the second number: ");num2 = Float.parseFloat (buf.readLine());System.out.println(num1 + " * " + num2 + " = "

+(num1 * num2));break;

case 4:System.out.println("Dividing two numbers ..." );System.out.print("Enter the first number: ");num1 = Float.parseFloat(buf.readLine());System.out.print("Enter the second number: ");num2 = Float.parseFloat(buf.readLine());System.out.println(num1 + " / " + num2 + " = "

+(num1 / num2));break;

default:System.err.println("Invalid response. ");break;

}

System.out.print("Type a c to continue: ");cont = buf.readLine();

}}

}

Page 56: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Fundamentals of Computer Programming Using Java

Page 162 Rev 4.1.2 © 2002 ITCourseware, LLC

Review Questions

1. What's the difference between an iterative loop and a conditional loop?

2. What is the common name for an iterative loop?

3. What is the common name for a conditional loop?

4. What is the term for the statement or group of statements controlled by a loop?

5. What is a nested loop?

6. What is an infinite loop? How is an infinite loop stopped?

Page 57: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

LoopingChapter 8

© 2002 ITCourseware, LLC Rev 4.1.2 Page 163

Page 58: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Fundamentals of Computer Programming Using Java

Page 164 Rev 4.1.2 © 2002 ITCourseware, LLC

❶ a. Write a program that uses a for loop to print out the first 16 multiples of 2.(Solution: Mult2.java)

b. Make a copy of your solution and modify it so that, in addition to printing the first 16multiples of 2, it also prints the first 16 powers of 2. Have both the multiple and the powerprint on the same line.(Solution: Pow2.java)

❷ Modify your temperature conversion program from the previous chapter and use a loop that willallow for 5 different temperatures to be input and converted.(Solution: LoopFahrCels.java)

❸ a. The Fibonacci series is a series of numbers in which the first two numbers are 0 and 1.Each subsequent number is the sum of the previous two. So, the third Fibonacci number is(0 + 1) = 1. The next is (1 + 1) = 2. Then (1 + 2) = 3. Then (2 + 3) = 5. Then (3 + 5) =8. And so on. The Fibonacci series has many interesting mathematical properties andshows up in surprising places in nature.

Write a program that uses a for loop to print the first 20 Fibonacci numbers. Rememberthat the first two (known as f0 and f1) are predefined as 0 and 1. All subsequent numbersare calculated from there.(Solution: Fib.java)

b. Modify your solution (if necessary) so that the sequence number is printed out next to thefibonacci value. Make sure that sequence numbers 0 and 1 match up with the first twopredefined values:

0: 01: 12: 13: 24: 35: 56: 87: 13...

(Solution: FibNum.java)

Continued . . .

Labs

Page 59: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

LoopingChapter 8

© 2002 ITCourseware, LLC Rev 4.1.2 Page 165

You've now learned enough programming fundamentals to start writing some more interesting programs.Conditionals, loops, variables and data types, input and output — putting these together so that thecomputer does what you want it to do is the programmer's craft and profession.

This chapter includes a large number of lab exercises for you to work on both during the lab session in class,and later, on your own time. You'll probably finish just a few of these during the lab session. Doing more ofthese exercises on your own, at your own pace, is the best way to reinforce and practice both the syntax ofthe language you're writing your programs in and the kind of logical thinking and problem solving allprogrammers must master.

Page 60: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Fundamentals of Computer Programming Using Java

Page 166 Rev 4.1.2 © 2002 ITCourseware, LLC

❹ Write a program that uses nested for loops to print a multiplication table for the integers -5 through5. For each integer, print all of its multiples on a single line. You might want to start with a copy ofMultTable.java.(Solution: MultTable5.java)

❺ Write a program that uses nested for loops to print a table of the first 8 powers of the first 10integers.Hint: You might want to start with a copy of MultTable.java.(Solution: PowTable.java)

❻ Modify your calculator program from the previous chapter, using a loop to allow for as manydifferent calculations as the user wants to do. When both input numbers are 0, then break out of theloop and end the program.(Solution: LoopCalc.java)

❼ (Optional) Make a copy of your solution to ❸, the Fibonacci number exercise. Modify the copyto calculate only the first 10 Fibonacci numbers. Instead of printing the value of the Fibonaccinumber, use a nested for loop to print a row of asterisks whose length is the current Fibonaccinumber.

If you get this working, then experiment. What happens if you calculate 15 Fibonacci numbers?How about 20?(Solution: FibGraph.java)

❽ Write a program with a for loop nested inside another for loop. Have the outer loop simply printout the value of its loop control variable, from 1 to 20. In the inner loop, don't print anything!Start by having the inner loop assign the same value to a variable 1000 times. Run your programand see how long it takes for the outer loop to finish. Keep modifying your program, increasing thenumber of times the inner loop iterates.Hint: add zeros to the number.How many times must the inner loop run before you see a noticeable slowdown in the outer loop?This technique is called a software delay.(Solution: Delay.java)

Continued . . .

Labs (contd.)

Page 61: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

LoopingChapter 8

© 2002 ITCourseware, LLC Rev 4.1.2 Page 167

Page 62: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Fundamentals of Computer Programming Using Java

Page 168 Rev 4.1.2 © 2002 ITCourseware, LLC

Labs (contd.)

❾ Write a program that prints the factorials of the integers from 1 to 10. The factorial of a number Nis the product of all numbers less than or equal to N: factorial 1 (1!) is just one. 2! is (1 * 2) = 3.3! is (1 * 2 * 3) = 6. 4! is (1 * 2 * 3 * 4) = 24. And so on. Have your program print the results ina tabular format:

1! = 12! = 23! = 64! = 24...

When you get your program working, experiment: What's the highest factorial the computer cancorrectly calculate? (Solution: Factorial.java)

❿ a. Write a program with an infinite loop, reading a floating-point number from the user at eachiteration. The program should maintain the sum of the numbers entered so far. Have theprogram exit when the user enters zero. At each iteration, print the last number entered, andthe current sum. Print the data in a tabular format:

Entered Sum12 129 2114.3 35.3...

(Solution: RunningSum.java)

b. Modify your solution so that in addition to the running sum, the program also calculates theaverage of the numbers so far. Have it print the average, as well as the count of thenumbers entered so far.(Solution: RunningSumAvg.java)

c. Modify your solution so that it also prints the largest and smallest numbers entered so far.(Solution: RunningStats.java)

Continued . . .

Page 63: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

LoopingChapter 8

© 2002 ITCourseware, LLC Rev 4.1.2 Page 169

Page 64: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Fundamentals of Computer Programming Using Java

Page 170 Rev 4.1.2 © 2002 ITCourseware, LLC

Labs (contd.)

❿ d. An alternative algorithm for calculating a running average is:

average = (previous average) + ((new number - previous average) / count)

Modify your program to maintain the average calculated this way, in addition to the moretraditional way. Compare the results. Is there any situation in which one algorithm is betterthan the other?(Solution: RunningAvg.java)

Employee Program Project

Put your employee program into an infinite loop. Make sure the exit option works so the user canend the program.(Solution: LoopEmployeeMenu.java)

Page 65: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

LoopingChapter 8

© 2002 ITCourseware, LLC Rev 4.1.2 Page 171

Page 66: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Fundamentals of Computer Programming Using Java

Page 172 Rev 4.1.2 © 2002 ITCourseware, LLC

Page 67: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Working with FilesChapter 13

© 2002 ITCourseware, LLC Rev 4.1.2 Page 253

Chapter 13 - Working with Files

Objectives

� Describe the three steps forperforming file input and output in aprogram.

� Open a file for either reading orwriting.

� Write programs that read input froma file.

� Save program data in an output file.

� State the definition of text file.

� Create text and binary files anddescribe the differences betweenthem.

Page 68: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Page 254 Rev 4.1.2 © 2002 ITCourseware, LLC

Fundamentals of Computer Programming Using Java

� To read input from the keyboard, your program simply reads from the standardinput device; to write output, your program just writes to the standard outputdevice.

� Most programs save data (the values of variables) in disk files.

� This is called writing to a file, or simply writing a file.

� Most programs retrieve (and store in variables) data from disk files.

� This is called reading from a file, or reading a file.

� To read input from a file or write output to a file, your program must performthree steps:

1. Open the file.2. Read and write the data.3. Close the file.

� These three steps have to happen, no matter which language you use.

� Most programming languages treat the terminal screen and keyboard as thoughthey were files.

� Some languages even let you use the same (or similar) I/O statements,functions, or operators.

� Usually, the operating system "opens" the keyboard and screen for youwhen your program starts running.

� So, once you've learned how to do terminal input and output, file I/O is easy!

Terminal I/O and File I/O

Page 69: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Working with FilesChapter 13

© 2002 ITCourseware, LLC Rev 4.1.2 Page 255

Page 70: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Page 256 Rev 4.1.2 © 2002 ITCourseware, LLC

Fundamentals of Computer Programming Using Java

� Opening a disk file from within a program prepares the file for input or outputoperations:

� You must know the name of the file.

� You must specify whether you are going to read from the file, write to thefile, or do both.

� Some systems also require you to specify whether you are opening a textfile or a binary file.

� If you open a file for reading, it must exist before you can open it.

� If you open a file for writing, it does not have to exist.

� If it doesn't exist, it will be created.

� If it does exist, it may get erased first.

� Once you've opened the file, it's represented in your program by a variable orobject called a file handle, file object or file variable.

� You use this variable (not the file name) to read from or write to the file.

Opening Files

Page 71: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Working with FilesChapter 13

© 2002 ITCourseware, LLC Rev 4.1.2 Page 257

To perform file input and output in java, you must import the I/O classes and methods:

TextOut.javaimport java.io.*;

public class TextOut {...

}

Page 72: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Page 258 Rev 4.1.2 © 2002 ITCourseware, LLC

Fundamentals of Computer Programming Using Java

� Use the file variable to open a file for output.

� Provide the file name when you create the file object.

� As your program moves through an opened file, the operating system maintainsa pointer to the current position in the file.

� When you open a file for writing, the pointer is placed at the beginning of thefile.

� If the file doesn't exist, it will be created.

� If the file does exist, its contents will be erased!

� To append data to the end of an existing file, you'll need to open it using alanguage-specific syntax that will place the pointer at the end of the file.

� Once the file has been successfully opened, use the file variable to write programdata to the file.

� Note that we close the file when we're done (more about that later).

Opening a File for Writing

Page 73: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Working with FilesChapter 13

© 2002 ITCourseware, LLC Rev 4.1.2 Page 259

This opens a file calledfood.txt for writing.

To open a file for output (writing) in Java, you must declare an object of type FileWriter. Use thevariable to open the file, passing the file name. Then you convert the FileWriter to a PrintWriter:

TextOut.javaimport java.io.*;

public class TextOut {public static void main(String[] args) throws IOException {

String companyOne = "Pam's Pizza";String companyTwo = "Bob's Burgers";

FileWriter txtOut = new FileWriter("food.txt");PrintWriter printOut = new PrintWriter(txtOut);

printOut.println(companyOne);printOut.println(companyTwo);

txtOut.close();

}}

To write output to the file, you use the PrintWriter object just like you use System.out.

Try It: When you compile and run TextOut.java, a file called food.txt is created and written to. Youcan open food.txt with a text editor to see its contents.

Page 74: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Page 260 Rev 4.1.2 © 2002 ITCourseware, LLC

Fundamentals of Computer Programming Using Java

� Use the file variable to open a file for input; provide the file name in the openstatement.

� Reading data copies information from the file into your program's variables.

� You must declare variables of the correct type and size for the data to beread from the file.

� Your language may require different kinds of read statements for differentdatatypes (int, float, character, etc.).

� The pointer is advanced with each read.

� The next read will occur wherever the pointer was left by the previousread.

� After your program has read all the data, the pointer is at EOF (End OfFile).

� Your program can check for this after each read, so it doesn't haveto know the file size when it starts.

� The language may provide a means of positioning the pointer anywhere in thefile you want.

� The position is specified in characters or bytes — the pointer is at byte 0of the file (the beginning), byte 10 (after reading 10 bytes), etc.

Opening a File for Reading

Page 75: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Working with FilesChapter 13

© 2002 ITCourseware, LLC Rev 4.1.2 Page 261

This opens a file calledfood.txt for reading.

To open a file for input (reading) in Java, you must declare an object of type FileReader. Use thevariable to open the file, passing the file name. Then you convert the FileReader to aBufferedReader:

TextIn.javaimport java.io.*;

public class TextIn {public static void main(String[] args) throws IOException {

String companyOne = null;String companyTwo = null;

FileReader txtIn = new FileReader("food.txt");BufferedReader readIn = new BufferedReader(txtIn);

companyOne = readIn.readLine();companyTwo = readIn.readLine();txtIn.close();

System.out.println(companyOne);System.out.println(companyTwo);

}}

Try It: This example reads the food.txt file that was created in the previous example.

Page 76: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Page 262 Rev 4.1.2 © 2002 ITCourseware, LLC

Fundamentals of Computer Programming Using Java

� If the attempt to open a file fails, there's no point in trying to perform I/O withthe file.

� The failure may be due to a nonexistent file, an access permissionproblem, or a number of other factors.

� In case of an open failure, your program should alert the user.

� The result of the open statement (or the value of the file variable) will tell you ifan attempted open failed.

try {FileReader txtIn = new FileReader("food.txt");BufferedReader readIn = new BufferedReader(txtIn);...

}catch(IOException e) {

System.err.println(e.getMessage());e.printStackTrace();System.exit(10);

}

Checking for File Open Errors

Page 77: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Working with FilesChapter 13

© 2002 ITCourseware, LLC Rev 4.1.2 Page 263

Never open a file without checking for a failure!

TextErr.javaimport java.io.*;

public class TextErr {public static void main(String[] args)throws IOException {

String companyOne = null;String companyTwo = null;

FileReader txtIn = new FileReader("food.xxx");BufferedReader readIn = new BufferedReader(txtIn);

companyOne = readIn.readLine();companyTwo = readIn.readLine();txtIn.close();

System.out.println(companyOne);System.out.println(companyTwo);

}}

Try It: Compile and run TextErr.java. What happens (assuming you don't have a food.xxx file)?

Page 78: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Page 264 Rev 4.1.2 © 2002 ITCourseware, LLC

Fundamentals of Computer Programming Using Java

� Closing a file tells the operating system that you're finished using the file.

� You don't close the file by its name; you use the file variable.

conv.close();

� Most operating systems temporarily store (buffer) in memory the output of all ofyour program's write statements.

� It actually puts the buffered data into the file (flushes the buffer) onlywhen the memory buffer is full.

� This makes the computer faster by reducing the number of times ithas to talk to the disk.

� The operating system must perform a number of tasks to ensure that the file is inthe correct state as you close it.

� It has to make sure that all of the data written by your program is actuallyin the file (flush the output buffer or buffers).

� It has to release the buffers that were used with the file.

� There may be other housekeeping tasks the system must do.

� Many systems automatically close all your open files when your program ends;but it is usually a good idea to go ahead and close them yourself in yourprogram.

Closing a File

Page 79: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Working with FilesChapter 13

© 2002 ITCourseware, LLC Rev 4.1.2 Page 265

Once the file has been successfully opened and you have finished all of the reading and writing you want todo, remember to close the file:

IoText.javaimport java.io.*;import java.text.DecimalFormat;

class CustRecord {String custName;String custPhone;int custNumber;float creditLimit;

}public class IoText{

public static void main(String[] args) throws IOException {

DecimalFormat precisionTwo = new DecimalFormat("0.00");CustRecord custRec = new CustRecord();custRec.custName = "Sidney Q. Flarp";custRec.custPhone = "555/123-4567";custRec.custNumber = 98765;custRec.creditLimit = 1000.00F;

FileWriter txtOut = new FileWriter("customer.txt");PrintWriter printOut = new PrintWriter(txtOut);

printOut.println(custRec.custName);printOut.println(custRec.custPhone);printOut.println(custRec.custNumber);printOut.println(precisionTwo.format(custRec.creditLimit));txtOut.close();String inputBuffer = null;FileReader conv = new FileReader("customer.txt");BufferedReader buf = new BufferedReader(conv);inputBuffer = buf.readLine();System.out.println("Customer name:\t" + inputBuffer);inputBuffer = buf.readLine();System.out.println("Customer phone:\t" + inputBuffer);inputBuffer = buf.readLine();System.out.println("Customer num.:\t" + inputBuffer);inputBuffer = buf.readLine();System.out.println("Credit limit:\t" + inputBuffer);conv.close();

}}

Page 80: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Page 266 Rev 4.1.2 © 2002 ITCourseware, LLC

Fundamentals of Computer Programming Using Java

� The terms text file and binary file refer to the type of data in the file.

� Many systems (such as UNIX) make no particular distinction betweenfiles containing text and files containing binary data.

� The distinction is very important to programs you write and use, though.

� A text file contains lines of text separated by newline characters and has anewline as the last character of the file.

� You can create and read text files with any text editor.

� A binary file can contain text, integers, floating point data, compiled programcode, encrypted data, anything.

� Only a specific program can do anything useful with a binary file.

� To write a program to read or write a binary file, you must know the layout ofthe file so that you can declare appropriate variables and data structures.

� Some systems require that you open the file in a different way in order toperform binary I/O.

Text Files vs. Binary Files

Page 81: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Working with FilesChapter 13

© 2002 ITCourseware, LLC Rev 4.1.2 Page 267

FileOutputStream andFileInputStream are

used for binary files.

In Java, if you want to open a file for binary output operations, you must open it differently:

IoBinary.javaimport java.io.*;import java.text.DecimalFormat;

class CustRecord {String custName;String custPhone;int custNumber;float creditLimit;

}public class IoBinary {

public static void main(String[] args) throws IOException {

DecimalFormat precisionTwo = new DecimalFormat("0.00");CustRecord custRecOut = new CustRecord();custRecOut.custName = "Sidney Q. Flarp";custRecOut.custPhone = "555/123-4567";custRecOut.custNumber = 98765;custRecOut.creditLimit = 1000.00F;

FileOutputStream binOut = new FileOutputStream("customer.bin");DataOutputStream writeOut = new DataOutputStream(binOut);

writeOut.writeUTF(custRecOut.custName);writeOut.writeUTF(custRecOut.custPhone);writeOut.writeInt(custRecOut.custNumber);writeOut.writeFloat(custRecOut.creditLimit);

binOut.close();CustRecord custRecIn = new CustRecord();

FileInputStream binIn = new FileInputStream("customer.bin");DataInputStream readIn = new DataInputStream(binIn);

custRecIn.custName = readIn.readUTF();System.out.println("Customer name:\t" + custRecIn.custName);custRecIn.custPhone = readIn.readUTF();System.out.println("Customer phone:\t" + custRecIn.custPhone);custRecIn.custNumber = readIn.readInt();System.out.println("Customer num.:\t" + custRecIn.custNumber);custRecIn.creditLimit = readIn.readFloat();System.out.println("Credit limit:\t" +

precisionTwo.format(custRecIn.creditLimit));

binIn.close();

}}

Page 82: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Page 268 Rev 4.1.2 © 2002 ITCourseware, LLC

Fundamentals of Computer Programming Using Java

Example 13 - A Customer Record in a File

CustomerFile.javaimport java.io.*;import java.text.DecimalFormat;

class CustRecord {String custName;String custPhone;int custNumber;float creditLimit;

}

public class CustomerFile {public static void main(String[] args) throws IOException {

int custCount;

custCount = inputCustRecords();outputCustRecords(custCount);

}

public static int inputCustRecords() throws IOException {

int count = 0;String inputBuffer = null;CustRecord cust = new CustRecord();

InputStreamReader conv = new InputStreamReader(System.in);BufferedReader buf = new BufferedReader(conv);FileOutputStream binOut = new FileOutputStream("customer.bin");DataOutputStream writeOut = new DataOutputStream(binOut);

for(count = 0; count < 100; count = count + 1) {System.out.print("Please enter the customer's name: ");cust.custName= buf.readLine();System.out.print("Please enter the customer's phone number: ");cust.custPhone= buf.readLine();System.out.print("Please enter the customer's customer number: ");inputBuffer = buf.readLine();cust.custNumber = Integer.parseInt(inputBuffer);System.out.print("Please enter the customer's credit limit: ");inputBuffer = buf.readLine();cust.creditLimit = Float.parseFloat(inputBuffer);writeOut.writeUTF(cust.custName);

Page 83: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Working with FilesChapter 13

© 2002 ITCourseware, LLC Rev 4.1.2 Page 269

writeOut.writeUTF(cust.custPhone);writeOut.writeInt(cust.custNumber);writeOut.writeFloat(cust.creditLimit);

System.out.print("\nDo you want to add another customer? " +"(y/n): ");

inputBuffer = buf.readLine();if(inputBuffer.charAt(0) == 'n' || inputBuffer.charAt(0)

== 'N')break;

}

binOut.close();

return count;}

public static void outputCustRecords(int custCount)throws IOException {

int count;DecimalFormat formatNumber = new DecimalFormat("00000000");DecimalFormat formatLimit = new DecimalFormat("0000000000.00");CustRecord cust = new CustRecord();

System.out.println("------------------ Customer File" +" ------------------");

System.out.println("Cust. #- Credit Limit- Phone" +" ------- Name-----------");

FileInputStream binIn = new FileInputStream("customer.bin");DataInputStream readIn = new DataInputStream(binIn);

for(count = 0; count <= custCount; count = count + 1){cust.custName = readIn.readUTF();cust.custPhone = readIn.readUTF();cust.custNumber = readIn.readInt();cust.creditLimit = readIn.readFloat();

System.out.print(formatNumber.format(cust.custNumber) + " ");System.out.print(formatLimit.format(cust.creditLimit) + " ");System.out.print(cust.custPhone + " ");System.out.println(cust.custName);

}

binIn.close();}

}

Page 84: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Page 270 Rev 4.1.2 © 2002 ITCourseware, LLC

Fundamentals of Computer Programming Using Java

1. What are the differences between terminal I/O and file I/O? Are there anysimilarities?

2. What three steps are always necessary for file I/O?

3. Why do you close a file?

4. What is a text file?

5. What are the differences between text and binary files, related to I/O?

Review Questions

Page 85: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Working with FilesChapter 13

© 2002 ITCourseware, LLC Rev 4.1.2 Page 271

Page 86: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Page 272 Rev 4.1.2 © 2002 ITCourseware, LLC

Fundamentals of Computer Programming Using Java

❶ Write a program that writes "Hello, world!" to a file. View the file with a text editor to see if yourprogram worked.(Solution: HelloFile.java)

❷ Using a text editor, create a file with several lines of text. Write a program to read the lines from thefile (in a loop) and display them.(Solution: ReadLines.java)

❸ Using a text editor, create a file containing a list of floating point numbers, one number per line.Write a program to read the numbers into an array, and then compute and print their average.(Solution: ReadNumbers.java)

Employee Program Project

Modify the program to use a binary file to store the employee data. Write a method that reads thefile into an array when the program starts, before the menu gets displayed. When the exit optionis chosen, write the data back out to the file (in a method, of course).

There is a special condition you will have to take into account in this exercise: the very first time youexecute the program, the data file will not exist. To handle this case, open the file for reading firstand then check for an error. If you receive an error from the open attempt, the file does not existand you don't have to read anything into the array. The first user-entered record will go into the firstelement of the array.(Solution: FileEmployeeMenu.java)

Labs

Page 87: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Working with FilesChapter 13

© 2002 ITCourseware, LLC Rev 4.1.2 Page 273

Page 88: Fundamentals of Computer Programming Using Java · Fundamentals of Computer Programming Using Java Page 10 Rev 4.1.2 © 2002 ITCourseware, LLC Explain what computer programs are and

Page 274 Rev 4.1.2 © 2002 ITCourseware, LLC

Fundamentals of Computer Programming Using Java