Arrays,Strings,File Access and Plotting

Download Report

Transcript Arrays,Strings,File Access and Plotting

Introduction to Java
Chapter 5
Arrays, File Access, and Plotting
Chapter 5 - Arrays, Strings, File Access, and Plotting
1
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]
Computer
Memory
a[2]
Array a
a[3]
a[4]
Chapter 5 - Arrays, Strings, File Access, and Plotting
5
a.length
2
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[];
x = new double[5];
// Create reference
// 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
3
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
4
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
5
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
6
Introduction to Java
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
Note failure when
a[0] = 1
access to an out-ofa[1] = 2
bounds subscript (5)
a[2] = 3
is attempted.
a[3] = 4
a[4] = 5
java.lang.ArrayIndexOutOfBoundsException: 5
at TestBounds.main(TestBounds.java:15)
Chapter 5 - Arrays, Strings, File Access, and Plotting
7
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
8
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
9
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
10
Introduction to Java
Import
package
Using Class FileIn
import chapman.io.*;
public class TestFileIn {
public static void main(String arg[]) {
Open file by
creating object
...
// Open file
FileIn in = new FileIn("infile");
// Check for valid open
if ( in.readStatus != in.FILE_NOT_FOUND ) {
Check for
valid file open
// Read numbers into array
while ( in.readStatus != in.EOF ) {
a[i++] = in.readDouble();
}
nvals = i;
// Close file
in.close();
Close file
when done
Report errors if
they exist
Read data one
value at a time
... (further processing)
}
// Get here if file not found. Tell user
else {
System.out.println("File not found: infile");
}
}
}
Chapter 5 - Arrays, Strings, File Access, and Plotting
11
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
12
Introduction to Java
Import
package
Using Class FileOut
import chapman.io.*;
public class TestFileOut {
public static void main(String arg[]) {
Open file by
creating object
// Test open without append
FileOut out = new FileOut("outfile");
// Check for valid open
if ( out.writeStatus != out.IO_EXCEPTION ) {
Check for
valid file open
// Write values
out.printf("double
out.printf("long
out.printf("char
out.printf("String
=
=
=
=
%20.14f\n",Math.PI);
%20d\n",12345678901234L);
%20c\n",'A');
%20s\n","This is a test.");
}
Close file
when done
// Close file
out.close();
}
Write data one
value at a time
}
Chapter 5 - Arrays, Strings, File Access, and Plotting
13
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
14
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
15
Introduction to Java
Example JPlot2D Outputs (1)
Linear Plot
Semilog x Plot
Chapter 5 - Arrays, Strings, File Access, and Plotting
16
Introduction to Java
Example JPlot2D Outputs (2)
Semilog y Plot
Log-log Plot
Chapter 5 - Arrays, Strings, File Access, and Plotting
17
Introduction to Java
Example JPlot2D Outputs (3)
Polar Plot
Bar Plot
Chapter 5 - Arrays, Strings, File Access, and Plotting
18
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
19
Introduction to Java
Import
packages
Create data to
plot here
Using Class JPlot2D (1)
import
import
import
import
public
java.awt.*;
java.awt.event.*;
javax.swing.*;
chapman.graphics.JPlot2D;
class TestJPlot2D {
public static void main(String s[]) {
// Create data to plot
...
Create
JPlot2D obj
Set the desired
plotting styles
// 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 );
Chapter 5 - Arrays, Strings, File Access, and Plotting
Set data to plot
20
Introduction to Java
Create frame
to hold plot
Using Class JPlot2D (2)
// 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 listener
(see Chap 11)
// 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 );
Set size of plot
}
}
// Create a window listener to close the program.
class WindowHandler extends WindowAdapter {
Window
listener (see
Chap 11)
Add plot to
frame
// This method implements a simple listener that detects
// the "window closing event" and stops the program.
public void windowClosing(WindowEvent e) {
System.exit(0);
};
}
Chapter 5 - Arrays, Strings, File Access, and Plotting
21
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
22
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;
s1 = "This is a test.";
s2 = new String();
// Create references
// Create array object
// 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
23
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);
s.substring(int st, int en);
// From "st"
// "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
24
Introduction to Java
Substrings (2)
• Examples:
s
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"
s.substring(3)
s.substring(3,6)
s1
"defgh"
Chapter 5 - Arrays, Strings, File Access, and Plotting
s2
"def"
25
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
26
Introduction to Java
Concatenating Strings (2)
• Example:
References
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 = abc
s2 = def
Objects
s1
Object
"abc"
s2
Object
"def"
Before
s1
Object
"abc"
s2
Object
"def"
Object
"abcdef"
After assignment:
s1 = abcdef
s2 = def
After
Chapter 5 - Arrays, Strings, File Access, and Plotting
New object
created.
27
Introduction to Java
Selected Additional String Methods
Method
int compareTo(String s)
boolean equals(Object o)
boolean equalsIgnoreCase(
String s)
int IndexOf(String s)
int IndexOf(String s,
int start)
String toLowerCase()
String toUpperCase()
String trim()
Description
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
Returns true if o is a String, and o contains exactly the same
characters as the string.
Returns true if s contains exactly the same characters as the
string, disregarding case.
Returns the index of the first location of substring s in the
string.
Returns the index of the first location of substring s at or after
position start in the string.
Converts the string to lower case.
Converts the string to upper case.
Removes white space from either end of the string.
Chapter 5 - Arrays, Strings, File Access, and Plotting
28