Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Dealing with Files COMP 102 #
© Peter Andreae COMP : 2 Menu Guidelines for designing loops Files Scanners Examples of methods with loops to process files. Reading: L-D-C: Administration Did you miss the test??? Flu shots: free for students. see details on the Forum.
© Peter Andreae COMP : 3 Designing loops Is the number of steps determined at the beginning? int i = 0;int i = 1; while ( i < number) {while ( i <= number) { do actions 〉 i = i + 1;i++;} Note, can count from 0 or from 1! Otherwise 〈 intialise 〉 while ( 〈 condition-to-do it again 〉 ) { 〈 body 〉 〈 increment 〉 } Shorthand for i = i+1
© Peter Andreae COMP : 4 Designing loops Does exiting the loop depend on the actions? if soor set up for the test while ( true ) { while ( test ) {set up for the test do actionsif ( exit-test ) { set up for the next test break; } do actions } Write out the steps for a couple of iterations including the tests to determine when to quit/keep going Identify the section that is repeated preferably starting with the test Wrap it with a while ( ) { } Identify the condition for repeating.
© Peter Andreae COMP : 5 Nested loops: while inside while public void drawCircles(int rows, int cols) { int diam = 20; int row = 0; while (row < rows) { int y = 20 +row*diam; int col = 0; while ( col < cols ) { int x = 50 + col*diam; UI.fillOval(x, y, diam, diam); col = col + 1; } row = row + 1; }
© Peter Andreae COMP : 6 Files The UI text pane window is transient: Typing large amounts of input into the text pane is a pain! It would be nice to be able to save the output of the program easily. Large amounts of text belong in files How can you write to a file ? How can you read from a file ? Easy! Files behave very like the UI text pane: next, nextInt etc read from a file, (via a Scanner object) print, println, printf write to a file (via a PrintStream object)
© Peter Andreae COMP : 7 Files: An overview My Program : int a =??.nextInt(); : ??.println(a*5); } My Program : int a =??.nextInt(); : ??.println(a*5); } Enter numbers: done Enter numbers: done UI Window UI.nextInt(); UI.println(); A real file: “myfile.txt” File object Scanner object Scanner object next(); println(); PrintStream object
© Peter Andreae COMP : 8 Scanner Scanner: a class in the java that allows a program to read user input from a source (console, a file, a String, …) New concept ? Not really! UI.next() and other next methods are actually a Scanner working in the background while(UI.hasNextInt()){ double amt = UI.nextDouble() } Most UI next methods work same as Scanner next methods, but a very few subtle differences…see Java documentation while(scan.hasNextInt()){ double amt = scan.nextDouble(); } Scanner scan = new Scanner(myfile);
© Peter Andreae COMP : 9 Reading using Scanner: /** Read lines from a file and print them to UI text pane. */ public void readFile(){ File myfile = new File(“input.txt”); Scanner scan = new Scanner(myfile); UI.println(“ input.txt ”); while (scan.hasNext()){ String line= scan.nextLine(); UI.println(line); } UI.println(“ end of input.txt ”); } Almost right, but compiler complains!!! Dealing with files may “raise exceptions”
© Peter Andreae COMP : 10 Files: handling exceptions If a piece of code might raise an exception: Have to enclose it in a try { … } catch (IOException e) { … } public void readFile(){ File myfile = new File(“input.txt”); try { Scanner scan = new Scanner(myfile); while (scan.hasNext()){ String line = scan.nextLine(); UI.println(line); } UI.println(“ end of input.txt ”); } catch (IOException e) { UI.println(“File failure: ” + e); } what to do what to do if it goes wrong
© Peter Andreae COMP : 11 Reading from files: example 2 /** Finds oldest person in file of ages and names. */ public void printOldest(){ try { Scanner scan = new Scanner(new File(“names.txt")); String oldest = ""; int maxAge = 0; while (scan.hasNextInt()){ int age = scan.nextInt(); String name = scan.nextLine(); if (age > maxAge) { maxAge = age; oldest = name; } UI.printf(“Oldest is %s (%d)%n”, oldest, maxAge); } catch (IOException e) { UI.printf(“File failure: %s%n”, e); } } no need to prompt user! 33 James Bond 25 Helen Clerk 73 John F Quay 19 pondy Copes with multi- token names
© Peter Andreae COMP : 12 Testing end of file Unlike UI text pane, can test for end of file: /** Finds oldest person in file of names and ages. */ public void printOldest(){ try { Scanner scan = new Scanner(new File(“names.txt")); String oldest = “”; int maxAge = 0; while (scan.hasNext()){ String name = scan.next(); int age = scan.nextInt(); if (age > maxAge) { maxAge = age; oldest = name; } UI.println(“Oldest is %s (%d)%n”, oldest, maxAge); } catch (IOException e) { UI.printf(“File failure: %s%n”, e); } } False when at end of file name first; age second Note: name must be just one token!! James 33 Helen 25 John 73 pondy 19
© Peter Andreae COMP : 13 A common simple pattern File with one entity per line, described by multiple values: while (sc.hasNext() ){ String type = sc.next(); double cost = sc.nextDouble(); int wheels = sc.nextInt(); String colour = sc.next(); String make = sc.next() if (wheels > 4) { …. } else { … } bicycle green Giant truck black Isuzu car red Toyota … Read all the values into variables process the values in the variables