220 likes | 453 Views
Java I/O using Scanner, Files. For CS201, SW Development Methods. Topics: I/O Streams Scanner class Reading from Files and Strings Reminder slides Adopted from slides for: CS 101, Chapter 2, Spring 2005 Aaron Bloomfield. Variable System.out gives. access to an output stream.
E N D
Java I/O using Scanner, Files For CS201, SW Development Methods. Topics: I/O Streams Scanner class Reading from Files and Strings Reminder slides Adopted from slides for: CS 101, Chapter 2, Spring 2005 Aaron Bloomfield
Variable System.out gives access to an output stream of type PrintStream The printing destination attribute for this PrintStream object is the console window The behaviors of a PrintStream object support a high-level view of printing System.out System.out : PrintStream - destination = - ... + println(String s) : void + print(String s) : void + ...
The period indicates that we want to The period indicates that we want to select an select an individual class member of out individual class member of System The method we are calling Member out of System is an output Literal character string that is stream object automatically the parameter to print(). associated with the console window running the application Class System is defined in the standard Method member of out. The execution of member print() package java.lang causes its parameter to be displayed to the output stream Selection string . . " " System out print ( )
I/O streams • System.out • Prints to standard output • Equivalent to cout in C++, and print() in C • System.err • Prints to standard error • Equivalent to cerr in C++, and fprintf(stderr) in C • System.in • Reads from standard input • Equivalent to cin in C++, and scanf() in C
Support for interactive console programs • Variable System.in • Associated with the standard input stream – the keyboard • Class Scanner • Makes obtaining input from the keyboard easy Scanner stdin = new Scanner (System.in); stdin : Scanner Variable stdin gives Scanner access to an input stream - source = - ... Input source attribute for this Scanner is the keyboard + nextDouble() : double + ... Behaviors of a Scanner support high-level view of inputting text
How to make Java work with the Scanner class • In Java 1.5, do a:import java.util.*; • To create a new Scanner (for the keyboard):Scanner stdin = new Scanner (System.in); • Do NOT use the following (it won’t work):Scanner stdin = Scanner.create (System.in); • This was correct for a short-time in the beta of Java 5.0,but was dropped in the final version. • Java API Documentation for Scanner:http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html
Scanner API public Scanner(InputStream in) // Scanner(): constructor for reading from a // InputStream public Scanner(File f) // Scanner(): constructor to read from a file object public Scanner(String s) // Scanner(): constructor to scan from a string public int nextInt() // nextInt(): next input value as an int public short nextShort() // nextShort(): next input value as a short public long nextLong() // nextLong(): next input value as a long public double nextDouble() // nextDouble(): next next input value as a double public float nextFloat() // nextFloat(): next next input value as a float public String next() // next(): get next whitespace-free string public String nextLine() // nextLine(): return contents of input line buffer public boolean hasNext() // hasNext(): is there a value to next
A Simple Example import java.util.*; public class MathFun { public static void main(String[] args) { // set up the Scanner object Scanner stdin = new Scanner(System.in); // have the user input the values for x and y System.out.print("Enter a decimal number: "); double x = stdin.nextDouble(); System.out.print("Enter another decimal number: "); double y = stdin.nextDouble(); double squareRootX = Math.sqrt(x); System.out.println ("Square root of " + x + " is " + squareRootX); } }
Typical Use of Scanner • Construct a scanner object • Use hasNext() to see if possible to read next item • Get the item with one of the “next” methods • Repeat as necessary • Example: read all input until “end of file” or “end of input” Scanner theInput = new Scanner( some-argument ); while ( theInput.hasNext() ) { String token = theInput.next(); // do something with the String you just read } • Note we could have called any of the “next methods” • Sometimes you must make sure there’s something to read before reading: if ( theInput.hasNext() ) anInt = theInput.nextInt();
You Can “Read” from Strings • When you create a scanner object, you can associate it with a String object • Pass a String to the constructor • Allows you to extract or scan values of various types from a string • Very useful! • Could you write this code? • Read an entire line from the input • Then, read each item in that line • Hint: need loop like the previous page, nextLine() and a second loop using a second scanner
You Can Read from a File Instead of the Keyboard • When you create a scanner object, associate it with a File object instead of System.in • The Java type File is an object that represents a file on disk • Need to have: import java.io.*; • Create a Java File object that’s linked to a disk-file: • Pass the File constructor a String containing the file-name and pathBut, this may fail! • Bad file-name • File not available for reading
Catching Exceptions when Opening a File • The File constructor may throw an exception • Exception is a Java object created when an error occurs • Handle this with a try-catch block • try { … } surrounds the code that might throw the exception • catch (Exception e) { … } follows the try-block and contains code to be executed if an exception of type Exception just occurred • Follow this example when opening a file:String fname = "mydata.txt";try { Scanner myInput = new Scanner( new File(fname) );}catch (Exception e) { System.out.println("Error: Cannot open file: " + fname);}
Some Reminder Slides • Here are some additional slides from that lecture in CS101 • You may know all the following • But maybe a quick review won’t hurt
System.out.println() public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943."); } • Class System supplies objects that can print and read values • System variable out references the standard printing object • Known as the standard output stream • Variable out provides access to printing methods • print(): displays a value • println(): displays a value and moves cursor to the next line
Escape sequences • Java provides escape sequences for printing special characters • \b backspace • \n newline • \t tab • \r carriage return • \\ backslash • \" double quote • \' single quote
Escape sequences • What do these statements output? System.out.println("Person\tHeight\tShoe size"); System.out.println("========================="); System.out.println("Hannah\t5‘1\"\t7"); System.out.println("Jenna\t5'10\"\t9"); System.out.println("JJ\t6'1\"\t14"); • Output Person Height Shoe size ========================= Hannah 5‘1" 7 Jenna 5'10" 9 JJ 6'1" 14
Casting • Consider the following code double d = 3.6; int x = Math.round(d); • Java complains (about loss of precision). Why? • Math.round() returns a long, not an int • So this is forcing a long value into an int variable • How to fix this double d = 3.6; int x = (int) Math.round(d); • You are telling Java that it is okay to do this • This is called “casting” • The type name is in parenthesis
More casting examples • Consider double d = 3.6; int x = (int) d; • At this point, x holds 3 (not 4!) • This truncates the value! • Consider int x = 300; byte b = (byte) x; System.out.println (b); • What gets printed? • Recall that a byte can hold values -128 to 127 • 44! • This is the “loss of precision”