introduction to java chapter 5 - arrays, strings, file access, and plotting1 chapter 5 arrays, file...
TRANSCRIPT
Chapter 5 - Arrays, Strings, File Access, and Plotting 1
Introduction to Java
Chapter 5
Arrays, File Access, and Plotting
Chapter 5 - Arrays, Strings, File Access, and Plotting 2
Introduction to Java
Arrays
• 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
a[0]
a[1]
a[2]
a[3]
a[4]
C omputerM emory A rray a
5 a.length
Chapter 5 - Arrays, Strings, File Access, and Plotting 3
Introduction to Java
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 reference
x = 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 4
Introduction to Java
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 5
Introduction to Java
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 6
Introduction to Java
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 7
Introduction to Java
Note failure when access to an out-of-bounds subscript (5) is attempted.
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)
Chapter 5 - Arrays, Strings, File Access, and Plotting 8
Introduction to Java
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 9
Introduction to Java
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 10
Introduction to Java
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 11
Introduction to Java
Using Class FileInimport chapman.io.*;public class TestFileIn { public static void main(String arg[]) {
...
// Open file FileIn in = new FileIn("infile");
// Check for valid open if ( in.readStatus != in.FILE_NOT_FOUND ) {
// Read numbers into array while ( in.readStatus != in.EOF ) { a[i++] = in.readDouble(); } nvals = i;
// Close file in.close();
... (further processing) }
// Get here if file not found. Tell user else { System.out.println("File not found: infile"); } }}
Open file by creating object
Check for valid file open
Import package
Close file when done
Read data one value at a time
Report errors if they exist
Chapter 5 - Arrays, Strings, File Access, and Plotting 12
Introduction to Java
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 13
Introduction to Java
import chapman.io.*;public class TestFileOut {
public static void main(String arg[]) {
// Test open without append FileOut out = new FileOut("outfile");
// Check for valid open if ( out.writeStatus != out.IO_EXCEPTION ) {
// Write values out.printf("double = %20.14f\n",Math.PI); out.printf("long = %20d\n",12345678901234L); out.printf("char = %20c\n",'A'); out.printf("String = %20s\n","This is a test."); }
// Close file out.close(); }}
Using Class FileOut
Open file by creating object
Check for valid file open
Import package
Close file when done
Write data one value at a time
Chapter 5 - Arrays, Strings, File Access, and Plotting 14
Introduction to Java
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 15
Introduction to Java
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 16
Introduction to Java
Example JPlot2D Outputs (1)
Linear Plot Semilog x Plot
Chapter 5 - Arrays, Strings, File Access, and Plotting 17
Introduction to Java
Example JPlot2D Outputs (2)
Log-log PlotSemilog y Plot
Chapter 5 - Arrays, Strings, File Access, and Plotting 18
Introduction to Java
Example JPlot2D Outputs (3)
Bar PlotPolar Plot
Chapter 5 - Arrays, Strings, File Access, and Plotting 19
Introduction to Java
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 20
Introduction to Java
import java.awt.*;import java.awt.event.*;import javax.swing.*;import chapman.graphics.JPlot2D;public class TestJPlot2D {
public static void main(String s[]) {
// Create data to plot ...
// Create plot object and set plot information. JPlot2D pl = new JPlot2D( x, y ); pl.setPlotType ( JPlot2D.LINEAR ); pl.setLineColor( Color.blue ); pl.setLineWidth( 3.0f ); pl.setLineStyle( JPlot2D.LINESTYLE_SOLID ); pl.setMarkerState( JPlot2D.MARKER_ON ); pl.setMarkerColor( Color.red ); pl.setMarkerStyle( JPlot2D.MARKER_DIAMOND ); pl.setTitle( "Plot of y(x) = x^2 - 10x + 26" ); pl.setXLabel( "x" ); pl.setYLabel( "y" ); pl.setGridState( JPlot2D.GRID_ON );
Using Class JPlot2D (1)
Create data to plot here
Create JPlot2D obj
Import packages
Set the desired plotting styles
Set data to plot
Chapter 5 - Arrays, Strings, File Access, and Plotting 21
Introduction to Java
// Create a frame and place the plot in the center of the // frame. Note that the plot will occupy all of the JFrame fr = new JFrame("JPlot2D ...");
// Create a Window Listener to handle "close" events WindowHandler l = new WindowHandler(); fr.addWindowListener(l);
fr.getContentPane().add(pl, BorderLayout.CENTER); fr.setSize(500,500); fr.setVisible( true ); }}
// Create a window listener to close the program.class WindowHandler extends WindowAdapter {
// This method implements a simple listener that detects // the "window closing event" and stops the program. public void windowClosing(WindowEvent e) { System.exit(0); };}
Using Class JPlot2D (2)
Create listener (see Chap 11)
Set size of plot
Create frame to hold plot
Window listener (see Chap 11)
Add plot to frame
Chapter 5 - Arrays, Strings, File Access, and Plotting 22
Introduction to Java
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 23
Introduction to Java
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 references
s1 = "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 24
Introduction to Java
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 25
Introduction to Java
Substrings (2)
• 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"
s.substring(3,6)s.substring(3)
s
s1
s2
Chapter 5 - Arrays, Strings, File Access, and Plotting 26
Introduction to Java
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 27
Introduction to Java
Concatenating Strings (2)
• Example:String s1 = "abc";String s2 = "def";
// Watch what happens here!System.out.println("\nBefore assignment:");System.out.println("s1 = " + s1);System.out.println("s2 = " + s2);s1 = s1.concat(s2);System.out.println("\nAfter assignment:");System.out.println("s1 = " + s1);System.out.println("s2 = " + s2);
Before assignment:s1 = abcs2 = def
After assignment:s1 = abcdefs2 = def
s1
s2
References Objects
s1
s2
Object"abc"
Object"def"
Object"abc"
Object"def"
Object"abcdef"
After
Before
New object created.
Chapter 5 - Arrays, Strings, File Access, and Plotting 28
Introduction to Java
Selected Additional String Methods
Method Descriptionint compareTo(String s) Compares the string object to another string lexicographically.
Returns: 0 if string is equal to s <0 if string less than s >0 if string greater than s
boolean equals(Object o) Returns true if o is a String, and o contains exactly the samecharacters as the string.
boolean equalsIgnoreCase( String s)
Returns true if s contains exactly the same characters as thestring, disregarding case.
int IndexOf(String s) Returns the index of the first location of substring s in thestring.
int IndexOf(String s, int start)
Returns the index of the first location of substring s at or afterposition start in the string.
String toLowerCase() Converts the string to lower case.String toUpperCase() Converts the string to upper case.String trim() Removes white space from either end of the string.