archive-edu.com » EDU » H » HWS.EDU

Total: 727

Choose link from "Titles, links and description words view":

Or switch to "Titles and links view".
  • Java Programming, Main Index
    Programming in the Large I Subroutines Chapter 5 Programming in the Large II Objects and Classes Chapter 6 Applets HTML and GUI s Chapter 7 Advanced GUI Programming Chapter 8 Arrays Chapter 9 Correctness and Robustness Chapter 10 Advanced Input Output Chapter 11 Linked Data Structures and Recursion Chapter 12 Generic Programming and Collection Classes Appendix 1 Other Features of Java Appendix 2 Some Notes on Java Programming Environments Appendix 3 Source Code for All Examples in this Book News and Errata 2002 and 2004 David J Eck This is a free textbook There are no restrictions on using or redistributing or posting on the web a complete unmodified copy of this material There are some restrictions on modified copies To be precise Permission is granted to copy distribute and or modify this document under the terms of the GNU Free Documentation License Version 1 1 or any later version published by the Free Software Foundation with no invariant sections front cover text or back cover text The most recent version of this book is always available at no charge for downloading and for on line use at the Web address http math hws edu javanotes The previous edition which covered Java 1 1 can be found at http math hws edu eck cs124 javanotes3 Downloading Links Use one of the following links to download a compressed archive of this textbook Windows http math hws edu eck cs124 downloads javanotes4 zip 1 8 Megabytes with text files in Windows DOS format This archive can be used directly in Windows XP On any versin of Windows this archive can be extracted with WinZip or with the free program Aladdin Stuffit Expander for Windows available from http www stuffit com expander Linux UNIX and MacOS X http math hws edu eck cs124

    Original URL path: http://math.hws.edu/eck/cs124/javanotes4/ (2016-02-07)
    Open archived version from archive


  • Javanotes 5.1.2 -- Title Page
    Subroutines Chapter 5 Programming in the Large II Objects and Classes Chapter 6 Introduction to GUI Programming Chapter 7 Arrays Chapter 8 Correctness and Robustness Chapter 9 Linked Data Structures and Recursion Chapter 10 Generic Programming and Collection Classes Chapter 11 Files and Networking Chapter 12 Advanced GUI Programming Source Code for All Examples in this Book News and Errata 1996 2010 David J Eck This work is licensed under a Creative Commons Attribution ShareAlike 2 5 License This license allows you to redistribute this book in unmodified form It allows you to make and distribute modified versions as long as you include an attribution to the original author clearly describe the modifications that you have made and distribute the modified work under the same license as the original See the license for full details The most recent version of this book is always available at no charge for downloading and for on line use at the Web address http math hws edu javanotes Downloading Links http math hws edu eck cs124 downloads javanotes5 zip This zip archive contains a complete copy of the web site It should be usable on almost any computer Size 3 8 Megabytes http math hws edu eck cs124 downloads javanotes5 tar bz2 This bzip2 tar archive contains a complete copy of the web site in a format that allows greater compression but that might not be usable on all computers On most UNIX systems including Linux and Mac OS you should be able to extract it using the command bunzip2 javanotes5 tar bz2 followed by tar xf javanotes5 tar on the command line if it is not extracted automatically when you download it Size 2 8 Megabytes http math hws edu eck cs124 downloads javanotes5 linked pdf and http math hws edu eck cs124

    Original URL path: http://math.hws.edu/eck/cs124/javanotes5/ (2016-02-07)
    Open archived version from archive

  • Javanotes 6.0 -- Title Page
    7 Arrays Chapter 8 Correctness Robustness Efficiency Chapter 9 Linked Data Structures and Recursion Chapter 10 Generic Programming and Collection Classes Chapter 11 Advanced Input Output Streams Files and Networking Chapter 12 Threads and Multiprocessing Chapter 13 Advanced GUI Programming Source Code for All Examples in this Book Glossary News 1996 2014 David J Eck This work is licensed under a Creative Commons Attribution Noncommercial ShareAlike 3 0 License This license allows you to redistribute this book in unmodified form for non commercial purposes It allows you to make and distribute modified versions for non commercial purposes as long as you include an attribution to the original author clearly describe the modifications that you have made and distribute the modified work under the same license as the original Permission might be given by the author for other uses See the license for full details The most recent version of this book is always available at no charge for downloading and for on line use at the Web address http math hws edu javanotes Downloading And Other Links http math hws edu eck cs124 downloads javanotes6 zip This zip archive contains a complete copy of the web site It should be usable on almost any computer Size 4 4 Megabytes http math hws edu eck cs124 downloads javanotes6 tar bz2 This bzip2 tar archive contains a complete copy of the web site in a format that allows greater compression but that might not be usable on all computers On most UNIX systems including Linux and Mac OS you should be able to extract it using the command bunzip2 javanotes6 tar bz2 followed by tar xf javanotes6 tar on the command line if it is not extracted automatically when you download it Size 3 2 Megabytes http math hws edu eck cs124

    Original URL path: http://math.hws.edu/eck/cs124/javanotes6/ (2016-02-07)
    Open archived version from archive


  • Java XSLT processor tested with version 2 7 1 To build the PDF versions you will also need the TeX typesetting system in particular the latex and dvipdf commands For information on getting TeX see http www latex project org ftp html The build scripts for the PDF versions assume that the command latex is available on your system and also that dvipdf is available Alternative command names or full paths to the commands can be set by editing the script BUILD env sh and providing new definitions for the appropriate variables Xalan can be obtained from http xml apache org xalan j downloads html Two versions are available xalan j 2 7 1 bin zip or xalan j 2 7 1 bin 2jars zip either one will work To make things as easy as possible you can extract Xalan J in the javanotes 6 0 source directory and rename the directory from something like xalan j 2 7 1 to xalan Alternatively you can edit the script BUILD env sh and define XALAN DIR to refer to the correct directory name for Xalan Or you could make a symbolic link from xalan to the Xalan directory Note that you really only need the jar files in the Xalan directory The following scripts are provided BUILD env sh defines variables used in other scripts BUILD web site sh creates the web site version of the book This does NOT require LaTeX BUILD pdf sh creates the regular PDF version of the book suitable mostly for printing BUILD linked pdf sh creates the linked PDF version of the book suitable mostly for on screen reading BUILD lulu sh creates the three PDF files for the print versions that are published at lulu com BUILD all sh runs the scripts to build all versions except lulu with output turned off Takes a while All these scripts put their output in a directory named build output but the destination can be changed by redefining BUILD OUTPUT DIR in BUILD env sh Note that not all errors are detected by the scripts so you will have to check the output directory to make sure that the output was actually produced correctly even if the script says that it finished successfully Here is a little more information for people who would like to try producing modified versions of the textbook The XML files that define the sections of the various chapters in the book can be found in one directory per chapter The directories are named c1 overview c2 basics c3 control c4 subroutines and so on These directories also contain other files such as images and jar files that are used in each chapter in the web site version of the book The directories also contain XML files for the chapter quiz and exercises The Java source code files for the examples in the textbook are in the directory named src c1 src c2 src 3 and so on The syntax of the XML

    Original URL path: http://math.hws.edu/javanotes/README-full-source.txt (2016-02-07)
    Open archived version from archive

  • Javanotes 7.0, Section 2.1 -- The Basic Java Application
    in general you will type the program using some sort of text editor and save the program in a file Then you will use some command to try to compile the file You ll either get a message that the program contains syntax errors or you ll get a compiled version of the program In the case of Java the program is compiled into Java bytecode not into machine language Finally you can run the compiled program by giving some appropriate command For Java you will actually use an interpreter to execute the Java bytecode Your programming environment might automate some of the steps for you for example the compilation step is often done automatically but you can be sure that the same three steps are being done in the background Here is a Java program to display the message Hello World Don t expect to understand what s going on here just yet some of it you won t really understand until a few chapters from now A program to display the message Hello World on standard output public class HelloWorld public static void main String args System out println Hello World end of class HelloWorld The command that actually displays the message is System out println Hello World This command is an example of a subroutine call statement It uses a built in subroutine named System out println to do the actual work Recall that a subroutine consists of the instructions for performing some task chunked together and given a name That name can be used to call the subroutine whenever that task needs to be performed A built in subroutine is one that is already defined as part of the language and therefore automatically available for use in any program When you run this program the message Hello World without the quotes will be displayed on standard output Unfortunately I can t say exactly what that means Java is meant to run on many different platforms and standard output will mean different things on different platforms However you can expect the message to show up in some convenient or inconvenient place If you use a command line interface like that in Oracle s Java Development Kit you type in a command to tell the computer to run the program The computer will type the output from the program Hello World on the next line In an integrated development environment such as Eclipse the output might appear somewhere in one of the environment s windows You must be curious about all the other stuff in the above program Part of it consists of comments Comments in a program are entirely ignored by the computer they are there for human readers only This doesn t mean that they are unimportant Programs are meant to be read by people as well as by computers and without comments a program can be very difficult to understand Java has two types of comments The first type begins with and extends to the

    Original URL path: http://math.hws.edu/javanotes/c2/s1.html (2016-02-07)
    Open archived version from archive

  • Javanotes 7.0, Section 2.2 -- Variables and the Primitive Types
    byte data type refers to a single byte of memory A variable of type byte holds a string of eight bits which can represent any of the integers between 128 and 127 inclusive There are 256 integers in that range eight bits can represent 256 two raised to the power eight different values As for the other integer types short corresponds to two bytes 16 bits Variables of type short have values in the range 32768 to 32767 int corresponds to four bytes 32 bits Variables of type int have values in the range 2147483648 to 2147483647 long corresponds to eight bytes 64 bits Variables of type long have values in the range 9223372036854775808 to 9223372036854775807 You don t have to remember these numbers but they do give you some idea of the size of integers that you can work with Usually for representing integer data you should just stick to the int data type which is good enough for most purposes The float data type is represented in four bytes of memory using a standard method for encoding real numbers The maximum value for a float is about 10 raised to the power 38 A float can have about 7 significant digits So that 32 3989231134 and 32 3989234399 would both have to be rounded off to about 32 398923 in order to be stored in a variable of type float A double takes up 8 bytes can range up to about 10 to the power 308 and has about 15 significant digits Ordinarily you should stick to the double type for real values A variable of type char occupies two bytes in memory The value of a char variable is a single character such as A x or a space character The value can also be a special character such a tab or a carriage return or one of the many Unicode characters that come from different languages Values of type char are closely related to integer values since a character is actually stored as a 16 bit integer code number In fact we will see that chars in Java can actually be used like integers in certain situations It is important to remember that a primitive type value is represented using ony a certain finite number of bits So an int can t be an arbitrary integer it can only be an integer in a certain finite range of values Similarly float and double variables can only take on certain values They are not true real numbers in the mathematical sense For example the mathematical constant π can only be approximated by a value of type float or double since it would require an infinite number of decimal places to represent it exactly For that matter simple numbers like 1 3 can only be approximated by floats and doubles 2 2 3 Literals A data value is stored in the computer as a sequence of bits In the computer s memory it doesn t look anything like a value written on this page You need a way to include constant values in the programs that you write In a program you represent constant values as literals A literal is something that you can type in a program to represent a value It is a kind of name for a constant value For example to type a value of type char in a program you must surround it with a pair of single quote marks such as A or x The character and the quote marks make up a literal of type char Without the quotes A would be an identifier and would be a multiplication operator The quotes are not part of the value and are not stored in the variable they are just a convention for naming a particular character constant in a program If you want to store the character A in a variable ch of type char you could do so with the assignment statement ch A Certain special characters have special literals that use a backslash as an escape character In particular a tab is represented as t a carriage return as r a linefeed as n the single quote character as and the backslash itself as Note that even though you type two characters between the quotes in t the value represented by this literal is a single tab character Numeric literals are a little more complicated than you might expect Of course there are the obvious literals such as 317 and 17 42 But there are other possibilities for expressing numbers in a Java program First of all real numbers can be represented in an exponential form such as 1 3e12 or 12 3737e 108 The e12 and e 108 represent powers of 10 so that 1 3e12 means 1 3 times 10 12 and 12 3737e 108 means 12 3737 times 10 108 This format can be used to express very large and very small numbers Any numeric literal that contains a decimal point or exponential is a literal of type double To make a literal of type float you have to append an F or f to the end of the number For example 1 2F stands for 1 2 considered as a value of type float Occasionally you need to know this because the rules of Java say that you can t assign a value of type double to a variable of type float so you might be confronted with a ridiculous seeming error message if you try to do something like x 1 2 if x is a variable of type float You have to say x 1 2F This is one reason why I advise sticking to type double for real numbers Even for integer literals there are some complications Ordinary integers such as 177777 and 32 are literals of type byte short or int depending on their size You can make a literal of type long by adding L as a suffix For example 17L

    Original URL path: http://math.hws.edu/javanotes/c2/s2.html (2016-02-07)
    Open archived version from archive

  • Javanotes 7.0, Section 2.3 -- Strings, Classes, Objects, and Subroutines
    can be containers for static variables and subroutines However classes also have another purpose They are used to describe objects In this role the class is a type in the same way that int and double are types That is the class name can be used to declare variables Such variables can only hold one type of value The values in this case are objects An object is a collection of variables and subroutines Every object has an associated class that tells what type of object it is The class of an object specifies what subroutines and variables that object contains All objects defined by the same class are similar in that they contain similar collections of variables and subroutines For example an object might represent a point in the plane and it might contain variables named x and y to represent the coordinates of that point Every point object would have an x and a y but different points would have different values for these variables A class named Point for example could exist to define the common structure of all point objects and all such objects would then be values of type Point As another example let s look again at System out println System is a class and out is a static variable within that class However the value of System out is an object and System out println is actually the full name of a subroutine that is contained in the object System out You don t need to understand it at this point but the object referred to by System out is an object of the class PrintStream PrintStream is another class that is a standard part of Java Any object of type PrintStream is a destination to which information can be printed any object of type PrintStream has a println subroutine that can be used to send information to that destination The object System out is just one possible destination and System out println is a subroutine that sends information to that particular destination Other objects of type PrintStream might send information to other destinations such as files or across a network to other computers This is object oriented programming Many different things which have something in common they can all be used as destinations for information can all be used in the same way through a println subroutine The PrintStream class expresses the commonalities among all these objects The dual role of classes can be confusing and in practice most classes are designed to perform primarily or exclusively in only one of the two possible roles Fortunately you will not need to worry too much about it until we start working with objects in a more serious way in Chapter 5 By the way since class names and variable names are used in similar ways it might be hard to tell which is which Remember that all the built in predefined names in Java follow the rule that class names begin with an upper case letter while variable names begin with a lower case letter While this is not a formal syntax rule I strongly recommend that you follow it in your own programming Subroutine names should also begin with lower case letters There is no possibility of confusing a variable with a subroutine since a subroutine name in a program is always followed by a left parenthesis As one final general note you should be aware that subroutines in Java are often referred to as methods Generally the term method means a subroutine that is contained in a class or in an object Since this is true of every subroutine in Java every subroutine in Java is a method The same is not true for other programming languages and for the time being I will prefer to use the more general term subroutine However I should note that some people prefer to use the term method from the beginning 2 3 3 Operations on Strings String is a class and a value of type String is an object That object contains data namely the sequence of characters that make up the string It also contains subroutines All of these subroutines are in fact functions For example every string object contains a function named length that computes the number of characters in that string Suppose that advice is a variable that refers to a String For example advice might have been declared and assigned a value as follows String advice advice Seize the day Then advice length is a function call that returns the number of characters in the string Seize the day In this case the return value would be 14 In general for any variable str of type String the value of str length is an int equal to the number of characters in the string Note that this function has no parameter the particular string whose length is being computed is the value of str The length subroutine is defined by the class String and it can be used with any value of type String It can even be used with String literals which are after all just constant values of type String For example you could have a program count the characters in Hello World for you by saying System out print The number of characters in System out print the string Hello World is System out println Hello World length The String class defines a lot of functions Here are some that you might find useful Assume that s1 and s2 are variables of type String s1 equals s2 is a function that returns a boolean value It returns true if s1 consists of exactly the same sequence of characters as s2 and returns false otherwise s1 equalsIgnoreCase s2 is another boolean valued function that checks whether s1 is the same string as s2 but this function considers upper and lower case letters to be equivalent Thus if s1 is cat then s1 equals Cat is false while

    Original URL path: http://math.hws.edu/javanotes/c2/s3.html (2016-02-07)
    Open archived version from archive

  • Javanotes 7.0, Section 2.4 -- Text Input and Output
    to the output This can be a convenient way to insert values into the middle of an output string For example if x and y are variables of type int you could say System out printf The product of d and d is d x y x y When this statement is executed the value of x is substituted for the first d in the string the value of y for the second d and the value of the expression x y for the third so the output would be something like The product of 17 and 42 is 714 quotation marks not included in output To output a percent sign use the format specifier in the format string You can use n to output a line feed You can also use a backslash as usual in strings to output special characters such as tabs and double quote characters 2 4 2 A First Text Input Example For some unfathomable reason Java has never made it very easy to read data typed in by the user of a program You ve already seen that output can be displayed to the user using the subroutine System out print This subroutine is part of a pre defined object called System out The purpose of this object is precisely to display output to the user There is a corresponding object called System in that exists to read data input by the user but it provides only very primitive input facilities and it requires some advanced Java programming skills to use it effectively Java 5 0 finally made input a little easier with a new Scanner class However it requires some knowledge of object oriented programming to use this class so it s not ideal for use here at the beginning of this course Java 6 introduced the Console class for communicating with the user but Console has its own problems It is not always available and it can only read strings not numbers Furthermore in my opinion Scanner and Console still don t get things quite right Nevertheless I will introduce Scanner briefly at the end of this section in case you want to start using it now However we start with my own version of text input Fortunately it is possible to extend Java by creating new classes that provide subroutines that are not available in the standard part of the language As soon as a new class is available the subroutines that it contains can be used in exactly the same way as built in routines Along these lines I ve written a class named TextIO that defines subroutines for reading values typed by the user The subroutines in this class make it possible to get input from the standard input object System in without knowing about the advanced aspects of Java that are needed to use Scanner or to use System in directly TextIO also has a few other capabilities that I will discuss later in this section To use the TextIO class you must make sure that the class is available to your program What this means depends on the Java programming environment that you are using In general you just have to add the source code file TextIO java to the same directory that contains your main program See Section 2 6 for information about how to use TextIO The input routines in the TextIO class are static member functions Static member functions were introduced in the previous section Let s suppose that you want your program to read an integer typed in by the user The TextIO class contains a static member function named getlnInt that you can use for this purpose Since this function is contained in the TextIO class you have to refer to it in your program as TextIO getlnInt The function has no parameters so a complete call to the function takes the form TextIO getlnInt This function call represents the int value typed by the user and you have to do something with the returned value such as assign it to a variable For example if userInput is a variable of type int created with a declaration statement int userInput then you could use the assignment statement userInput TextIO getlnInt When the computer executes this statement it will wait for the user to type in an integer value The user must type a number and press return before the program can continue The value that the user typed will then be returned by the function and it will be stored in the variable userInput Here is a complete program that uses TextIO getlnInt to read a number typed by the user and then prints out the square of that number A program that reads an integer that is typed in by the user and computes and prints the square of that integer public class PrintSquare public static void main String args int userInput The number input by the user int square The userInput multiplied by itself System out print Please type a number userInput TextIO getlnInt square userInput userInput System out println System out println The number that you entered was userInput System out println The square of that number is square System out println end of main end of class PrintSquare When you run this program it will display the message Please type a number and will pause until you type a response including a carriage return after the number Note that it is good style to output a question or some other prompt to the user before reading input Otherwise the user will have no way of knowing exactly what the computer is waiting for or even that it is waiting for the user to do something 2 4 3 Basic TextIO Input Functions TextIO includes a variety of functions for inputting values of various types Here are the functions that you are most likely to use j TextIO getlnInt Reads a value of type int y TextIO getlnDouble Reads a value of type double a TextIO getlnBoolean Reads a value of type boolean c TextIO getlnChar Reads a value of type char w TextIO getlnWord Reads one word as a value of type String s TextIO getln Reads an entire input line as a String For these statements to be legal the variables on the left side of each assignment statement must already be declared and must be of the same type as that returned by the function on the right side Note carefully that these functions do not have parameters The values that they return come from outside the program typed in by the user as the program is running To capture that data so that you can use it in your program you have to assign the return value of the function to a variable You will then be able to refer to the user s input value by using the name of the variable When you call one of these functions you are guaranteed that it will return a legal value of the correct type If the user types in an illegal value as input for example if you ask for an int and the user types in a non numeric character or a number that is outside the legal range of values that can be stored in a variable of type int then the computer will ask the user to re enter the value and your program never sees the first illegal value that the user entered For TextIO getlnBoolean the user is allowed to type in any of the following true false t f yes no y n 1 or 0 Furthermore they can use either upper or lower case letters In any case the user s input is interpreted as a true false value It s convenient to use TextIO getlnBoolean to read the user s response to a Yes No question You ll notice that there are two input functions that return Strings The first getlnWord returns a string consisting of non blank characters only When it is called it skips over any spaces and carriage returns typed in by the user Then it reads non blank characters until it gets to the next space or carriage return It returns a String consisting of all the non blank characters that it has read The second input function getln simply returns a string consisting of all the characters typed in by the user including spaces up to the next carriage return It gets an entire line of input text The carriage return itself is not returned as part of the input string but it is read and discarded by the computer Note that the String returned by TextIO getln might be the empty string which contains no characters at all You will get this return value if the user simply presses return without typing anything else first TextIO getln does not skip blanks or end of lines before reading a value But the input functions getlnInt getlnDouble getlnBoolean and getlnChar behave like getlnWord in that they will skip past any blanks and carriage returns in the input before reading a value When one of these functions skips over an end of line it outputs a to let the user know that more input is expected Furthermore if the user types extra characters on the line after the input value all the extra characters will be discarded along with the carriage return at the end of the line If the program executes another input function the user will have to type in another line of input even if they had typed more than one value on the previous line It might not sound like a good idea to discard any of the user s input but it turns out to be the safest thing to do in most programs Using TextIO for input and output we can now improve the program from Section 2 2 for computing the value of an investment We can have the user type in the initial value of the investment and the interest rate The result is a much more useful program for one thing it makes sense to run it more than once Note that this program uses formatted output to print out monetary values in their correct format This class implements a simple program that will compute the amount of interest that is earned on an investment over a period of one year The initial amount of the investment and the interest rate are input by the user The value of the investment at the end of the year is output The rate must be input as a decimal not a percentage for example 0 05 rather than 5 public class Interest2 public static void main String args double principal The value of the investment double rate The annual interest rate double interest The interest earned during the year System out print Enter the initial investment principal TextIO getlnDouble System out print Enter the annual interest rate as a decimal rate TextIO getlnDouble interest principal rate Compute this year s interest principal principal interest Add it to principal System out printf The amount of interest is 1 2f n interest System out printf The value after one year is 1 2f n principal end of main end of class Interest2 You might be wondering why there is only one output routine System out println which can output data values of any type while there is a separate input routine for each data type For the output function the computer can tell what type of value is being output by looking at the parameter However the input routines don t have parameters so the different input routines can only be distinguished by having different names 2 4 4 Introduction to File I O System out sends its output to the output destination known as standard output But standard output is just one possible output destination For example data can be written to a file that is stored on the user s hard drive The advantage to this of course is that the data is saved in the file even after the program ends and the user can print the file email it to someone else edit it with another program and so on Similarly System in has only one possible source for input data TextIO has the ability to write data to files and to read data from files TextIO includes output functions TextIO put TextIO putln and TextIO putf Ordinarily these functions work exactly like System out print System out println and System out prinf and are interchangeable with them However they can also be used to output text to files and to other destinations When you write output using TextIO put TextIO putln or TextIO putf the output is sent to the current output destination By default the current output destination is standard output However TextIO has subroutines that can be used to change the current output destination To write to a file named result txt for example you would use the statement TextIO writeFile result txt After this statement is executed any output from TextIO output statements will be sent to the file named result txt instead of to standard output The file will be created if it does not already exist Note that if a file with the same name already exists its previous contents will be erased without any warning When you call TextIO writeFile TextIO remembers the file and automatically sends any output from TextIO put or other output functions to that file If you want to go back to writing to standard output you can call TextIO writeStandardOutput Here is a simple program that asks the user some questions and outputs the user s responses to a file named profile txt As an example it uses TextIO for output to standard output as well as to the file but System out could also have been used for the output to stadard output public class CreateProfile public static void main String args String name The user s name String email The user s email address double salary the user s yearly salary String favColor The user s favorite color TextIO putln Good Afternoon This program will create TextIO putln your profile file if you will just answer TextIO putln a few simple questions TextIO putln Gather responses from the user TextIO put What is your name name TextIO getln TextIO put What is your email address email TextIO getln TextIO put What is your yearly income salary TextIO getlnDouble TextIO put What is your favorite color favColor TextIO getln Write the user s information to the file named profile txt TextIO writeFile profile txt subsequent output goes to file TextIO putln Name name TextIO putln Email email TextIO putln Favorite Color favColor TextIO putf Yearly Income 1 2f n salary Print a final message to standard output TextIO writeStandardOutput TextIO putln Thank you Your profile has been written to profile txt In many cases you want to let the user select the file that will be used for output You could ask the user to type in the file name but that is error prone and users are more familiar with selecting a file from a file dialog box The statement TextIO writeUserSelectedFile will open a typical graphical user interface file selection dialog where the user can specify the output file This also has the advantage of alerting the user if they are about to replace an existing file It is possible for the user to cancel the dialog box without selecting a file TextIO writeUserSelectedFile is a function that returns a boolean value The return value is true if the user selected a file and is false if the user canceled the dialog box Your program can check the return value if it needs to know whether it is actually going to write to a file or not TextIO can also read from files as an alternative to reading from standard input You can specify an input source for TextIO s various get functions The default input source is standard input You can use the statement TextIO readFile data txt to read from a file named data txt instead or you can let the user select the input file with a GUI style dialog box by saying TextIO readUserSelectedFile After you have done this any input will come from the file instead of being typed by the user You can go back to reading the user s input with TextIO readStandardInput When your program is reading from standard input the user gets a chance to correct any errors in the input This is not possible when the program is reading from a file If illegal data is found when a program tries to read from a file an error occurs that will crash the program Later we will see that it is possible to catch such errors and recover from them Errors can also occur though more rarely when writing to files A complete understanding of input output in Java requires a knowledge of object oriented programming We will return to the topic later in Chapter 11 The file I O capabilities in TextIO are rather primitive by comparison Nevertheless they are sufficient for many applications and they will allow you to get some experience with files sooner rather than later 2 4 5 Other TextIO Features The TextIO input functions that we have seen so far can only read one value from a line of input Sometimes however you do want to read more than one value from the same line of input For example you might want the user to be able to type something like 42 17 to input the two numbers 42 and 17 on the same line TextIO provides the following alternative input functions to allow you to do this j TextIO getInt Reads a value

    Original URL path: http://math.hws.edu/javanotes/c2/s4.html (2016-02-07)
    Open archived version from archive