winter 2006cisc121 - prof. mcleod1 last time wrapper classes jfilechooser (along with joptionpane,...
TRANSCRIPT
Winter 2006 CISC121 - Prof. McLeod 1
Last Time
• Wrapper classes
• JFileChooser (along with JOptionPane, and JColorChooser!)
• Text File Output
Winter 2006 CISC121 - Prof. McLeod 2
Stuff…
• Any questions on assignment one?
Winter 2006 CISC121 - Prof. McLeod 3
Today
• Quick review of Text File Output.
• Text File Input.
• The File class.
• Notes on Programming Style and Documentation are included here, for you to read!
• Start 1D Arrays.
Winter 2006 CISC121 - Prof. McLeod 4
Text File Output in Java 5.0
PrintWriter writeFile = null;
try {
writeFile = new PrintWriter(outputFile);
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
System.exit(0);
} // end try catch
• outputFile can be a filename String or a File object (as returned by JFileChooser, for example).
Winter 2006 CISC121 - Prof. McLeod 5
Text File Output in Java 5.0, Cont.
• The Object writeFile, owns a couple of familiar methods: print() and println().
• When you are done writing, don’t forget to close the file with:
fileOut.close();
• Way easy!!
Winter 2006 CISC121 - Prof. McLeod 6
Text File Input in Java 5.0
• Use the FileReader and Scanner classes.• Our usual import statements:
import java.util.Scanner;
import java.io.FileReader;
import java.io.FileNotFoundException;
Winter 2006 CISC121 - Prof. McLeod 7
Text File Input in Java 5.0, Cont.
• This works:
FileReader fileIn = null;
try{
fileIn = new FileReader("Test.txt");
}
catch (FileNotFoundException e) {
// Do something clever here!
}
Scanner fileInput = new Scanner(fileIn);
Winter 2006 CISC121 - Prof. McLeod 8
Without using FileReader
• You can also send a File object to the Scanner class when you instantiate it instead of a FileReader object.
• You will still need to do this in a try catch block as shown in the previous slide.
• See the demo program “TextFileReaderDemo.java”
Winter 2006 CISC121 - Prof. McLeod 9
Text File Input in Java 5.0, Cont.
• We are going to have to talk about try/catch blocks soon! But for now, let’s get back to file input.
• To get the file contents, and print them to the console, for example:
while (fileInput.hasNextLine()) {
System.out.println(fileInput.nextLine());
}
Winter 2006 CISC121 - Prof. McLeod 10
Aside - Scanner Class’ Tokenizer
• The Scanner class has a built in String Tokenizer.
• Set the delimiters using the useDelimiter(delimiter_String) method.
• Obtain the tokens by calling the next() method.• The hasNext() method will return false when
there are no more tokens.
Winter 2006 CISC121 - Prof. McLeod 11
• File is a class in the java.io.* package.• It contains useful utility methods that will help prevent
programs crashing from file errors.• For example:
File myFile = new File(“test.dat”);
myFile.exists(); // returns true if file exists
myFile.canRead(); // returns true if can read from file
myFile.canWrite(); // returns true if can write to file
The File Class
Winter 2006 CISC121 - Prof. McLeod 12
The File Class, Cont.
myFile.delete(); // deletes file and returns true if successful
myFile.length(); // returns length of file in bytes
myFile.getName(); // returns the name of file (like “test.dat”)
myFile.getPath(); // returns path of file (like “C:\AlanStuff\JavaSource”)
• One nice thing is that none of these methods nor the File class’ constructor throw exceptions!
Winter 2006 CISC121 - Prof. McLeod 13
Binary and Random Access
• Binary files contain data exactly as it is stored in memory – you can’t read these files in Notepad!
• Text file is sequential access only.• What does that mean?
• Random access can access any byte in the file at any time, in any order.
• More about Binary and Random File Access later!
Winter 2006 CISC121 - Prof. McLeod 14
Aside – Assignment 1
• You should not need to know anything else to do assignment one!
• Now we can move on to new topics.
• Please read the following slides on Programming Style and Documentation on your own. Part of your grade on Assn1 will be for style and commenting.
Winter 2006 CISC121 - Prof. McLeod 15
Programming Style & Documentation
• Purpose is to make your code readable (and “debuggable”) by you or another programmer who is familiar with the Java language.
• Internal style elements are documentation (comments), spacing, and descriptive variable names.
• Select the conventions you want to use and be consistent.
• (We will discuss creating external documentation through the use of the Javadoc utility later.)
Winter 2006 CISC121 - Prof. McLeod 16
Programming Style & Documentation – Cont.
• Comments:– Add a block comment to the top of the class and at the
beginning of each method. Describe overall purpose of class/method, main algorithm used, author, date created, and any assumptions made and/or bugs found. Method comments should state what parameters are expected by the method and what the method returns.
– Comments for variable declarations, when the name of variable is not self-explanatory.
– Comments at the beginnings of logical blocks of code.– In-line comments to indicate the closing brackets of
blocks and what they close.
Winter 2006 CISC121 - Prof. McLeod 17
Programming Style & Documentation – Cont.
• Spacing (alignment)– Class definition header starts at column 1, and
closing bracket on column 1.– Indent of about 3 or 4 spaces is adequate.– Method headers and instance variable
declarations indented once.– Code inside any block, including method code
indented once from alignment of method header, or outer block.
Winter 2006 CISC121 - Prof. McLeod 18
Programming Style & Documentation – Cont.
– Opening “{“ can be at the end of a statement line (Ready to Program puts them at the start of the statement, on the line below).
– Closing “}” on same column as the column where the method header is declared, or the statement containing the opening “{“. “}” is usually by itself on a line.
– Add a comment after “}” to indicate what is being closed.
– If you have an overlong line, it is OK to continue the line on the line below, but indent the continued part of the line. (Note – do not try to continue a line in the middle of a String literal!)
Winter 2006 CISC121 - Prof. McLeod 19
Programming Style & Documentation – Cont.
• Spacing (“white space”)– Add blank lines before and after methods and larger
logical blocks.– One statement per line. (Longer statements can be
broken onto multiple lines.)– Use a space before “{“, “(“ and “[“. Use a space after “)”
and “]” (unless the next character is “;”).– No code after “{“ or “}” on same line.– No space after “(“ or before “)”.– Use space after “,” or “;” in parameter lists or for loop
arguments, but not before.– Put a space on both sides of an operator.– No space before “;”.
Winter 2006 CISC121 - Prof. McLeod 20
Do
public class StyleDemo {
public static int someSum (int num1, int num2) {
int sum = num1 + num2;
return sum;
} // end someSum method
} // end StyleDemo class
Winter 2006 CISC121 - Prof. McLeod 21
Don’t!
public class StyleDemo{
public static int s(int l,int l1){
int S=l+l1; return S;
}}
Winter 2006 CISC121 - Prof. McLeod 22
Programming Style & Documentation – Cont.
• Variable Names– Also applies to method and class names.– Follow java restrictions on names:
• Use only letters, numeric digits (0 to 9) and the “_” character.• Cannot start name with a number.• Java is case sensitive!
– Variables and method names usually start with a lower case character. Class names start with an upper case character. Constants are all in upper case.
– Variables are usually nouns.– Methods are verbs or verbs and nouns.
Winter 2006 CISC121 - Prof. McLeod 23
Programming Style & Documentation – Cont.
– Be descriptive, but not excessive!– Examples:
•numStudents•setPassingGrade ( parameter list )
– Somewhat too long…:•flagThatIsSetToTrueIfAProblemArisesWhenThereIsAFullMoonOverMyHouseInTheWinterWhileMyProgramIsRunning
– It is OK to use single letter variable names such as i, j, k for counters in loops.
Winter 2006 CISC121 - Prof. McLeod 24
Programming Style & Documentation – Cont.
• The java compiler ignores all white space including space characters, tabs and carriage return/line feed characters.
• Note that most java keywords are in lower case.• You will get an error message if you attempt to
use a keyword as a variable name.
Winter 2006 CISC121 - Prof. McLeod 25
One-Dimensional Arrays
• An array is just a collection of items, stored in computer memory (RAM).
• In Java:– The items must all be of the same base type.– Can be of any primitive type or object.– The size of the array must be declared before any
items can be stored.– The size of the array cannot be changed after
declaration.– An array occupies a contiguous memory space.– Array elements are numbered from zero.
Winter 2006 CISC121 - Prof. McLeod 26
One-Dimensional Arrays - Cont.
• The use of arrays in memory offers great speed advantages over processing data in and out of files.– File operations are always much slower than
operations dealing only in RAM.– Typically, you will write array programs to:
• Read values from a file.• Carry out all the calculations and manipulations
required, in memory.• Save the data back to another file.
• Arrays make it much easier to carry out the same calculation on many values.
Winter 2006 CISC121 - Prof. McLeod 27
One-Dimensional Arrays - Declaration
• For example, to create an array to hold 10 integers:
int[] testArray = new int[10];
• testArray now points to an area of memory that holds locations for 10 integers.
• It also points to one location that holds testArray.length which is an attribute of the array, that is equal to the number of elements.
• Arrays are Objects in Java.
Winter 2006 CISC121 - Prof. McLeod 28
0
0
0
0
0
0
0
0
0
0
One-Dimensional Arrays - Declaration, Cont.
0180ff
…
int[]
testArray
0480ff
0480ff
10.length
• As a “pointer”, testArray points to an area of memory that contains a series of int values as well as the attribute length.
Winter 2006 CISC121 - Prof. McLeod 29
One-Dimensional Arrays - Declaration, Cont.
• The java statement above can be split into two:
int[] testArray;
testArray = new int[10];
• The first statement creates a variable of type int[] - that is to say that it will be an array of int’s.
• The variable, testArray is now an object of type int[] that contains an “object reference” or a pointer. The object reference is null after the first statement.
Winter 2006 CISC121 - Prof. McLeod 30
One-Dimensional Arrays - Declaration, Cont.
int[] testArray;testArray = new int[10];
• The second statement looks for a chunk of memory big enough to contiguously hold 10 integers (about 40 bytes), and then changes the object reference of testArray from null to the memory location of the chunk.
• This assignment of the object reference of the testArray object is carried out by the “=“ assignment operator.
• The new keyword is responsible for blocking out the memory space and initializing each memory location to the default value for a new memory location of type int (zero).
Winter 2006 CISC121 - Prof. McLeod 31
• Back to the 10 array elements in memory:
testArray[0]testArray[1]testArray[2]testArray[3]testArray[4]testArray[5]testArray[6]testArray[7]testArray[8]testArray[9]
One-Dimensional Arrays - Cont.
0
0
0
0
0
0
0
0
0
0
10
testArray.length
Winter 2006 CISC121 - Prof. McLeod 32
One-Dimensional Arrays - Indices
• The numbers 0 to 9 are called the index values of the array. The notation used above allows you to refer to individual elements.
• Note that the elements of the array are numbered from zero.
• arrayname.length returns the number of elements in the array.
Winter 2006 CISC121 - Prof. McLeod 33
One-Dimensional Arrays - Cont.
• for loops are often used with arrays. For example, to initialize each of the elements of testArray to the value 1000 * i:
int i;
for (i = 0; i < 10; i++)
testArray[i] = 1000 * i;
• Arrays can also be initialized at declaration, using an “array initializer”. To get the same array as above:
int[] testArray = {0, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000};
Winter 2006 CISC121 - Prof. McLeod 34
One-Dimensional Arrays - Cont.
• Arrays can also be created using a variable (or constant) to specify the array size:
final int MAX_SIZE = 1000;
int[] testArray = new int[MAX_SIZE];
int size = testArray.length; // size is 1000
Winter 2006 CISC121 - Prof. McLeod 35
One-Dimensional Arrays - Cont.
• All the examples so far, have been arrays of int’s.
• Could be arrays of double’s, boolean’s or even String’s: (anything in fact, as long as all the array elements are the same “thing”)
• For example:
Winter 2006 CISC121 - Prof. McLeod 36
More Declaration Examples
double[] dArray = new double[50];
String[] sArray = new String[100];
String[] sArray2 = {“Hi”, “Ho”, “Silver!”};
• Note that there is some flexibility in where the first set of “[]” goes. These two declarations are equivalent:
double[] disNDat = new double[1000];
double disNDat[] = new double[1000];
Winter 2006 CISC121 - Prof. McLeod 37
One-Dimensional Arrays - “Out-of-bounds” Error
• If n is the size of the array, then:• Array indices (or “subscripts”) < 0 or n are
illegal, since they do not correspond to real memory locations in the array.
• These indices are said to be out-of-bounds.• Reference to an out-of-bounds index produces an
out-of-bounds exception, and the program will crash if the exception is not caught.