CSCI/CMPE 3326 Object-Oriented Programming in Java Class, object, member field and method, final constant, format specifier, file I/O Dongchul Kim Department of Computer Science University of Texas Rio Grande Valley
Examples - class class Test public static void main(string[] args) Person p = new Person(); class Person String name; int age;
Examples - constructor class Test class Person public static void main(string[] args) String name; int age; Person(String na, int a) Person p = new Person(); // error name = na; age = a;
Examples - constructor class Test class Person public static void main(string[] args) String name; int age; Person(String na, int a) Person p = new Person( Mike, 18); // no error name = na; age = a;
class Test Examples - method class Person public static void main(string[] args) String name; int age; void disply_age() Person p = new Person(); System.out.println(age);
dot operator to access members class Test class Person public static void main(string[] args) String name; int age; void disply_age() Person p = new Person(); p.age = 21; p.display_age(); System.out.println(age);
final
Creating Named Constants with final Constants keep the program organized and easier to maintain. Constants are identifiers that can hold only a single value. Constants are declared using the keyword final. Constants need not be initialized when declared; however, they must be initialized before they are used or a compiler error will be generated.
Creating Named Constants with final Once initialized with a value, constants cannot be changed programmatically. By convention, constants are all upper case and words are separated by the underscore character. For example: final double CAL_SALES_TAX = 0.0725;
printf
Setting the Field Width A format specifier may also include a field width. Here is an example: int number = 9; System.out.printf("The value is %6d\n", number); The format specifier %6d indicates that the argument number should be printed in a field that is 6 places wide. If the value in number is shorter than 6 places, it will be right justified. Here is the output of the code. 123456 The value is 9 If the value of the argument is wider than the specified field width, the field width will be expanded to accommodate the value.
Using Field Widths to Print Columns Field widths can help when you need to print values aligned in columns. For example, look at the following code: int num1 = 97654, num2 = 598; int num3 = 86, num4 = 56012; int num5 = 246, num6 = 2; System.out.printf("%7d %7d\n", num1, num2); System.out.printf("%7d %7d\n", num3, num4); System.out.printf("%7d %7d\n", num5, num6); This code displays the values of the variables in a table with three rows and two columns. Each column has a width of seven spaces. Here is the output for the code: 97654 598 86 56012 246 2 1 2 3 4 5 6 7 1 2 3 4 5 6 7
Printing Formatted Floating- Point Values If you wish to print a floating-point value, use the %f format specifier. Here is an example: double number = 1278.92; System.out.printf("The number is %f\n", number); This code produces the following output: The number is 1278.920000 You can also use a field width when printing floating-point values. For example the following code prints the value of number in a field that is 18 spaces wide: System.out.printf("The number is %18f\n", number);
Printing Formatted Floating- Point Values In addition to the field width, you can also specify the number of digits that appear after the decimal point. Here is an example: double grosspay = 874.12; System.out.printf("Your pay is %.2f\n", grosspay); In this code, the %.2f specifier indicates that the value should appear with two digits after the decimal point. The output of the code is: Your pay is 874.12 1 2
File I/O
File Input and Output Reentering data all the time could get tedious for the user. The data can be saved to a file. Files can be input files or output files. Files: Files have to be opened. Data is then written to the file. The file must be closed prior to program termination. In general, there are two types of files: binary text
Writing Text To a File To open a file for text output you create an instance of the PrintWriter class. PrintWriter outputfile = new PrintWriter("test.txt"); Pass the name of the file that you wish to open as an argument to the PrintWriter constructor. Warning: if the file already exists, it will be erased and replaced with a new file.
The PrintWriter Class The PrintWriter class allows you to write data to a file using the print and println methods, as you have been using to display data on the screen. Just as with the System.out object, the println method of the PrintWriter class will place a newline character after the written data. The print method writes data without writing the newline character.
The PrintWriter Class Open the file. PrintWriter outputfile = new PrintWriter("Names.txt"); outputfile.println("chris"); outputfile.println("kathryn"); outputfile.println("jean"); outputfile.close(); Close the file. Write data to the file.
The PrintWriter Class To use the PrintWriter class, put the following import statement at the top of the source file: import java.io.*;
Exceptions When something unexpected happens in a Java program, an exception is thrown. The method that is executing when the exception is thrown must either handle the exception or pass it up the line. Handling the exception will be discussed later. To pass it up the line, the method needs a throws clause in the method header.
Exceptions To insert a throws clause in a method header, simply add the word throws and the name of the expected exception. PrintWriter objects can throw an IOException, so we write the throws clause like this: public static void main(string[] args) throws IOException
Example - PrintWriter import java.io.*; public class Hello public static void main(string[ ] args) throws IOException PrintWriter pw = new PrintWriter("test.txt"); pw.println("hello, Dr. Kim."); pw.close();
Appending Text to a File To avoid erasing a file that already exists, create a FileWriter object in this manner: FileWriter fw = new FileWriter("names.txt", true); Then, create a PrintWriter object in this manner: PrintWriter pw = new PrintWriter(fw);
Example - FileWriter import java.io.*; public class Hello public static void main(string[ ] args) throws IOException FileWriter fw = new FileWriter("test.txt", true); //PrintWriter pw = new PrintWriter("test.txt"); PrintWriter pw = new PrintWriter(fw); pw.println("hello, Dr. Kim."); pw.close();
Specifying a File Location On a Windows computer, paths contain backslash (\) characters. Remember, if the backslash is used in a string, it is a special character so you must use two of them (\\): FileWriter fw = new FileWriter("C:\\test.txt", true);
Specifying a File Location This is only necessary if the backslash is in a string literal. If the backslash is in a String object then it will be handled properly. Fortunately, Java allows Unix style filenames using the forward slash (/) to separate directories: FileWriter fw = new FileWriter("./test.txt", true);
Reading Data From a File You use the File class and the Scanner class to read data from a file: Pass the name of the file as an argument to the File class constructor. File f1= new File("Customers.txt"); Scanner s1 = new Scanner(f1); Pass the File object as an argument to the Scanner class constructor.
Reading Data From a File Scanner s1 = new Scanner(System.in); System.out.print("Enter the filename: "); String filename = s1.nextline(); File file = new File(filename); Scanner s2 = new Scanner(file); The lines above: Creates an instance of the Scanner class to read from the keyboard Prompt the user for a filename Get the filename from the user Create an instance of the File class to represent the file Create an instance of the Scanner class that reads from the file
Reading Data From a File Once an instance of Scanner is created, data can be read using the same methods that you have used to read keyboard input (nextline, nextint, nextdouble, etc). // Open the file. File file = new File("Names.txt"); Scanner s1 = new Scanner(file); // Read a line from the file. String str = s1.nextline(); // Close the file. s1.close();
Example Read File import java.io.*; import java.util.scanner; public class Hello public static void main(string[] args) throws IOException File f1 = new File("C:\\test.txt"); PrintWriter pw = new PrintWriter(new FileWriter(f1,true)); pw.println("hello, Dr. Kim."); pw.println("how are you?"); pw.close(); Scanner s1 = new Scanner(f1); System.out.println(s1.nextLine()+" "+s1.nextline()); s1.close();
Exceptions The Scanner class can throw an IOException when a File object is passed to its constructor. So, we put a throws IOException clause in the header of the method that instantiates the Scanner class.
Detecting The End of a File The Scanner class s hasnext() method will return true if another item can be read from the file. // Open the file. File file = new File(filename); Scanner s1 = new Scanner(file); // Read until the end of the file. while (s1.hasnext()) String str = s1.nextline(); System.out.println(str); s1.close();// close the file when done.