Copyright 2008 by Pearson Education Building Java Programs Chapter 7 Lecture 7-3: File Output; Reference Semantics reading: 6.4-6.5, 7.1, 4.3, 3.3 self-checks:

Slides:



Advertisements
Similar presentations
Copyright 2010 by Pearson Education Building Java Programs Chapter 7 Lecture 7-2: Arrays as Parameters reading: , 3.3 self-checks: Ch. 7 #5, 8,
Advertisements

1 Various Methods of Populating Arrays Randomly generated integers.
BUILDING JAVA PROGRAMS CHAPTER 6.4 FILE OUTPUT. 22 PrintStream : An object in the java.io package that lets you print output to a destination such as.
Copyright 2008 by Pearson Education Building Java Programs Chapter 6 Lecture 6-1: File Input with Scanner reading: , 5.3 self-check: Ch. 6 #1-6.
1 CSE 142 Lecture Notes File input using Scanner Suggested reading: , Suggested self-checks: Section 6.7 # 1-11, These lecture.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 7: Arrays.
Copyright 2008 by Pearson Education Building Java Programs Chapter 7 Lecture 7-2: Tallying and Traversing Arrays reading: 7.1 self-checks: #1-9 videos:
Copyright 2008 by Pearson Education Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: self-check: #16-19.
Copyright 2008 by Pearson Education Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: self-check: #16-19.
Copyright 2008 by Pearson Education Building Java Programs Chapter 7 Lecture 27: More on ArrayList, Reference Semantics Command Line Arguments reading:
Copyright 2010 by Pearson Education Building Java Programs Chapter 7 Lecture 7-3: Arrays for Tallying; Text Processing reading: 4.3, 7.6.
1 Reference semantics. 2 A swap method? Does the following swap method work? Why or why not? public static void main(String[] args) { int a = 7; int b.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapters 3-4: Using Objects.
Copyright 2010 by Pearson Education Building Java Programs Chapter 6 Lecture 6-2: Line-Based File Input reading:
1 Hours question Given a file hours.txt with the following contents: 123 Kim Eric Stef
Building java programs chapter 6
1 BUILDING JAVA PROGRAMS CHAPTER 7 LECTURE 7-3: ARRAYS AS PARAMETERS; FILE OUTPUT.
Topic 19 file input, line based Copyright Pearson Education, 2010 Based on slides bu Marty Stepp and Stuart Reges from
Topic 22 arrays - part 2 Copyright Pearson Education, 2010 Based on slides bu Marty Stepp and Stuart Reges from
Advanced File Processing NOVEMBER 21 ST, Objectives Write text output to a file. Ensure that a file can be read before reading it in your program.
Copyright 2008 by Pearson Education Building Java Programs Chapter 7 Lecture 7-3: Arrays as Parameters; File Output reading: 7.1, 4.3, 3.3 self-checks:
Building Java Programs Chapter 7 Lecture 7-3: Arrays for Tallying; Text Processing reading: 7.6, 4.3.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 7: Arrays.
Copyright 2010 by Pearson Education Building Java Programs Chapter 7 Lecture 7-3: Arrays for Tallying; Text Processing reading: 7.1, 4.4 self-checks: #1-9.
Copyright 2010 by Pearson Education Building Java Programs Chapter 7 Lecture 7-2: Arrays as Parameters reading:
FILE PROCESSING. Reading files To read a file, pass a File when constructing a Scanner. Scanner name = new Scanner(new File(" file name ")); Example:
Building Java Programs Chapter 6 Lecture 6-2: Line-Based File Input reading:
File Processing Copyright Pearson Education, 2010 Based on slides bu Marty Stepp and Stuart Reges from "We can only.
Copyright 2010 by Pearson Education Building Java Programs Chapter 7 Lecture 17: Arrays for Tallying; Text Processing reading: 4.3, 7.6 (Slides adapted.
1 Line-based file processing suggested reading:6.3.
File Input & Output Sections Outcomes  Know the difference between files and streams  Use a Scanner to read from a file  add “throws” annotations.
Copyright 2008 by Pearson Education Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: self-check: #16-19.
Copyright 2008 by Pearson Education Building Java Programs Chapter 7 Lecture 7-3: Arrays as Parameters; File Output reading: 7.1, 4.3, 3.3 self-checks:
CS1020 Data Structures and Algorithms I Lecture Note #16 File Processing.
Building Java Programs Chapter 6 File Processing Copyright (c) Pearson All rights reserved.
Building Java Programs
Building Java Programs
Hours question Given a file hours.txt with the following contents:
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs Chapter 7
Building Java Programs
Building Java Programs Chapter 6
Topic 22 arrays - part 2 Copyright Pearson Education, 2010 Based on slides by Marty Stepp and Stuart Reges from
Lecture 7-3: Arrays for Tallying; Text Processing
CIS 110: Introduction to Computer Programming
Building Java Programs
Building Java Programs
Building Java Programs
Why did the programmer quit his job?
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Hours question Given a file hours.txt with the following contents:
Building Java Programs
Building Java Programs
Building Java Programs
Topic 19 file input, line based
Building Java Programs
Building Java Programs
Building Java Programs
File output; Arrays reading: 6.4 – 6.5, 7.1
Building Java Programs
Building Java Programs
Building Java Programs
A counting problem Problem: Write a method mostFrequentDigit that returns the digit value that occurs most frequently in a number. Example: The number.
Building Java Programs
Building Java Programs
Presentation transcript:

Copyright 2008 by Pearson Education Building Java Programs Chapter 7 Lecture 7-3: File Output; Reference Semantics reading: , 7.1, 4.3, 3.3 self-checks: Ch. 7 #19-23 exercises: Ch. 7 #5

Copyright 2008 by Pearson Education 2 Two separate topics File output A lot like printing to the console Pretty easy; needed for homework 7 References Most difficult topic in the whole course Arrays (and next week objects) don’t “work” how you probably think they do! May or may not come up in your homework 7 solution

Copyright 2008 by Pearson Education 3 Output to files PrintStream : An object in the java.io package that lets you print output to a destination such as a file. Any methods you have used on System.out (such as print, println ) will work on a PrintStream. Syntax: PrintStream name = new PrintStream(new File(" file name ")); Example: PrintStream output = new PrintStream(new File("out.txt")); output.println("Hello, file!"); output.println("This is a second line of output.");

Copyright 2008 by Pearson Education 4 Details about PrintStream PrintStream name = new PrintStream(new File(" file name ")); If the given file does not exist, it is created. If the given file already exists, it is overwritten. The output you print appears in a file, not on the console. You will have to open the file with an editor to see it. Do not open the same file for both reading ( Scanner ) and writing ( PrintStream ) at the same time. You will overwrite your input file with an empty file (0 bytes).

Copyright 2008 by Pearson Education 5 System.out and PrintStream The console output object, System.out, is a PrintStream. PrintStream out1 = System.out; PrintStream out2 = new PrintStream(new File("data.txt")); out1.println("Hello, console!"); // goes to console out2.println("Hello, file!"); // goes to file A reference to it can be stored in a PrintStream variable. Printing to that variable causes console output to appear. You can pass System.out as a parameter to a method expecting a PrintStream. Allows methods that can send output to the console or a file.

Copyright 2008 by Pearson Education 6 PrintStream question Modify our previous Sections program from last lecture to use a PrintStream to output to the file sections_out.txt. Section #1: Sections attended: [9, 6, 7, 4, 3] Student scores: [20, 18, 20, 12, 9] Student grades: [100.0, 90.0, 100.0, 60.0, 45.0] Section #2: Sections attended: [6, 7, 5, 6, 4] Student scores: [18, 20, 15, 18, 12] Student grades: [90.0, 100.0, 75.0, 90.0, 60.0] Section #3: Sections attended: [5, 6, 5, 7, 6] Student scores: [15, 18, 15, 20, 18] Student grades: [75.0, 90.0, 75.0, 100.0, 90.0]

Copyright 2008 by Pearson Education 7 PrintStream answer // Section attendance program // This version uses a PrintStream for output. import java.io.*; import java.util.*; public class Sections { public static void main(String[] args) throws FileNotFoundException { Scanner input = new Scanner(new File("sections.txt")); PrintStream out = new PrintStream(new File("sections_out.txt")); while (input.hasNextLine()) { // process one section String line = input.nextLine(); int[] attended = countAttended(line); int[] points = computePoints(attended); double[] grades = computeGrades(points); results(attended, points, grades, out); } // Produces all output about a particular section. public static void results(int[] attended, int[] points, double[] grades, PrintStream out) { out.println("Sections attended: " + Arrays.toString(attended)); out.println("Sections scores: " + Arrays.toString(points)); out.println("Sections grades: " + Arrays.toString(grades)); out.println(); }...

Copyright 2008 by Pearson Education 8 Prompting for a file name We can ask the user to tell us the file to read. The file name might have spaces; use nextLine(), not next() // prompt for input file name Scanner console = new Scanner(System.in); System.out.print("Type a file name to use: "); String filename = console.nextLine(); Scanner input = new Scanner(new File(filename)); What if the user types a file name that does not exist?

Copyright 2008 by Pearson Education 9 Fixing file-not-found issues File objects have an exists method we can use: Scanner console = new Scanner(System.in); System.out.print("Type a file name to use: "); String filename = console.nextLine(); File file = new File(filename); if (!file.exists()) { // try a second time System.out.print("Try again: "); String filename = console.nextLine(); file = new File(filename); } Scanner input = new Scanner(file); // open the file Output: Type a file name to use: hourz.text Try again: hours.txt

Copyright 2008 by Pearson Education 10 Arrays as parameters and returns; values vs. references reading: 7.1, 3.3, 4.3 self-checks: Ch. 7 #5, 8, 9 exercises: Ch. 7 #1-10

Copyright 2008 by Pearson Education 11 Swapping values public static void main(String[] args) { int a = 42; int b = 64; // swap a with b (incorrectly) a = b; b = a; System.out.println(a + " " + b); } What is wrong with this code? What is its output? The red code should be replaced with: int temp = a; a = b; b = temp;

Copyright 2008 by Pearson Education 12 A swap method? Does the following swap method work? Why or why not? public static void main(String[] args) { int a = 42; int b = 64; // swap a with b swap(a, b); System.out.println(a + " " + b); } public static void swap(int a, int b) { int temp = a; a = b; b = temp; }

Copyright 2008 by Pearson Education 13 Value semantics Java parameters are initialized by copying the value The parameter is a different variable Assigning to a parameter variable has no effect on callers So there is no way to write a swap method for two int s We learned all this back when we learned parameters (although we didn’t carefully discuss all the consequences at that time, to avoid overwhelming you with lots of information all at once)

Copyright 2008 by Pearson Education 14 Mini-exercise What does this print? public static void main(String[] args) { int j = 10; squid(j); System.out.println(”in main - j = " + j); } public static void squid(int k) { System.out.println("starting squid - k = " + k); k = 20; System.out.println(”leaving squid - k = " + k); }

Copyright 2008 by Pearson Education 15 Mini-exercise - answer public static void main(String[] args) { int j = 10; squid(j); System.out.println(”in main - j = " + j); } public static void squid(int k) { System.out.println("starting squid - k = " + k); k = 20; System.out.println(”leaving squid - k = " + k); } Output: starting squid - k = 10 leaving squid - k = 20 in main - j = 10

Copyright 2008 by Pearson Education 16 Something different public static void main(String[] args) { int[] a = new int[2]; a[0] = 42; a[1] = 64; swap(a); System.out.println(a[0] + " " + a[1]); } public static void swap(int[] arr) { int temp = arr[0]; arr[0] = arr[1]; arr[1] = arr[0]; } Prints – this swap “works” The question is why

Copyright 2008 by Pearson Education 17 This doesn’t work public static void main(String[] args) { int[] a = new int[2]; a[0] = 42; a[1] = 64; swap(a); System.out.println(a[0] + " " + a[1]); } public static void swap(int[] arr) { int[] x = new int[2]; x[0] = arr[1]; x[1] = arr[0]; arr = x; } Prints 42 64

Copyright 2008 by Pearson Education 18 An analogy you know 1. Dan sends Alan an attaching the file funPic.jpg. The file has a picture in it. 2. Alan gets the and saves the file. 3. Then Alan changes his copy of funPic.jpg to have a different picture in it. Is Dan’s file changed? No. This is how parameters work: Dan’s file is like a variable in the caller Alan’s file is like a variable in the method called Changing the file’s contents is like assigning to a variable Variables are like files in the analogy

Copyright 2008 by Pearson Education 19 A slightly different analogy 1. Dan sends Alan an attaching a file that contains the URL 2. Alan gets the and saves the file. 3. Then Alan follows the link and uses it to change an online photo. When Dan follows the link, does he see the new photo? Yes. This is how arrays work: A file with a link in it is like a variable containing a reference to an array Updating an array affects all variables that refer to that array Array variables are like files holding URLs in the analogy

Copyright 2008 by Pearson Education 20 The truth about new new doesn’t actually return an array (or an object) It returns a “URL” for a new array (or a new object) We call them “references” (or “addresses” or “pointers”) A variable never “holds” an array (or an object) It always holds a reference to an array (or an object) So when we copy the reference (think URL), there are now two references to the same array a[i] = 42; follows the reference and updates the array So any other references to the same array see the change

Copyright 2008 by Pearson Education 21 That explains everything public static void main(String[] args) { int[] a = new int[2]; a[0] = 42; a[1] = 64; swap(a); System.out.println(a[0] + " " + a[1]); } public static void swap(int[] arr) { int temp = arr[0]; arr[0] = arr[1]; arr[1] = arr[0]; } 0 1 a arr

Copyright 2008 by Pearson Education 22 Arrows Of course, there aren’t really “arrows” inside the computer The array is at some “address” (think URL) and a variable referring to the array holds the “address” You don’t care what the address is; it isn’t meaningful You do care if two array variables hold the same address This is why printing an array variable doesn’t work print and println show the address public static void main(String[] args) { int[] arr = {42, 64}; System.out.println("array is at address: " + arr); }

Copyright 2008 by Pearson Education 23 Our wrong example public static void swap(int[] arr) { // WRONG int[] x = new int[2]; x[0] = arr[1]; x[1] = arr[0]; arr = x; } 1. arr refers to some array at some address #1 2. x refers to some new array at some address #2 3. we initialize the contents of the new array 4. we change arr to refer to the new array but this has no effect on the caller

Copyright 2008 by Pearson Education 24 A non-parameter example int[] a1 = {4, 5, 2, 12, 14, 14, 9}; int[] a2 = a1; // refer to same array as a1 a2[0] = 7; System.out.println(a1[0]); // 7 index value index value a1 a2

Copyright 2008 by Pearson Education 25 Mini-exercise What does this print? public static void main(String[] args) { int[] xs = new int[10]; int[] ys = xs; xs[3] = 10; ys[4] = 20; System.out.println(ys[3] + ys[4]); }

Copyright 2008 by Pearson Education 26 Mini-exercise - answer public static void main(String[] args) { int[] xs = new int[10]; int[] ys = xs; xs[3] = 10; ys[4] = 20; System.out.println(ys[3] + ys[4]); } Output: 30

Copyright 2008 by Pearson Education 27 Mini-exercise #2 What does this print? public static void main(String[] args) { int[] xs = new int[10]; int[] ys = xs; int[] zs = new int[10]; xs[0] = 100; ys[0] = 50; zs[0] = 20; System.out.println(xs[0]); System.out.println(ys[0]); System.out.println(zs[0]); }

Copyright 2008 by Pearson Education 28 Mini-exercise #2 - answer public static void main(String[] args) { int[] xs = new int[10]; int[] ys = xs; int[] zs = new int[10]; xs[0] = 100; ys[0] = 50; zs[0] = 20; System.out.println(xs[0]); System.out.println(ys[0]); System.out.println(zs[0]); } Output:

Copyright 2008 by Pearson Education 29 A useful parameter example public static void main(String[] args) { int[] iq = {126, 167, 95}; doubleAll(iq); System.out.println(Arrays.toString(iq)); } public static void doubleAll(int[] a) { for (int i = 0; i < a.length; i++) { a[i] = a[i] * 2; } } Output: [252, 334, 190] index012 value index012 value iq a