Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 3: Input/Output

Similar presentations


Presentation on theme: "Lecture 3: Input/Output"— Presentation transcript:

1 Lecture 3: Input/Output
Dr. Kyung Eun Park Summer 2017

2 Communicating with I/O Devices

3 Interactive Programming
Reads input from the console Writes output to the console Programming with a file Reads input from a file Writes output to a file Object-oriented programming: Interactions between objects Console as an object File as an object Objects from your program class

4 Standard Input Standard Input Object: System.in Tools to read input:
Reads input from the console While the program runs, it asks the user to type input. The input typed by the user is stored in variables in the code. Tools to read input: By referring to Scanner class (blue print), create a Scanner object Scanner tool An object that can read input from many sources (console, file, etc.) Process input data and handle it appropriately

5 Scanner Object The Scanner class is found in the java.util package.
import java.util.*; // so you can use Scanner Constructing a Scanner object to read console input: Scanner name = new Scanner(System.in); Example: Scanner console = new Scanner(System.in);

6 Scanner methods Each method waits until the user presses Enter.
The value typed by the user is returned. System.out.print("How old are you? "); // prompt int age = console.nextInt(); System.out.println("You typed " + age); prompt: A message telling the user what input to type. Method Description nextInt() reads an int from the user (or data source) and returns it nextDouble() reads a double from the user (or data source) next() reads a one-word String from the user (or data source) nextLine() reads a one-line (next entire line) String from the user (or data source): from cursor to next \n, consumes the \n

7 Scanner example Console (user input underlined): age 29 years 36 29
import java.util.*; // so that I can use Scanner public class UserInputExample { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print("How old are you? "); int age = console.nextInt(); int years = 65 - age; System.out.println(years + " years to retirement!"); } Console (user input underlined): How old are you? 36 years until retirement! age 29 years 36 It's also useful to write a program that prompts for multiple values, both on the same line or each on its own line. 29

8 Scanner example 2 Output (user input underlined):
import java.util.*; // so that I can use Scanner public class ScannerMultiply { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print("Please type two numbers: "); int num1 = console.nextInt(); int num2 = console.nextInt(); int product = num1 * num2; System.out.println("The product is " + product); } Output (user input underlined): Please type two numbers: 8 6 The product is 48 The Scanner can read multiple values from one line. It's also useful to write a program that prompts for multiple values, both on the same line or each on its own line.

9 Standard Output Standard Output Object: System.out System.out object
Writes output to the console While the program runs, it prints the output to the console System.out object Supports methods print() println() printf()

10 File Input/Output (I/O)
import java.io.*; Create a File object to get info about a file on your drive. (This doesn't actually create a new file on the hard disk.) File f = new File("example.txt"); if (f.exists() && f.length() > 1000) { f.delete(); } Method name Description canRead() returns whether file is able to be read delete() removes file from disk exists() whether this file exists on disk getName() returns file's name length() returns number of bytes in file renameTo(file) changes name of file

11 Reading a File using Scanner Tool
To read a file, pass a File object when constructing a Scanner tool Scanner name = new Scanner(new File("file name")); Example: File file = new File("mydata.txt"); Scanner input = new Scanner(file); or (shorter): Scanner input = new Scanner(new File("mydata.txt")); It is nice that Java uses the same object to read files as it does to read the keyboard. It's simpler and easier to learn. Some languages (C, Python, etc.) don't do this.

12 File Paths Absolute path: specifies a drive or a top "/" folder
C:/Documents/smith/hw6/input/data.csv Windows can also use backslashes to separate folders. Relative path: does not specify any top-level folder names.dat input/kinglear.txt Assumed to be relative to the current directory: Scanner input = new Scanner(new File("data/readme.txt")); If our program is in H:/hw6 , Scanner will look for H:/hw6/data/readme.txt

13 Compiler Error with Files
import java.io.*; // for File import java.util.*; // for Scanner public class ReadFile { public static void main(String[] args) { Scanner input = new Scanner(new File("data.txt")); String text = input.next(); System.out.println(text); } The program fails to compile with the following error: ReadFile.java:6: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown ^

14 Exceptions: Error Objects
exception: An object representing a runtime error. No compiler errors, but logic errors at run time. dividing an integer by 0 calling substring on a String and passing too large an index trying to read the wrong type of value from a Scanner trying to read a file that does not exist accessing the 11th element in a 10-element array Why? Java is a robust language and does not allow these “illegal” operations to occur unnoticed. Inform Java Virtual Machine (JVM) of the possibility of FileNotFoundException The IOException class and its subclass, FileNotFoundException are in the java.io package

15 Exception Handling Illegal operations generate exceptions.
generated by the JVM or by constructors or other methods An exception is generated  the program will terminate We say that a program with an error "throws" an exception. It is possible to "catch" (handle or fix) an exception. What if we want to continue running the program after recovering from the exception? using exception classes using the try, catch, and finally blocks

16 The throws Clause throws clause: Keywords on a method's header that state that it may generate an exception (and will not handle it). Syntax: public static type name(params) throws type { Example: public class ReadFile { public static void main(String[] args) throws FileNotFoundException { meaning that the main() method may detect a situation for which it will generate an FileNotFoundException. Like saying, "I hereby announce that this method might throw an exception, and I accept the consequences if this happens." analogy: A throws clause is like the legal waiver you sign before you go bungee jumping. "I understand that I am taking a risk, and I promise not to sue!"

17 Using try and catch Blocks
try/catch block: “tries” to execute a given block of code. . “catch block” of code that should be executed if any code in the “try block” generates an exception of a particular type Syntax: try { statements; } catch (<type> <name>) { } analogy: A throws clause is like the legal waiver you sign before you go bungee jumping. "I understand that I am taking a risk, and I promise not to sue!"

18 Handling try and catch Blocks
Example: try { Scanner input = new Scanner(new File(“input.txt”)); } catch (FileNotFoundException e) { System.out.println(“Error reading file: ” + e); } If you wrap all potentially unsafe operations in a method with the try/catch syntax no need to use a throws clause on that method’s header

19 Input Tokens token: A unit of user input, separated by whitespace.
A Scanner splits a file's contents into tokens. If an input file contains the following: "John Smith" The Scanner can interpret the tokens as the following types: Token Type(s) 23 int, double, String 3.14 double, String "John String Smith" String Even though we think of 23 as being an int, it can be any of the three types: 23, 23.0, or "23".

20 Token Collection using Different Methods
Integer: nextInt() Real number: nextDouble() One Word (String): next() One Line (String): nextLine() nextInt() 29 Integer type nextDouble() 29.0 Double type next() Hi String type nextLine() Hi all! String type

21 Files and Input Cursor Consider a file weather.txt that contains this text: A Scanner views all input as a stream of characters: \n \n\n \n ^ input cursor: The current position of the Scanner.

22 Consuming tokens consuming input: Reading input and advancing the cursor. Calling nextInt() etc. moves the cursor past the current token. \n \n\n \n ^ double d = input.nextDouble(); // 16.2 String s = input.next(); // "23.5" String s = input.nextLine(); // "“: null String

23 File input question Recall the input file weather.txt:
Write a program that prints the change in temperature between each pair of neighboring days. 16.2 to 23.5, change = 7.3 23.5 to 19.1, change = -4.4 19.1 to 7.4, change = -11.7 7.4 to 22.8, change = 15.4 22.8 to 18.5, change = -4.3 18.5 to -1.8, change = -20.3 -1.8 to 14.9, change = 16.7 8 temperatures in the file, but 7 lines of output. It's a fencepost problem in disguise.

24 File Input Answer // Displays changes in temperature from data in an input file. import java.io.*; // for File import java.util.*; // for Scanner public class Temperatures { public static void main(String[] args) throws FileNotFoundException { Scanner input = new Scanner(new File("weather.txt")); double prev = input.nextDouble(); // fencepost: loop and a half for (int i = 1; i <= 7; i++) { double next = input.nextDouble(); System.out.println(prev + " to " + next + ", change = " + (next - prev)); prev = next; }

25 Reading an entire file Suppose we want our program to work no matter how many numbers are in the file. Currently, if the file has more numbers, they will not be read. If the file has fewer numbers, what will happen? A crash! Example output from a file with just 3 numbers: 16.2 to 23.5, change = 7.3 23.5 to 19.1, change = -4.4 Exception in thread "main" java.util.NoSuchElementException at java.util.Scanner.throwFor(Scanner.java:838) at java.util.Scanner.next(Scanner.java:1347) at Temperatures.main(Temperatures.java:12)

26 Scanner exceptions NoSuchElementException InputMismatchException
You read past the end of the input. InputMismatchException You read the wrong type of token (e.g. read "hi" as an int). Finding and fixing these exceptions: Read the exception text for line numbers in your code (the first line that mentions your file; often near the bottom): Exception in thread "main" java.util.NoSuchElementException at java.util.Scanner.throwFor(Scanner.java:838) at java.util.Scanner.next(Scanner.java:1347) at MyProgram.myMethodName(MyProgram.java:19) at MyProgram.main(MyProgram.java:6)

27 Scanner tests for valid input
Method Description hasNext() returns true if there is a next token hasNextInt() returns true if there is a next token and it can be read as an int hasNextDouble() returns true if there is a next token and it can be read as a double hasNextLine() returns true if there are any more lines of input to read (always true for console input) These methods of the Scanner do not consume input, they just give information about what the next token will be. Useful to see what input is coming, and to avoid crashes. These methods can be used with a console Scanner, as well. When called on the console, they sometimes pause waiting for input. Don't spend much time talking about using these methods on a console Scanner. We don't need that right now and it may confuse students.

28 Using hasNext() Methods
Avoiding type mismatches: Scanner console = new Scanner(System.in); System.out.print("How old are you? "); if (console.hasNextInt()) { int age = console.nextInt(); // will not crash! System.out.println("Wow, " + age + " is old!"); } else { System.out.println("You didn't type an integer."); } Avoiding reading past the end of a file: Scanner input = new Scanner(new File("example.txt")); if (input.hasNext()) { String token = input.next(); // will not crash! System.out.println("next token is " + token);

29 File Input Question 2 Modify the temperature program to process the entire file, regardless of how many numbers it contains. Example: If a ninth day's data is added, output might be: 16.2 to 23.5, change = 7.3 23.5 to 19.1, change = -4.4 19.1 to 7.4, change = -11.7 7.4 to 22.8, change = 15.4 22.8 to 18.5, change = -4.3 18.5 to -1.8, change = -20.3 -1.8 to 14.9, change = 16.7 14.9 to 16.1, change = 1.2

30 File Input Answer 2 // Displays changes in temperature from data in an input file. import java.io.*; // for File import java.util.*; // for Scanner public class Temperatures { public static void main(String[] args) throws FileNotFoundException { Scanner input = new Scanner(new File("weather.txt")); double prev = input.nextDouble(); // fencepost while (input.hasNextDouble()) { double next = input.nextDouble(); System.out.println(prev + " to " + next + ", change = " + (next - prev)); prev = next; }

31 File input question 3 Modify the temperature program to handle files that contain non- numeric tokens (by skipping them). For example, it should produce the same output as before when given this input file, weather2.txt: Tuesday Wed THURS. TEMP: 22.8 <-- Marty here is my data! --Kim 14.9 :-) You may assume that the file begins with a real number.

32 File Input Answer 3 // Displays changes in temperature from data in an input file. import java.io.*; // for File import java.util.*; // for Scanner public class Temperatures2 { public static void main(String[] args) throws FileNotFoundException { Scanner input = new Scanner(new File("weather.txt")); double prev = input.nextDouble(); // fencepost while (input.hasNext()) { if (input.hasNextDouble()) { double next = input.nextDouble(); System.out.println(prev + " to " + next + ", change = " + (next - prev)); prev = next; } else { input.next(); // throw away unwanted token }

33 File Output 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.");

34 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).

35 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 to a method as a PrintStream. Allows a method to send output to the console or a file.

36 Mixing Tokens and Lines
Using nextLine in conjunction with the token-based methods on the same Scanner can cause bad results. Joe "Hello" world You'd think you could read 23 and 3.14 with nextInt and nextDouble, then read Joe "Hello" world with nextLine . System.out.println(input.nextInt()); // 23 System.out.println(input.nextDouble()); // 3.14 System.out.println(input.nextLine()); // But the nextLine call produces no output! Why? I don't intend to reach this in lecture; it's just extra information.

37 Mixing Tokens and Lines
Don't read both tokens and lines from the same Scanner: Joe "Hello world" input.nextInt() // \t3.14\nJoe\t"Hello" world\n\t\t \n ^ input.nextDouble() // \t3.14\nJoe\t"Hello" world\n\t\t \n ^ input.nextLine() // "" (empty!) 23\t3.14\nJoe\t"Hello" world\n\t\t \n ^ input.nextLine() // "Joe\t\"Hello\" world" 23\t3.14\nJoe\t"Hello" world\n\t\t \n ^

38 Homework I – Standard Input/Output
Write a program which (1) generates the following sequence, (2) reads user input, (3) validates the input, and (4) prints the output as follows: Program sequence: How many characters in a row? p How many characters in a row? 7 How many characters in a column? 4 What character? k kkkkkkk k     k User Interaction: prompt & reading Printing output

39 Homework II – File Input/Output
Write a program which counts the number of words in the given text file, words.txt and writes the answer into both console and an output file, count.txt. Given data (words.txt) Output (count.txt) TensorFlow is an variety of other domains as well. /*** The input file contains total 110 words. ***/ TensorFlow is an open source software library for numerical computation using data flow graphs. Nodes in the graph represent mathematical operations, while the graph edges represent the multidimensional data arrays (tensors) communicated between them. The flexible architecture allows you to deploy computation to one or more CPUs or GPUs in a desktop, server, or mobile device with a single API. TensorFlow was originally developed by researchers and engineers working on the Google Brain Team within Google's Machine Intelligence research organization for the purposes of conducting machine learning and deep neural networks research, but the system is general enough to be applicable in a wide variety of other domains as well.


Download ppt "Lecture 3: Input/Output"

Similar presentations


Ads by Google