Download presentation
Presentation is loading. Please wait.
Published byTodd McDaniel Modified over 9 years ago
1
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Files COMP 102 #15 2015T2
2
© Xiaoying Gao, Peter Andreae COMP 102 14: 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
3
© Xiaoying Gao, Peter Andreae COMP 102 14: 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){ … }
4
© Xiaoying Gao, Peter Andreae COMP 102 14: 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)
5
© Xiaoying Gao, Peter Andreae COMP 102 14: 5 Assignment 4 Q1 Get the basic if else if else Guess 5 times Then other methods, test each method separately
6
© Xiaoying Gao, Peter Andreae COMP 102 14: 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; }
7
© Xiaoying Gao, Peter Andreae COMP 102 14: 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; }
8
© Xiaoying Gao, Peter Andreae COMP 102 14: 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
9
© Xiaoying Gao, Peter Andreae COMP 102 14: 9 Today’s topic File as Input, Output File class Scanner class PrintStream class
10
© Xiaoying Gao, Peter Andreae COMP 102 14: 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)
11
© Xiaoying Gao, Peter Andreae COMP 102 14: 11 Files: An overview My Program : int a =??.nextInt(); : ??.println(a*5); } My Program : int a =??.nextInt(); : ??.println(a*5); } Enter numbers: 40 60 30 50 done Enter numbers: 40 60 30 50 done UI Window UI.nextInt(); UI.println(); A real file: “myfile.txt” File object Scanner object Scanner object next(); println(); PrintStream object
12
© Xiaoying Gao, Peter Andreae COMP 102 14: 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);
13
© Xiaoying Gao, Peter Andreae COMP 102 14: 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”
14
© Xiaoying Gao, Peter Andreae COMP 102 14: 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
15
© Xiaoying Gao, Peter Andreae COMP 102 14: 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
16
© Xiaoying Gao, Peter Andreae COMP 102 14: 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
17
© Xiaoying Gao, Peter Andreae COMP 102 14: 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
18
© Xiaoying Gao, Peter Andreae COMP 102 14: 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);} }
19
© Xiaoying Gao, Peter Andreae COMP 102 14: 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; }
20
© Xiaoying Gao, Peter Andreae COMP 102 14: 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
21
© Xiaoying Gao, Peter Andreae COMP 102 14: 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
22
© Xiaoying Gao, Peter Andreae COMP 102 14: 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);
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.