File I/O Array Basics For-each loop 178
Recap Use the Java API to look-up classes/method details: Math, Character, String, StringBuffer, Random, etc. The Random class gives us several ways to generate random data, but we often need to apply transformations to get what we need Review posted RandomStuff solution 179
Text Files for Input/Output text files are simply character streams (sequences) standard streams: System.in, System.out, System.err (also for output, used for error messages usually) import java.io.*; // I/O package needed for file classes use FileReader (input) and PrintWriter (output) classes for character data IOException must be caught or thrown by every method that indirectly or directly uses an IO class (particularly for input): public static void main(string[] args) throws IOException EXAMPLES: code/filesdemo.java [There are other types of files that we won't be using in this course.] 180
Writing to Files Declare and initialize an object linked to the external filename: PrintWriter outfile = new PrintWriter("outfile.txt"); Use print(), println() and printf() to write data to the file, just like we did with System.out: outfile.print("writing to this file"); Save the data permanently to your file system when done: outfile.close(); // very important to save data permanently use String literal or variable with external file name to create will overwrite existing contents if file already exists, will create new file otherwise must close file to save permanently! 181
Reading from files reading from a file: Scanner filescan = new Scanner(new FileReader("infile.txt")); // proceed as usual: filescan.next(), nextint(), nextdouble(), etc. infile.close(); // when finished reading from it use String literal or variable with external file name to initialize file must already exist, otherwise an exception is thrown reading to end of input: while (scan.hasnext()) // scan can be keyboard or string or file true if there is more input false when the end of input is reached type ^d (unix, Mac) or ^z (PC, jgrasp) to denote end of keyboard input, or right-click in jgrasp and choose "Close Input Stream" 182
Review: Scanner class for input import java.util.*; Create object of class, init w/system.in for keyboard input, or with a String, or with a FileReader Methods for various data types, separated by whitespace (space, tab, newline) next() (String, stopping at first whitespace) nextint() (int) nextdouble() (double) next().charat(0) (char) nextline() (String, entire line to end including whitespace) hasnext() or hasnextline() is true if not at end of input, false if at end (good for controlling loops) 183
More Method Docs We can add more tags depending on what else affects the method, include the @throws tag for methods that throw things like the IOException /** General description of method goes on the first line. @param first what the first parameter is for, plus assumptions @param second how the second param is used, etc. @return what gets returns if not void, otherwise omit @throws SomeException explain any declared exceptions */ Remember: checkstyle requires the description to end in a period 184
Pig-Latin Revisited Problem Statement: We want a program that can convert a text document from English to Pig-Latin (simplified version). This is some pig latin. Histay ishay omesay igpay atinlay. (simplified form) Subroutines we need to write: String convertword(string orig) String convertline(string line) void convertfile(string origfile, String newfile) 185
Pig-Latin Pseudocode convertfile(string origfile, String newfile) Initialize input file Initialize output file For every line in the input file Write the conversion to the output file Write an end of line character to the output convertline(orig) Set result to For every word in orig: Add convertword(word) to result Add space to result Return result 189
Pig-Latin completed Write a full pig-latin program using these subroutines: String convertword(string orig) (adapt code from 9/25) String convertline(string line) void convertfile(string origfile, String newfile) Your main method should get the name of the input file. The output file should be named Pig + the input filename. If extra time, deal with capital letters correctly deal with punctuation correctly Submit on Blackboard as c10 190
I/O Recap File I/O requires an extra step to initialize and one to save, and declaring an exception File input uses a Scanner as usual File output using print, println, printf as usual 191
Arrays allow one variable to hold multiple values all values must be of the same base type integer indices are used to access individual values, called array elements [] are used to denote indices indices begin at 0 always we must declare a size (capacity) to create arrays are reference objects in java.length tells us the declared size of any array variable 194
Array examples Declare variable: ra int[] ra; double xray[]; Allocate memory: ra = new int[20]; int size = 6; xray = new double[size]; Access element: ra[0] = 23; xray[3] = -23.492; 0 1 2 3 4 5... 17 18 19 0 1 2 3 4 5 xray 195
Array Initializations primitive base types are initialized to 0 reference (object) base types are initialized to null can use an initializer list to declare & initialize if base type is primitive or String: int hw[] = {40, 30, 25, 35, 42, 47}; can use a loop to initialize various ways: for (int i=0; i < hw.length; i++) hw[i] = i*2; 196
Array Practice Piazza polls: @210 Array Init1 @211 Array Init2 @212 Array Init3 @208 Array Init4 197
Midterm Reminders In class Wednesday Bring writing implements no other tools allowed Bring J-card for identification (required!) Spread out as soon as you get to class 198
Midterm! 199