User Input You’ve seen this: A Scanner object:

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

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 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.
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.
Evan Korth Scanner class Evan Korth NYU. Evan Korth Java 1.5 (5.0)’s Scanner class Prior to Java 1.5 getting input from the console involved multiple.
COMP 14 Introduction to Programming Miguel A. Otaduy May 17, 2004.
21-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.
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.
1 TCSS 143, Autumn 2004 Lecture Notes Review. 2 Computer programming computers manipulate data data is often categorized into types numbers (integers,
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.
Using java’s Scanner class To read from input and from a file. (horstmann ch04 and ch 17)
Conditional If Week 3. Lecture outcomes Boolean operators – == (equal ) – OR (||) – AND (&&) If statements User input vs command line arguments.
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.
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.
File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files.
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.
Can we talk?. In Hello World we already saw how to do Standard Output. You simply use the command line System.out.println(“text”); There are different.
Miscellaneous topics Chapter 2 Savitch. Miscellaneous topics Standard output using System.out Input using Scanner class.
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.
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
CMSC 202 Text File I/O. Aug 8, Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with.
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.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Week 12 – Text Files Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
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.
File Input & Output Sections Outcomes  Know the difference between files and streams  Use a Scanner to read from a file  add “throws” annotations.
Chapter 2 Console Input and Output Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
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.
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.
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 Computer Science and Object-Oriented Programming
CompSci 230 S Programming Techniques
File I/O (Input and Output)
Streams & File Input/Output (I/O)
CMSC 202 Text File I/O.
Introduction to programming in java
String Comparison, Scanner
Input/Output.
Console Input and Output
TemperatureConversion
Project 1.
Streams and File I/O.
OBJECT ORIENTED PROGRAMMING II LECTURE 2 GEORGE KOUTSOGIANNAKIS
Building Java Programs
CSS161: Fundamentals of Computing
CSS 161 Fundamentals of Computing Introduction to Computers & Java
Introduction to Classes and Methods
A+ Computer Science INPUT.
Input/output (I/O) import java.io.*;
Introduction to Computing Using Java
OBJECT ORIENTED PROGRAMMING II LECTURE 13_1 GEORGE KOUTSOGIANNAKIS
A+ Computer Science INPUT.
Introduction to Java Applications
Input/output (I/O) import java.io.*;
មជ្ឈមណ្ឌលកូរ៉េ សហ្វវែរ អេច អ ឌី
Exceptions 10-May-19.
Basic Exception Handling
Presentation transcript:

User Input You’ve seen this: 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 An Input Stream 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: Enter an int, a float, a double and a string. 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. 2 3.1 3.24 hi there how are you Now enter another value. no Here is what you entered: 2 3.1 3.24 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 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; You can catch more than one exception:

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: 217.8575927137373 597.655625825856 210.56479046932353 518.4918672220385 980.1225356891215 249.22772143775117 94.27214196883537 218.54436204437766 909.1938505252127 64.77187265528717 522.4332161890065 409.3104756268032 523.8845868006724 545.9574555472581 480.24527204720766 423.3817954814687 1.1995922112015833 31.542425381440474 159.2409972487274 826.9895092890089 876.7185709820699 905.5090060305496 826.2549887160317 902.8826404817949 102.6001484498129 865.678399786176 869.3623864174282 764.6236242191251 832.6226040740607 744.5345466483448 480.5374374958481 328.8940102976276 804.6528435755249 476.5255281033308 701.3804741693555 865.5677865881347 473.16200063038025 939.9005125578615 106.11401024206168 869.7228980147195 107.8829700207542 566.1791646848557 225.14981932646862 555.4267916885535 919.4309107470867 806.6396061869323 922.8806070647845 358.04479313158765 898.6853144841515 772.7498589630353 334.9514250847454 449.98473057812527 463.9578866182207 626.2568492194717 643.117385541904 424.2054922717532 198.44775061227148 584.6863387866528 919.8961924374581 980.4804996320166 930.2115601909552 729.2957731241569 510.5749895400613 661.322074457543 157.8530590786883 155.06158864366725 936.7331953500385 427.63591389063413 357.3626766233403 386.07120201134194 103.29393913692742 138.5895515411516 19.015139669919414 394.72893290349253 670.2189767548267 805.8424225713404 357.9585978625832 9.474846909941048 810.3128833868223 829.1992908814386 518.1060966371921 973.2535478211257 216.2041575662601 288.9128758724809 746.1667967184507 423.75974056620225 142.42259858874107 769.2755643999647 451.13010115309584 106.52640929375889 472.5935354330558 118.80427438277653 284.2434781014766 203.21002242875142 287.12133694128306 14.23626895067953 375.5006089897035 259.96665890567016 173.33597287852288 188.71818119248795 644.883318809338 334.60225938402357 567.9282666825169 708.9843882036027 670.0770831263618 146.21828511551684 750.6004229089104 741.984720568829 937.1070809292727 707.3644617291698 718.2110183812108 838.3361590205222 426.3172853136753 646.248048345563 60.29399686015824 878.1364931147457 This is ugly, and we often don’t care about the .00000001th 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 = 3.14159; 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 %4.3f prints a double with 3 values after the decimal but the whole string occupying 4 places. It never truncates 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 of characters, 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 :

Formatting, Special Characters: Special characters in formatting are preceded with a \ \t prints a tab \n adds a new line \\ inserts a backslash \’ inserts a single quote \” inserts a double quote E.g., String[] s = {"cat","dog","echidna","wombat","whale","bunny"}; for (int i = 0; i < s.length; i++) { System.out.format("%s\t",s[i]); if ((i+1)%2 == 0) { System.out.format("\n"); } Prints: cat dog echidna wombat whale bunny:

Try: Write a method that prints out a 3x4 Matrix of integers (random numbers) Random r = new Random(); int arr[][] = new int[3][4]; for (int i = 0; i < arr.length*arr[0].length; i++) { arr[Math.floorDiv(i,4)][i%4] = r.nextInt(10); } for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) { System.out.format("%2d\t",arr[i][j]); System.out.format("\n");