1 User Input Create a Scanner object: Scanner inx = new Scanner(System.in); System.out.println("Type a number"); int x = inx.nextInt(); System.out.println("The.

Slides:



Advertisements
Similar presentations
Mr. Wortzman.  So far, we have gotten all our input and written all our output to the console  In reality, this is somewhat uncommon  Instead, we often.
Advertisements

Exceptions & exception handling Use sparingly. Things you can do with exceptions: 1. Define a new exception class. 2. Create an exception instance. 3.
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
CS102--Object Oriented Programming
Java I/O Java I/O is based on input streams and output streams. All input and output are defined in the Java IO package. 1.
More Java Syntax. Scanner class Revisited The Scanner class is a class in java.util, which allows the user to read values of various types. There are.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Today’s topics: I/O (Input/Output). Scribbler Inputs & Outputs  What are the Scribbler’s inputs and outputs?  reset button  motors/wheel  light sensor.
Text File I/O. Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with an editor are called.
The Print Formatting Statement … named printf. 2 Introduction to printf statements print and println statements don’t allow us to easily format output.
File I/O and Exceptions File I/O Exceptions Throwing Exceptions Try statement and catch / finally clauses Checked and unchecked exceptions Throws clause.
FIT FIT1002 Computer Programming Unit 19 File I/O and Exceptions.
11-Jun-15 Exceptions. 2 Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a.
Exception Handling. Lecture Objectives To learn how to throw exceptions To be able to design your own exception classes To understand the difference between.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Files and Streams CS 21a Chapter 11 of Horstmann.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
COMP 14 Introduction to Programming Miguel A. Otaduy May 17, 2004.
COMP 14 Introduction to Programming Mr. Joshua Stough February 2, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 29, 2005.
18 File handling1June File handling CE : Fundamental Programming Techniques.
26-Jun-15 Simple Text I/O. java.util.Scanner Java finally has a fairly simple way to read input First, you must create a Scanner object To read from the.
Strings as objects Strings are objects. Each String is an instance of the class String They can be constructed thus: String s = new String("Hi mom!");
© 2006 Pearson Addison-Wesley. All rights reserved2-1 Console Input Using the Scanner Class Starting with version 5.0, Java includes a class for doing.
Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 1 Files.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
1 Scanning Tokens. 2 Tokens When a Scanner reads input, it separates it into “tokens”  … at least when using methods like nextInt()  nextInt() takes.
Using java’s Scanner class To read from input and from a file. (horstmann ch04 and ch 17)
Introduction to Computer Programming Error Handling.
Streams and File I/O Chapter 14. I/O Overview I/O = Input/Output In this context it is input to and output from programs Input can be from keyboard or.
Conditional If Week 3. Lecture outcomes Boolean operators – == (equal ) – OR (||) – AND (&&) If statements User input vs command line arguments.
Methods (Functions) CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Chapter 2 Console Input and Output Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Console Input & Output CSS 161: Fundamentals of Computing Joe McCarthy 1.
Sahar Mosleh California State University San MarcosPage 1 System.out.println for console output System.out is an object that is part of the Java language.
Chapter 2 Console Input and Output Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
Chapter 10 Exceptions. Chapter Scope The purpose of exceptions Exception messages The call stack trace The try-catch statement Exception propagation The.
Java I/O Java I/O is based on input streams and output streams. All input and output are defined in the Java IO package. 1.
1 Recitation 8. 2 Outline Goals of this recitation: 1.Learn about loading files 2.Learn about command line arguments 3.Review of Exceptions.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
CMSC 202 Java Console I/O. July 25, Introduction Displaying text to the user and allowing the user to enter text are fundamental operations performed.
Odds and Ends. CS 21a 09/18/05 L14: Odds & Ends Slide 2 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights.
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
CHAPTER 5 GC 101 Input & Output 1. INTERACTIVE PROGRAMS  We have written programs that print console output, but it is also possible to read input from.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
Using the while-statement to process data files. General procedure to access a data file General procedure in computer programming to read data from a.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
Slides prepared by Rose Williams, Binghamton University Console Input and Output.
COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded.
Input and Output The system console. In the beginning … When computers were relatively expensive and rare, most users interacted with a terminal –CRT.
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
Lab 04-2 Objectives:  Understand what a file is.  Learn how to use the File class  Learn how to use the Scanner class to read from files  Learn about.
File Input & Output Sections Outcomes  Know the difference between files and streams  Use a Scanner to read from a file  add “throws” annotations.
1 Text File Input and Output. Objectives You will be able to Write text files from your Java programs. Read text files in your Java programs. 2.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Introduction to programming in java
Introduction to programming in java
Input/Output.
Streams and File I/O.
User Input You’ve seen this: A Scanner object:
Streams and File I/O Chapter 14.
CSS 161 Fundamentals of Computing Introduction to Computers & Java
Introduction to Classes and Methods
មជ្ឈមណ្ឌលកូរ៉េ សហ្វវែរ អេច អ ឌី
Exceptions 10-May-19.
Basic Exception Handling
Presentation transcript:

1 User Input Create a Scanner object: Scanner inx = new Scanner(System.in); System.out.println("Type a number"); int x = inx.nextInt(); System.out.println("The num you typed is " + x); Requires an import statement: You can just click and eclipse will add this for you: import java.util.Scanner;

Scanner class The Scanner class is a class in java.util that allows us to read values of various types We can read input from either the keyboard (as we saw) or from a file (to be seen) When reading from the keyboard, we need the parameter to be System.in We’ve been using System.out- writes to the console. System.in reads from the console (little window below the programming window in Eclipse) Like standard input (stdin) in c++

What the Scanner reads: The Scanner looks for tokens in the input. A token is a series of characters that ends with whitespace. a blank, a tab, a carriage return, or the end of the file. Methods for reading tokens:.nextInt().nextDouble().nextFloat().next() // next String.nextLine() And then there’s.close() MORE TO COME!

Example: Scanner in = new Scanner(System.in); System.out.println("Enter an int, a float, a double and a string."); System.out.println("Separate each with a blank or return."); int x1 = in.nextInt(); float f1 = in.nextFloat(); double d1 = in.nextDouble(); String s1 = in.nextLine(); System.out.println("Now enter another value."); String s2 = in.next(); System.out.println("Here is what you entered: "); System.out.println(x1 + " " + f1 + " " + d1 + " " + s1 + " and " + s2); in.close(); Enter an int, a float, a double and a string. Separate each with a blank or return hi there how are you Now enter another value. no Here is what you entered: hi there how are you and no

Processing Files File class contains a reference to an actual file location on your machine Special classes can read/write data to the file Scanner can actually read a file just like console input But we have to make a File object from the file class first: File myFile = new File(“myFile.txt”); //myFile.txt is the name of the file on your computer. Scanner in = new Scanner(myFile); if myFile.exists() //.exists is a method that checks to see if the myFile object was successfully created. (Why wouldn’t it have been?) What must it return? You can now use in to read from myFile.txt just like you read from the keyboard: int x1 = in.nextInt(); float f1 = in.nextFloat(); double d1 = in.nextDouble(); String s1 = in.nextLine(); String s2 = in.next();

Scanning in a file: Now we may want to use a few other scanner class methods:.hasNext() // returns true if there is more data to be read.hasNextInt() //returns true if the next value is an int.hasNextFloat() // returns true if the next value is a float.hasNextDouble() // returns true if the next value is a double We’ll likely use the.hasNext method (how?)

int[][] matrix = new int[][]; File fl = new File(filename); if (fl.exists()) { System.out.println("The file exists!"); } Scanner fn = new Scanner(fl); int row = 0; while (fn.hasNext()) { String line = fn.nextLine(); System.out.println(line); String[] numarr = line.split("\t"); for (int i = 0; i<numarr.length;i++){ matrix[row][i] = Integer.parseInt(numarr[i]); } row++; } fn.close(); What does this do?

Exceptions What could go wrong when we are trying to write data to a file? out of disk space don't have permission to write disk disconnected during our write file "locked" by a different program (maybe another program is writing to it when you want to…) etc

Exceptions We want to check for some exceptions, especially if we know it’s something that occurs regularly. Certain methods in java create exceptions for us They “throw an exception” File IO (the Scanner class) definitely creates exceptions for us. Some of the file IO exceptions are: IOException EOFException FileNotFoundException

Try…Catch We use Try…Catch to catch exceptions that are thrown. So if a method might “throw an exception” if something goes wrong, we can try it. If we don’t succeed and an exception is thrown, we “catch it. E.g.,: File fl = new File(filename); try { Scanner fn = new Scanner(fl); int row = 0; while (fn.hasNext()) { String line = fn.nextLine(); arr[row] = line; row++; } fn.close(); } catch (FileNotFoundException e) { System.out.println(“e.getMessage()"); System.exit(0); }

You can catch more than one exception: private int[][] makeMatrix(String filename) { int[][] matrix = new int[13][13]; File fl = new File(filename); try { Scanner fn = new Scanner(fl); int row = 0; while (fn.hasNext()) { String line = fn.nextLine(); System.out.println(line); String[] numarr = line.split("\t"); for (int i = 0; i<numarr.length;i++){ matrix[row][i] = Integer.parseInt(numarr[i]); } row++; } fn.close(); } catch (FileNotFoundException e) { System.out.println("File not found: " + e.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); System.exit(0); } return matrix; }

In general: There’s Exception – the catch-all exception that’s thrown. To find out what the problem was, use the Exception object’s getMessage method. E.g., try { int x = 10; int y = 0; int z = x/y; System.out.println(z); } catch (Exception err) { System.out.println(err.getMessage()); } Google other Exception errors if you want to use them.

Writing to a file: System.out.println is actually a special instance of PrintStream File myOutputFile = new File(“myOutputFile.txt”); PrintStream output = new PrintStream(myOutputFile); PrintStream “throws an error” so we will want to try it and, if unsuccessful, catch the error.

For example: public void makefile() { File f1 = new File("testout.txt"); try { PrintStream outfile = new PrintStream(f1); for (double[] x: newmatrix) { for (double y: x) { outfile.print(y + " "); } outfile.println(); } outfile.close(); } catch(IOException io) { System.out.println(io.getMessage()); }

How about formatting? In the previous example we were printing out doubles generated randomly. We get: This is ugly, and we often don’t care about the th place. Can we format?

Formatting: Instead of using print, use format, e.g, System.out.format(“”); Outfile.format(); And then we format, e.g.,: Double pi = ; System.out.format(“%3.2f”, pi); Prints: 3.14 %f prints a double or float out to 6 places %.3f prints a double or float with 3 values after the decimal (but as many numbers as needed) %4.3f prints a double with 3 values after the decimal but the whole string occupying 4 places. It doesn’t truncate the number before the decimal. However, if the number is smaller than the first number (e.g., %10.3), it will make the whole number 10 characters long, including the decimal, then add spaces to the left.

More formatting: Integer formatting: %d prints an integer with as many digits as needed %4d prints an integer with as many digits as needed, but always at least 4, with spaces to the left %04d prints an integer with as many digits as needed, but always at least 4, with zeros to the left Examples: System.out.format(“%d, %4d, %04d”, 34291, 34, 34); Prints: 34291, 34, 0034

Formatting Strings: %s prints the string (the whole string) %15s prints out a string with the specified number, right justified. %-15s prints out the string with the specified number, left-justified E.g., System.out.format("%s: %15s: %-15s:", "echidna", "wombat", "puffin"); Prints: echidna: wombat: puffin :