280 likes | 287 Views
This chapter covers arrays, strings, file access, and plotting in Java. Learn how to declare arrays, initialize them, handle out-of-bounds subscripts, read and write data to files, and more.
E N D
Chapter 5 Arrays, File Access, and Plotting Chapter 5 - Arrays, Strings, File Access, and Plotting
An array is a special object containing: A group of contiguous memory locations that all have the same name and same type A separate instance variable containing the number of elements in the array Arrays Chapter 5 - Arrays, Strings, File Access, and Plotting
Declaring Arrays • An array must be declared or created before it can be used. This is a two-step process: • First, declare a reference to an array. • Then, create the array with the new operator. • Example: double x[]; // Create referencex = new double[5]; // Create array object • These steps can be combined on a single line: double x[] = new double[5]; // All together Chapter 5 - Arrays, Strings, File Access, and Plotting
Using Arrays • An array element may be used in any place where an ordinary variable of the same type may be used. • An array element is addressed using the array name followed by a integer subscript in brackets: a[2] • Arrays are typically used to perform the same calculation on many different values • Example: for ( int i = 0; i < 100; i++ ) { a[i] = Math.sqrt(a[i]); // sqrt of 100 values } Chapter 5 - Arrays, Strings, File Access, and Plotting
Initializing Arrays • When an array object is created with the new operator, its elements are automatically initialized to zero. • Arrays can be initialized to non-zero values using array initializers, which are comma-separated list enclosed in braces • Array initializers only work in declaration statements • Example: int a[] = {1, 2, 3, 4, 5}; // Create & initialize array Chapter 5 - Arrays, Strings, File Access, and Plotting
Out-of-Bounds Subscripts • Each element of an array is addressed using the name of the array plus the subscripts 0, 1, …, n-1, where n is the number of elements in the array. • Subscripts < 0 or n are illegal, since they do not correspond to real memory locations in the array. • These subscripts are said to be out-of-bounds. • Reference to an out-of-bounds subscript produces an out-of-bounds exception, and the program will crash if the exception is not handled. Chapter 5 - Arrays, Strings, File Access, and Plotting
Out-of-Bounds Subscripts (2) • Example: // Declare and initialize array int a[] = {1,2,3,4,5}; // Write array (with an error!) for ( int i = 0; i <= 5; i++ ) System.out.println("a[" + i + "] = " + a[i]); • Result: C:\book\java\chap5>java TestBounds a[0] = 1 a[1] = 2 a[2] = 3 a[3] = 4 a[4] = 5 java.lang.ArrayIndexOutOfBoundsException: 5 at TestBounds.main(TestBounds.java:15) Note failure when access to an out-of-bounds subscript (5) is attempted. Chapter 5 - Arrays, Strings, File Access, and Plotting
Reading and Writing Data to Files • Disk files are a convenient way to store large amounts of data between uses. • The simplest way to read or write disk files is with command-line redirection. • The file to read data from is listed after a < on the command line. All input data comes from this file. • The file to write data from is listed after a > on the command line. All output data goes to this file. • Example: • D:\>java Example < infile > outfile Chapter 5 - Arrays, Strings, File Access, and Plotting
Reading and Writing Data to Files • Command line redirection is relatively inflexible, since all input must be in a single file and all output must go to a single file. • It is better to use the Java I/O system to open and close files as needed when a program is running. • The Java I/O system is very complex, and discussion is postponed to Chapter 14. • We introduce 2 convenience classes FileIn and FileOut for easy Java I/O. Chapter 5 - Arrays, Strings, File Access, and Plotting
Reading Files with Class FileIn • Class chapman.io.FileIn is designed to read numeric data from an input file. • To open a file for reading, import package chapman.io, and create a new FileIn object with the name of the file as a calling parameter. FileIn in = new FileIn("inputFile"); • Then read input data using the readDouble(), readFloat(), readInt(), or readLong() methods. Chapter 5 - Arrays, Strings, File Access, and Plotting
Import package Open file by creating object Check for valid file open Read data one value at a time Close file when done Report errors if they exist Using Class FileIn Chapter 5 - Arrays, Strings, File Access, and Plotting
Writing Files with Class FileOut • Class chapman.io.FileOut is designed to write formatted data from an output file. • To open a file for writing, import package chapman.io, and create a new FileOut object with the name of the file as a calling parameter. FileOut out = new FileOut("outFile"); • Then write output data using the printf()method, and close file using the close() method. Chapter 5 - Arrays, Strings, File Access, and Plotting
Import package Open file by creating object Check for valid file open Write data one value at a time Close file when done Using Class FileOut Chapter 5 - Arrays, Strings, File Access, and Plotting
Introduction to Plotting • Support for graphics is built into the Java API. • Support is in the form of low-level graphics classes and methods • These methods are discussed in Chapter 11 • Meanwhile, we will use the convenience class chapman.graphics.JPlot2D to create 2D plots. Chapter 5 - Arrays, Strings, File Access, and Plotting
Introduction to Class JPlot2D • Class JPlot2D supports many types of plots: • Linear plots • Semilog x plots • Semilog y plots • Logarithmic plots • Polar Plots • Bar Plots • Examples are shown on the following slides Chapter 5 - Arrays, Strings, File Access, and Plotting
Example JPlot2D Outputs (1) Linear Plot Semilogx Plot Chapter 5 - Arrays, Strings, File Access, and Plotting
Example JPlot2D Outputs (2) Semilogy Plot Log-log Plot Chapter 5 - Arrays, Strings, File Access, and Plotting
Example JPlot2D Outputs (3) Polar Plot Bar Plot Chapter 5 - Arrays, Strings, File Access, and Plotting
Creating Plots • To create plots, use the template shown on the following two pages • Create arrays x and y containing the data to plot, and insert it into the template • The components of this program will be explained in Chapters 11 and 12; meanwhile we can use it to plot any desired data • See Table 5.5 for a list of plotting options Chapter 5 - Arrays, Strings, File Access, and Plotting
Import packages Create data to plot here Create JPlot2Dobj Set data to plot Set the desired plotting styles Using Class JPlot2D (1) Chapter 5 - Arrays, Strings, File Access, and Plotting
Create frame to hold plot Create listener (see Chap 11) Set size of plot Add plot to frame Window listener (see Chap 11) Using Class JPlot2D (2) Chapter 5 - Arrays, Strings, File Access, and Plotting
Strings • A String is an object containing one or more characters, treated as a unit. • Strings are types of objects. Once a string is created, its contents never change. • The simplest form of string is a string literal, which is a series of characters between quotation marks. • Example: "This is a string literal." Chapter 5 - Arrays, Strings, File Access, and Plotting
Creating Strings • To create a String: • First, declare a reference to a String. • Then, create the String with a string literal or the new operator. • Examples: String s1, s2; // Create referencess1 = "This is a test."; // Create array object s2 = new String(); // Create array object • These steps can be combined on a single line: String s3[] = "String 3."; // All together Chapter 5 - Arrays, Strings, File Access, and Plotting
Substrings • A substring is a portion of a string. • The String method substring creates a new String object containing a portion of another String. • The forms of this method are: s.substring(int st); // From "st" s.substring(int st, int en); // "st" to "en" • This method returns a String object containing the characters from st to en (or the end of the string). Chapter 5 - Arrays, Strings, File Access, and Plotting
Examples: String s = "abcdefgh"; String s1 = s.substring(3); String s2 = s.substring(3,6); Substring s1 contains "defgh", and substring s2 contains "def". Note that the indices start at 0, and that the substring contains the values from st to en-1. "abcdefgh" "defgh" "def" Substrings (2) s s.substring(3) s.substring(3,6) s1 s2 Chapter 5 - Arrays, Strings, File Access, and Plotting
Concatenating Strings • The String method concat creates a new String object containing the contents of two other strings. • The form of this method is: s1.concat(String s2); // Combine s1 and s2 • This method returns a String object containing the contents of s1 followed by the contents of s2. Chapter 5 - Arrays, Strings, File Access, and Plotting
Example: Concatenating Strings (2) New object created. Chapter 5 - Arrays, Strings, File Access, and Plotting
Selected Additional String Methods Chapter 5 - Arrays, Strings, File Access, and Plotting