/
Lecture 3:  Input/Output Lecture 3:  Input/Output

Lecture 3: Input/Output - PowerPoint Presentation

eloise
eloise . @eloise
Follow
65 views
Uploaded On 2023-11-04

Lecture 3: Input/Output - PPT Presentation

Dr Kyung Eun Park Summer 2017 Communicating with IO Devices Interactive Programming Interactive program Reads input from the console Writes output to the console Programming with a file ID: 1028498

file input java scanner input file scanner java system output console string change txt println data read program printstream

Share:

Link:

Embed:

Download Presentation from below link

Download Presentation The PPT/PDF document "Lecture 3: Input/Output" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.


Presentation Transcript

1. Lecture 3: Input/OutputDr. Kyung Eun ParkSummer 2017

2. Communicating with I/O Devices

3. Interactive ProgrammingInteractive program: Reads input from the console Writes output to the consoleProgramming with a fileReads input from a fileWrites output to a fileObject-oriented programming: Interactions between objectsConsole as an objectFile as an objectObjects from your program class

4. Standard InputStandard Input Object: System.inReads input from the consoleWhile 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 objectScanner tool An object that can read input from many sources (console, file, etc.)Process input data and handle it appropriately

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

6. Scanner methodsEach 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.MethodDescriptionnextInt()reads an int from the user (or data source) and returns itnextDouble()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 exampleimport java.util.*; // so that I can use Scannerpublic 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!29age29years36

8. Scanner example 2import java.util.*; // so that I can use Scannerpublic 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 6The product is 48The Scanner can read multiple values from one line.

9. Standard OutputStandard Output Object: System.outWrites output to the consoleWhile the program runs, it prints the output to the consoleSystem.out object Supports methodsprint()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 nameDescriptioncanRead()returns whether file is able to be readdelete()removes file from diskexists()whether this file exists on diskgetName()returns file's namelength()returns number of bytes in filerenameTo(file)changes name of file

11. Reading a File using Scanner ToolTo 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"));

12. File Paths Absolute path: specifies a drive or a top "/" folder C:/Documents/smith/hw6/input/data.csvWindows can also use backslashes to separate folders. Relative path: does not specify any top-level folder names.dat input/kinglear.txtAssumed 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 Filesimport java.io.*; // for Fileimport java.util.*; // for Scannerpublic 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 Scanner input = new Scanner(new File("data.txt")); ^

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

15. Exception HandlingIllegal operations generate exceptions.generated by the JVM or by constructors or other methodsAn exception is generated  the program will terminateWe 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 classesusing the try, catch, and finally blocks

16. The throws Clausethrows 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."

17. Using try and catch Blockstry/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 typeSyntax: try { statements; } catch (<type> <name>) { statements; }

18. Handling try and catch BlocksExample: 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 syntaxno need to use a throws clause on that method’s header

19. Input Tokenstoken: A unit of user input, separated by whitespace. A Scanner splits a file's contents into tokens.If an input file contains the following: 23 3.14 "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

20. Token Collection using Different MethodsInteger: nextInt()Real number: nextDouble()One Word (String): next()One Line (String): nextLine() 2929.0HiHi all!nextInt()nextDouble()next()nextLine()Integer typeDouble typeString typeString type

21. Files and Input CursorConsider a file weather.txt that contains this text:16.2 23.5 19.1 7.4 22.818.5 -1.8 14.9A Scanner views all input as a stream of characters:16.2 23.5\n19.1 7.4 22.8\n\n18.5 -1.8 14.9\n^input cursor: The current position of the Scanner.

22. Consuming tokensconsuming input: Reading input and advancing the cursor.Calling nextInt() etc. moves the cursor past the current token. 16.2 23.5\n19.1 7.4 22.8\n\n18.5 -1.8 14.9\n ^ double d = input.nextDouble(); // 16.2 16.2 23.5\n19.1 7.4 22.8\n\n18.5 -1.8 14.9\n ^ String s = input.next(); // "23.5" 16.2 23.5\n19.1 7.4 22.8\n\n18.5 -1.8 14.9\n ^ String s = input.nextLine(); // "“: null String 16.2 23.5\n19.1 7.4 22.8\n\n18.5 -1.8 14.9\n ^

23. File input questionRecall the input file weather.txt:16.2 23.5 19.1 7.4 22.818.5 -1.8 14.9Write a program that prints the change in temperature between each pair of neighboring days.16.2 to 23.5, change = 7.323.5 to 19.1, change = -4.419.1 to 7.4, change = -11.77.4 to 22.8, change = 15.422.8 to 18.5, change = -4.318.5 to -1.8, change = -20.3-1.8 to 14.9, change = 16.7

24. File Input Answer// Displays changes in temperature from data in an input file.import java.io.*; // for Fileimport java.util.*; // for Scannerpublic 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 fileSuppose 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.323.5 to 19.1, change = -4.4Exception 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 exceptionsNoSuchElementExceptionYou read past the end of the input.InputMismatchExceptionYou 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 inputThese 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.MethodDescriptionhasNext()returns true if there is a next tokenhasNextInt()returns true if there is a next tokenand it can be read as an inthasNextDouble()returns true if there is a next tokenand it can be read as a doublehasNextLine()returns true if there are any more lines of input to read (always true for console input)

28. Using hasNext() MethodsAvoiding 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 2Modify 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 Fileimport java.util.*; // for Scannerpublic 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 3Modify 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:16.2 23.5Tuesday 19.1 Wed 7.4 THURS. TEMP: 22.818.5 -1.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 Fileimport java.util.*; // for Scannerpublic 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 PrintStreamPrintStream 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 consoleout2.println("Hello, file!"); // goes to fileA 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 LinesUsing nextLine in conjunction with the token-based methods on the same Scanner can cause bad results. 23 3.14Joe "Hello" world 45.2 19You'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?

37. Mixing Tokens and LinesDon't read both tokens and lines from the same Scanner: 23 3.14Joe "Hello world" 45.2 19 input.nextInt() // 2323\t3.14\nJoe\t"Hello" world\n\t\t45.2 19\n ^ input.nextDouble() // 3.1423\t3.14\nJoe\t"Hello" world\n\t\t45.2 19\n ^ input.nextLine() // "" (empty!)23\t3.14\nJoe\t"Hello" world\n\t\t45.2 19\n ^ input.nextLine() // "Joe\t\"Hello\" world"23\t3.14\nJoe\t"Hello" world\n\t\t45.2 19\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? pHow many characters in a row? 7How many characters in a column? 4What character? kkkkkkkkk     kk     kkkkkkkkUser Interaction: prompt & readingPrinting output

39. Homework II – File Input/OutputWrite 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)TensorFlowisan……varietyofotherdomainsaswell./*** 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.https://www.tensorflow.org/