Download presentation
Presentation is loading. Please wait.
Published byCory Ferguson Modified over 9 years ago
1
2011-T1 Lecture 12 School of Engineering and Computer Science, Victoria University of Wellington Rashina Hoda and Peter Andreae COMP 102 Rashina Hoda Nested Loops and Files
2
2 RECAP-TODAY RECAP while loops TODAY Nested loops Next methods, Files Administrivia: Test results: available soon – hopefully this week Assignment#2 mark sheets should be available online
3
3 public void drawCircles(int rows, int cols) { int diam = 20; int row = 0; int col = 0; while (row < rows){ col = 0; while ( col < cols ) { int x = col*diam; int y = row*diam; canvas.fillOval(x, y, diam, diam); col++; } row++; } Nested loops
4
4 Some next methods MethodWhat it doesReturns next()Read and return next token of user’s inputString hasNext()Returns true if there is another token in the user input. Waits for the user to type something if necessary. boolean nextInt()Read the next token of the user's input Return it as a integer if it is a number. Throws an exception if it is not a number. int hasNextInt()Returns true if the next token in the user input is an integer. Waits for the user to type something if necessary. boolean nextBoolean()Read the next token of the user's input. Return true if it is "yes", "y", or "true", return false if it is "no", "n", or "false" (case insensitive). Throws an exception if it is anything else. boolean nextLine()Read the remaining characters of the user's input up to (but not including) the next end-of-line and return them as a string. Reads and throws away the end-of-line character. If there are no characters on the line, then it returns an empty string (""). String
5
5 next vs. nextLine() next(), nextInt(), nextDouble() next() picks up any spaces, discards them, and picks up next value (till it reaches a space), then returns the value as a String (nextInt returns it as an int, nextDouble returns it as a double.) nextLine() Picks up all the values (including spaces) till it reaches end-of-line character, throws away end-of-line, and returns all the values (including spaces) as a String. User enters: 40 60 20 done Using next(), the tokens are: “40”, “60”, “20”, “done” Using nextInt(), the tokens are: 40, 60, 20 Using nextDouble(), the tokens are: 40.0, 60.0, 20.0 Using nextLine() would return: “40 60 20 done”
6
6 next methods...how they work /** sum up all numbers entered by user */ : UI.print(“Enter numbers: end with ‘done’:”); double sum = 0; while (UI.hasNextDouble() ) {//peeking at next value or “token” double amt = UI.nextDouble(); //getting the next value and move pointer sum = sum + amt; } UI.printf(“Total of all numbers entered: %.2f”, sum); : Enter numbers: end with ‘done’: 40 60 30 50 done Enter numbers: end with ‘done’: 40 60 30 50 done * MENU *
7
7 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 input and output 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)
8
8 Files: An overview My Program : int a =.nextInt(); : } My Program : int a =.nextInt(); : } 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) next(); println(); PrintStream (object)
9
9 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.hasNextInt()){ double amt = UI.next() } 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.next(); } Scanner scan = new Scanner(myfile);
10
10 Reading using Scanner: /** Read names from a file and print them to UI text pane. */ public void readFile(){ File myfile = new File(“input.txt”); Scanner scan = new Scanner(myfile); while (scan.hasNext()){ String name = scan.nextLine(); UI.println(name); } UI.println(“Read and printed all names”); } Almost right, but compiler complains!!! Dealing with files may “raise exceptions”
11
11 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
12
12 Reading from files: example 2 Scanner "wraps up" the file. No need to prompt: (but need try…catch…) /** Finds oldest person in list 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 prompt! 33 James Bond 25 Helen Clerk 73 John F Quay 19 pondy
13
13 Testing end of file Unlike UI text pane, can test for end of file: /** Finds oldest person in list 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!! name first; age second Note: name must be just one token!! James 33 Helen 25 John 73 pondy 19
14
14 Passing an open scanner 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; }
15
15 Writing to a File Open a File Wrap it in a new PrintStream 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; } output.close() : File Object
16
16 Checking 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()) { outfile.println((num++) + “: ” + sc.nextLine() ); } out.close(); sc.close(); } catch (IOException e) {UI.printf(“File failure %s\n”, e);} }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.