Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Files COMP 102 # T2
© Xiaoying Gao, Peter Andreae COMP : 2 Assignments, handout Java brief documentation A4 due Friday 10am Q1 Changing a double to int: casting (int)(Math.random()*40) Changing a number to String, can you can drawString “”+num return statement return value; value must match with returned type Leave the method
© Xiaoying Gao, Peter Andreae COMP : 3 Use the brief documentation UI class: public void drawString(String s, double left, double baseline) UI.drawString(“Hello”, 100, 200); String class: public int length() String message = “Good Morning”; int x = message.length(); If (message.length()>10){ … }
© Xiaoying Gao, Peter Andreae COMP : 4 Call a method Static methods: call from class name:UI, Math, System Instance methods: objectName.methodName(arguments) Objects Default: this (call method in the same class) Create your own objects: new … types: String, Animal, Color, Scanner, ButterFly Arguments, data to use Check documentation (or your own code), to find out parameters Must match the type, order, number of parameters If the method returns a value Assign it to a variable (store it) Print it out (use it for output) Do nothing (throw it away)
© Xiaoying Gao, Peter Andreae COMP : 5 Assignment 4 Q1 Get the basic if else if else Guess 5 times Then other methods, test each method separately
© Xiaoying Gao, Peter Andreae COMP : 6 Assignment 4 Q1 public boolean playRound(){ int n = (int) (maxValue*Math.random()+1); int count = 5; while(count >0){ int x =UI.askInt("guess a number: "); count = count -1; if (x == n){ UI.println("you got it!"); return true; }else if (x>n){ UI.println("too big"); }else{ UI.println("too small"); } UI.println(“you didn’t get it, the number is: "+ n); return false; }
© Xiaoying Gao, Peter Andreae COMP : 7 Assign 4 Q1 public boolean playRound(){ boolean b = false; int n = (int) (maxValue*Math.random()+1); int count = 5; while((count >0) && (b == false)){ int x =UI.askInt("guess a number: "); count = count -1; if (x == n){ UI.println("you got it"); b = true; }else if (x>n){ UI.println("too big"); }else{ UI.println("too small"); } UI.println("the number is: "+ n); return b; }
© Xiaoying Gao, Peter Andreae COMP : 8 Write a method Input Ask User Use parameters: data will be given when it is called type name Processing data Assignment statement Call a method If statement While statement Output Print to screen Draw on screen Return a value
© Xiaoying Gao, Peter Andreae COMP : 9 Today’s topic File as Input, Output File class Scanner class PrintStream class
© Xiaoying Gao, Peter Andreae COMP : 10 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 read from a file ? How can you write to 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)
© Xiaoying Gao, Peter Andreae COMP : 11 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
© Xiaoying Gao, Peter Andreae COMP : 12 Scanner Scanner: a class in the java that allows a program to read user input from a source (such as the UI text pane or a file) New concept ? Not really! UI.next() and other next methods are actually a scanner working in the background while(UI.hasNextDouble()){ 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.hasNextDouble()){ double amt = scan.nextDouble(); } Scanner scan = new Scanner(myfileObject);
© Xiaoying Gao, Peter Andreae COMP : 13 Reading using Scanner (not completed) /** 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”
© Xiaoying Gao, Peter Andreae COMP : 14 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 name = scan.nextLine(); UI.println(name); } UI.println(“Read and printed all names”); } catch (IOException e) { UI.println(“File failure: ” + e); } what to do what to do if it goes wrong
© Xiaoying Gao, Peter Andreae COMP : 15 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
© Xiaoying Gao, Peter Andreae COMP : 16 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
© Xiaoying Gao, Peter Andreae COMP : 17 Writing to a File Open a File Wrap it in a new PrintStream object. Call print, println, or printf on it. Close the file : PrintStream out = new PrintStream(new File("Square-table.txt")); int n=1; out.println("Number\tSquare"); while ( n <= 1000 ) { out.printf("%6d\t%8d\n", n, n*n); n = n+1; } out.close() : File Object
© Xiaoying Gao, Peter Andreae COMP : 18 Check if files exist before reading Can check that file exists before trying to read: /** Make a copy of a file with line numbers */ public void lineNumber(String fname){ File infile = new File(fname); if (infile.exists()) { File outfile = new File(“numbered-” +fname) try { PrintStream out = new PrintStream(outfile); Scanner sc = new Scanner ( infile ); int num = 0; while (sc.hasNext()) { out.println((num++) + “: ” + sc.nextLine() ); } out.close(); sc.close(); } catch (IOException e) {UI.printf(“File failure %s\n”, e);} }
© Xiaoying Gao, Peter Andreae COMP : 19 Passing a scanner object to other method First method: Just opens and closes the file public void countTokensInFile(String fname){ try { Scanner sc = new Scanner (new File(fname)); UI.printf(“%s has %d tokens\n”, fname, this.countT(sc)); sc.close(); } catch (Exception e) {UI.printf(“File failure %s\n”, e);} } Second Method: Just reads from the file and counts public int countT (Scanner scan){ int count = 0; while (scan.hasNext()) { scan.next(); // throws result away ! count = count+1; } return count; }
© Xiaoying Gao, Peter Andreae COMP : 20 UIFileChooser So far, we’ve specified which file to open and read or write. eg: File myfile = new File(“input.txt”); How can we allow the user to choose a file ? UIFileChooser class (part of comp102 library, like UI) MethodWhat it doesReturns open() Opens dialog box; user can select an existing file to open. Returns name of file or null if user cancelled. String open(String title) Same as open(), but with specified title;String save() Opens dialog box; user can select file (possibly new) to save to. Returns name of file, or null if the user cancelled. String save(String title) Same as save(), but with specified title.String
© Xiaoying Gao, Peter Andreae COMP : 21 /** allow user to choose and open an existing file*/ String filename = UIFileChooser.open(); File myfile = new File(filename); Scanner scan = new Scanner(myfile); OR Scanner scan = new Scanner(new File(UIFileChooser.open())); /** allow user to choose and open an existing file, specifies a title for dialog box*/ File myfile = new File(UIFileChooser.open(“Choose a file to copy”)); Scanner scan = new Scanner(myfile); Two “open” methods in one class ? Overloading: two methods in the same class can have the same name as long as they have different parameters. Using UIFileChooser methods: open
© Xiaoying Gao, Peter Andreae COMP : 22 Using UIFileChooser methods: save /** allow user to choose and save to a (new/existing) file*/ String filename = UIFileChooser.save(); File myfile = new File(filename); PrintStream ps = new PrintStream(myfile); OR PrintStream ps = new PrintStream(new File(UIFileChooser.save())); /** allow user to choose and save to a (new/existing) file, Specifies a title for dialog box */ File myfile = new File(UIFileChooser.save(“File to save data in”)); PrintStream ps = new PrintStream(myfile);