Week 8 Variables of class Type - Correction! Libraries/Packages String Class, reviewed Screen Input/Output, reviewed File Input/Output Coding Style Guidelines A simple class: Variables of class Type public class Student { private int age; private boolean is_awake; private boolean is_reading_paper; public Student (int n, boolean awake, boolean paper) { set_student(n, awake, paper); } // end default constructor public void set_student (int n, boolean awake, boolean paper) { age = n; is_awake = awake; is_reading_paper = paper; } // end set_student method // more methods } // end Student class APSC142 - Prof.McLeod 1 APSC142 - Prof.McLeod 2 Variables of class Type, Cont. What would be returned by: artsstudent = apscstudent; (apscstudent == artsstudent)? Variables of class Type, Cont. What would be returned by: (apscstudent == artsstudent)? true (not false as in last week s lecture!) Memory Location Variable Name Value 1048 apscstudent 5012 1120 artsstudent 5012 More memory locations When the equality operator is used to compare objects, it only compares the memory locations referenced by the two objects. Suppose we tried: 5012 8068 age 32 is_awake true is_reading_paper false (methods, etc ) More memory locations age 22 is_awake false is_reading_paper false (methods, etc ) Student test1 = new Student(20, true, true); Student test2 = new Student(20, true, true); (test1 == test2) // would return false test1 = test2; // match memory locations (test1 == test2) // now returns true // regardless of attribute values Should define an equals method as member of Student class. APSC142 - Prof.McLeod 3 APSC142 - Prof.McLeod 4 1
Libraries or Packages A package is a collection of classes that are grouped together under one package name. The classes are still in separate files and follow the same naming rules, as always. The first line in a class that is to be included in a package must be: package package_name; package_name must include the directory path from that given by the CLASSPATH DOS environmental variable (internal to JBuilder2). For example, if your package classes are in C:\JBuilder2\myclasses\myStuff\utilities then package_name would be mystuff.utilities. In order to use all these classes a program uses an import statement: import mystuff.utilities.*; Libraries or Packages, Cont. The import statement must also be right at the top of the program, before the class definition line. The * at the end tells the import statement to import all classes - otherwise you can specify which classes you want to import. Packages that are often imported for simple input/output (screen or file) are java.io.* and java.util.*. GUI tools are available from Swing: javax.swing.* and/or AWT: java.awt.* and java.awt.event.*. Essentially, importing packages allows you to extend the Java language with the tools that you need for your purposes. APSC142 - Prof.McLeod 5 APSC142 - Prof.McLeod 6 String literals: String Class, reviewed Escape Characters: String Class, Cont. Press <enter> to continue. String variable declaration: String teststuff; or: String teststuff = A testing string. ; String concatenation ( addition ): String teststuff = Hello ; System.out.println(testStuff + to me! ); Would print the following to the DOS window: Hello to me! \ Double quote \ Single quote \\ Backslash \n Go to beginning of next line \r Go to beginning of current line \t Tab character For example: String teststuff = Line1\nLine2 ; System.out.println(testStuff); Would print the following to the DOS window: Line1 Line2 APSC142 - Prof.McLeod 7 APSC142 - Prof.McLeod 8 2
String Class, Cont. String methods include: length() equals(otherstring) equalsignorecase(otherstring) tolowercase() touppercase() trim() charat(position) substring(start) substring(start, End) indexof(searchstring) replace(oldchar, newchar) startswith(prefixstring) endswith(suffixstring) Wrapper Class Methods for String/Number Conversions Integer.parseInt(String value) // returns // an int Integer.toString(int value) // returns a // String Double.valueOf(String value) // returns a // double Double.toString(double value) // returns a // String Remember that wrapper class methods are all static. APSC142 - Prof.McLeod 9 APSC142 - Prof.McLeod 10 Screen Input/Output, reviewed To print to the screen (a DOS window): System.out.print( Good Morning ); // no LF System.out.println( Class! ); // appends LF print and println are overloaded methods, and can take arguments of any primitive type, String class, or object. To get input from the screen (from the user): SavitchIn.readLine() // returns a String SavitchIn.readLineInt() // returns int SavitchIn.readLineDouble() // returns double SavitchIn.readLineNonwhiteChar() // returns //first non-space char All SavitchIn methods are static. The SavitchIn class uses java.io and java.util libraries. File Input/Output File input means reading from a file into memory. File output means writing to a file from memory. SavitchIn does not include any methods for file input/output. We will be concerned with input/output for text files only (as opposed to binary files). Text files can be easily viewed, edited and/or created with Notepad, or any other text editor. Need to use methods and classes from the java.io library, so you must have an import statement as the first line in your program file: import java.io.*; APSC142 - Prof.McLeod 11 APSC142 - Prof.McLeod 12 3
Inside your method: File Output For example: File Output, Cont. PrintWriter outputstream = new PrintWriter( new FileOutputStream(fileName)); PrintWriter dataout = new PrintWriter( new FileOutputStream( Data.txt )); PrintWriter and FileOutputStream are classes from java.io. outputstream is a variable name that you choose. filename is a String literal or String variable representing the name of a text file. As used above, if filename does not exist, it is created. If filename does exist, the previous content of the file is overwritten. To append to an existing file, use: PrintWriter outputstream = new PrintWriter( new FileOutputStream(fileName, true)); To write text to the file use print() or println() methods: dataout.print( No LF after this line! ); dataout.println( This one has a LF. ); When finished writing to file, close it using: dataout.close(); Closing a file immediately after writing helps to prevent corruption of your file, if your program crashes before it would normally terminate. APSC142 - Prof.McLeod 13 APSC142 - Prof.McLeod 14 Inside your method: File Input To read from the file: File Input BufferedReader inputstream = new BufferedReader(new FileReader(fileName)); BufferedReader and FileReader are classes from java.io. iputstream is a variable name that you choose. filename is a String literal or String variable representing the name of a text file. For example: String inputline = null; inputline = indata.readline().trim(); // returns trimmed String value to // inputline. // entire line is read. // null is returned if at end of file. When done, close the file: indata.close(); BufferedReader indata = new BufferedReader(new FileReader( Data.txt )); APSC142 - Prof.McLeod 15 APSC142 - Prof.McLeod 16 4
File Input/Output, Cont. Note that the filename String can contain a full or relative path, along with the filename. The path and filename must be legal for the operating system in use. The techniques described above are for textonly sequential file operations. Sequential means that you can only add data to the end of the file. Reading the file must start at the beginning of the file and progress towards the end. Random input/output can be done with binary files. You can read/write to any position in the file. When a file is not found (for input), or cannot be opened (for output), an exception is thrown by the java.io classes used. In more advanced programs, these exceptions can be caught and handled. Coding Style Guidelines The purpose of adding white space and comments to your code is to make it easier to maintain, as well as making it more easily understood by another programmer. Properly formatted comments can also be used to generate external documentation (using javadoc ). But don t go overboard! Too many comments swamp out the code. Don t repeat yourself in comments! Be concise! Use descriptive variable names, that might use one, two or possibly even three words - don t use a sentence! For example: num_students is much better than: variable_to_keep_track_of_the_number_of_students APSC142 - Prof.McLeod 17 APSC142 - Prof.McLeod 18 Coding Style Guidelines, Cont. 1. Variable Names Use descriptive variable names (method names will probably contain a verb). Use all uppercase for constants. Primitive type variable names start with a lowercase letter, object names start with an upper case letter. Use _ to space out the variable name. 2. Indentation Use a three-space indent (JBuilder default). Indent code in any block. Line up braces ({}) as follows: while (total < 25) { } total += 5; System.out.println("The total is " + total); Line up else with corresponding if: if (num_students > 100) statement; else statement; Coding Style Guidelines, Cont. 3. Spacing Put one space after every comma in a parameter list. Put one space on either side of a binary operator (like: +, -, <, >=, etc.) Do not put a space after ( or before ). Do not put a space before ;. Put one space before (. Do not put a space before [ 4. Comments Add comments as you complete logical units of your code - don t wait until you are finished. Assume that your reader is familiar with the Java language, but has no idea of how your program works. Make sure your comments keep up with code changes. If you use a block comment (/*.*/) then add a * to the left of each line. Comment any variable name that is not completely self-explanatory. APSC142 - Prof.McLeod 19 APSC142 - Prof.McLeod 20 5
Coding Style Guidelines, Cont. 4. Comments, Cont. A comment should be aligned with the block it is describing. Block comments should be used to describe each class and method. Include author name(s), and date, version or revision number (for larger projects) in the comment describing a class. It should also describe the purpose of the class. Method comments should include a description of what the method does, and the algorithm used. The main method comment should describe the overall purpose of the main method and what input & output should be provided and expected. Add short comments to the code body of a method where appropriate. Provide a brief explanation of logical units of code. When you are coding, you can add comments to remind yourself of an area that will need additional work after another module is completed, for example. Add an in-line comment after each close } to indicate what they close. Coding Style Guidelines, Cont. 5. External Documentation At present, you append the sample DOS output of your program to the end of your program as a comment. That is all that is required for this course. External documentation is supplied for a user of your code. It is less technical and more descriptive. It describes the purpose of the program and describes the user interface (but not the implementation!). The description would include the input and output of the program, and the meanings of various error messages, etc. You must assume that your user knows nothing about programming, and has only fundamental computer skills. APSC142 - Prof.McLeod 21 APSC142 - Prof.McLeod 22 6