java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner



Similar documents
Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

Introduction to Java

JAVA.UTIL.SCANNER CLASS

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

Chapter 2 Elementary Programming

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Chapter 2: Elements of Java

Chapter 3. Input and output. 3.1 The System class

Introduction to Java. CS 3: Computer Programming in Java

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

CS 106 Introduction to Computer Science I

Pemrograman Dasar. Basic Elements Of Java

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

AP Computer Science Static Methods, Strings, User Input

Sample CSE8A midterm Multiple Choice (circle one)

Topic 11 Scanner object, conditional execution

D06 PROGRAMMING with JAVA

Reading Input From A File

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Basics of Java Programming Input and the Scanner class

Handout 3 cs180 - Programming Fundamentals Spring 15 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane.

Variables, Constants, and Data Types

J a v a Quiz (Unit 3, Test 0 Practice)

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

Building Java Programs

Explain the relationship between a class and an object. Which is general and which is specific?

Using Files as Input/Output in Java 5.0 Applications

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Carron Shankland. Content. String manipula3on in Java The use of files in Java The use of the command line arguments References:

IRA EXAMPLES. This topic has two examples showing the calculation of the future value an IRA (Individual Retirement Account).

Building Java Programs

Chapter 2 Introduction to Java programming

Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output

Programming Languages CIS 443

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

Object-Oriented Programming in Java

Event-Driven Programming

Java Interview Questions and Answers

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

Week 1: Review of Java Programming Basics

Building Java Programs

CS1020 Data Structures and Algorithms I Lecture Note #1. Introduction to Java

AP Computer Science File Input with Scanner

CS 106 Introduction to Computer Science I

Lecture 1 Introduction to Java

READING DATA FROM KEYBOARD USING DATAINPUTSTREAM, BUFFEREDREADER AND SCANNER

AP Computer Science Java Subset

6.1. Example: A Tip Calculator 6-1

CS 111 Classes I 1. Software Organization View to this point:

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Lecture 5: Java Fundamentals III

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)

Programming and Data Structures with Java and JUnit. Rick Mercer

Install Java Development Kit (JDK) 1.8

Crash Course in Java

Computer Programming I

Part I. Multiple Choice Questions (2 points each):

Interactive Programs and Graphics in Java

CS 1302 Ch 19, Binary I/O

Introduction to Programming

13 File Output and Input

Third AP Edition. Object-Oriented Programming and Data Structures. Maria Litvin. Gary Litvin. Phillips Academy, Andover, Massachusetts

Comp 248 Introduction to Programming

MIDTERM 1 REVIEW WRITING CODE POSSIBLE SOLUTION

Some Scanner Class Methods

In this Chapter you ll learn:

Programming in Java. What is in This Chapter? Chapter 1

Java 進 階 程 式 設 計 03/14~03/21

Introduction to Java Lecture Notes. Ryan Dougherty

LOOPS CHAPTER CHAPTER GOALS

java Features Version April 19, 2013 by Thorsten Kracht

Course Intro Instructor Intro Java Intro, Continued

CS106A, Stanford Handout #38. Strings and Chars

IMDB Data Set Topics: Parsing Input using Scanner class. Atul Prakash

D06 PROGRAMMING with JAVA

Chapter 20 Streams and Binary Input/Output. Big Java Early Objects by Cay Horstmann Copyright 2014 by John Wiley & Sons. All rights reserved.

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

JavaScript: Introduction to Scripting Pearson Education, Inc. All rights reserved.

Building a Multi-Threaded Web Server

WRITING DATA TO A BINARY FILE

A Brief Introduction to MySQL

WA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc.

Line-based file processing

Outline Basic concepts of Python language

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

Java Basics: Data Types, Variables, and Loops

Moving from CS 61A Scheme to CS 61B Java

CS170 Lab 11 Abstract Data Types & Objects

CSE 1020 Introduction to Computer Science I A sample nal exam

Compiler Construction

Chapter 8. Living with Java. 8.1 Standard Output

Arrays. Introduction. Chapter 7

Quick Introduction to Java

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

JavaScript: Control Statements I

Transcription:

java.util.scanner java.util.scanner is a class in the Java API used to create a Scanner object, an extremely versatile object that you can use to input alphanumeric characters from several input sources and convert them to binary data.. The following three constructors allow you to scan data from the standard input object (System.in), from string objects (especially ones provided by an input dialog box) and from external text files. Three Constructors of java.util.scanner public Scanner( InputStream source ) // Creates a scanner that scans values from the input stream. public Scanner( String source ) // Creates a scanner that scans values from the string. public Scanner( File source ) // Creates a scanner that scans values from the external file. Here are some of the many features of Scanner objects. Some Features of java.util.scanner They can scan data of all the primitive data types (e.g. int, double, etc.) except char. They can scan strings. They easily scan multiple tokens from a single input source. They can change the characters used to delimit tokens in the input. They can specify the precise pattern of legal input. They generate an InputMismatchException if the input does not conform to the expected data type, allowing you to use try and catch constructs to validate the user s input. java.util.scanner Page

Scanning from the Standard Input Object The first Scanner constructor allows you to create a scanner for the standard input object System.in, which is an object of class InputStream. Example The following Java code reads two floating-point values from the standard input object. Below shows the user interaction (the underlined text shows what the user types; the program doesn t underline anything). To the right is a picture of memory after the input values are scanned. weight.0 height 0.0 Enter your weight and height: 0 66 5 6 double weight, height; // patient stats Scanner in = new Scanner( System.in ); System.out.print( "Enter your weight and height: " ); weight = in.nextdouble( ); height = in.nextdouble( ); Scanning from a String The second Scanner constructor allows you to create a scanner for a string, which you can use to scan data input from a dialog box. Example This Java code gets its input from the dialog box shown to the right. 5 6 7 import javax.swing.joptionpane; String prompt = "Enter your weight and height: "; String input = JOptionPane.showInputDialog( prompt ); Scanner in = new Scanner( input ); double weight = in.nextdouble( ); double height = in.nextdouble( ); java.util.scanner Page

Scanning from an External Text File The third Scanner constructor allows you to create a scanner that gets its input from a file of text residing on the external disk. Example Suppose you have an external file named data.txt that contains the values you wish to input. See the picture to the right. data.txt 65 67 The following Java code opens the file as a scanner and inputs the two values. It assumes that the data file resides in the same folder as the application s class file. 5 import java.io.file; Scanner in = new Scanner( new File( "data.txt" ) ); double weight = in.nextdouble( ); double height = in.nextdouble( ); java.util.scanner Page

Scanning Primitive Data and Strings java.util.scanner has methods to scan all the primitive data types except char. In addition, it has two methods that scan strings. Scanner Methods that Scan Primitive Data public double nextdouble( ) Scans floating-point data public float nextfloat( ) public byte nextbyte( ) public int nextint( ) Scans integer data public long nextlong( ) public short nextshort( ) Scans true and false public boolean nextboolean( ) Scanner Methods that Scan Strings next( ) Method nextline( ) What it Does Skips leading white space, collects alphanumeric characters until encountering trailing white space, returns the characters collected as a string. Collects all characters (visible and invisible) until encountering the next newline character and returns the characters collected as a string. To scan a primitive value, call the appropriate method within the Scanner object and store the scanned value into a variable of the same primitive data type. Example 5 Scanner in = new Scanner( System.in ); double salary = in.nextdouble( ); boolean ismarried = in.nextboolean( ); int numberchildren = in.nextint( ); java.util.scanner Page

To scan a string, you must a declare reference variable for the String object that is to be returned. You don t need to initialize it the object is built and returned by the method. Example 5 6 Scanner in = new Scanner( System.in ); System.out.print( "Enter name and address: " ); String firstname = input.next( ); String lastname = input.next( ); String address = input.nextline( ); Suppose in response to the user prompt, the user enters the underlined text shown below: Enter name and address: Herb Green 50 Maple St. The input is read in three parts. The call to next on line reads Herb and ends because of the trailing space. The string reference is placed into firstname: firstname Herb String object Line 5 reads Green and places it into a string object referenced by lastname: lastname Green String object Line 6 uses a call to nextline to read the entire address including its embedded spaces. nextline scans characters until reaching the newline character. The scanned string is placed into a string object referenced by address: address String object 50 Maple St. java.util.scanner Page 5

Specifying Token Delimiters By default a Scanner object expects tokens to be delimited by white space (i.e. spaces, horizontal tabs and newline characters). You can change the delimiter by calling these Scanner methods: Scanner Methods to Change Token Delimiters Scanner usedelimiter( String pattern ) // Set the scanner's token delimiter to the characters specified // by the 'pattern' string. Scanner reset( ) // Restores the scanner's token delimiter to its default. Although these methods return a Scanner object, it s the same as the altered scanner so there s no reason to save it. Example Line in the Java code below tells the scanner to use a single comma as a token delimiter. For example, the input string Herb Green,50 Maple St,Kansas City Would be divided into these three tokens: Herb Green 50 Maple St Kansas City Scanner in = new Scanner( System.in ); in.usedelimiter( "," ); java.util.scanner Page 6

A pattern matches a set of string literals. It looks very much like a string literal itself but some of its characters are metacharacters that represent different combinations of characters. A full explanation of patterns is an entire topic in itself. Following are some simple, but useful, token delimiting patterns. Pattern " character " "[ characters ]" "[ characters ]+" What it Means character is any character literal (including an escape sequence). The pattern matches the character characters is a sequence of characters and[ and ] are metacharacters. The pattern matches any single character in the sequence. + is a metacharacter. The pattern matches one or more occurrences of each of the characters. Examples This pattern Matches " " A single space "\n" A single newline character "," A single comma "[, ]" Any single comma or space "[ \n]" Any single space or newline character "[/-]" Any single slash or hyphen "[.,;]" Any single period, comma or semi-colon "[ ]+" One or more spaces "[, ]+" Any combination of one or more commas or spaces java.util.scanner Page 7

Making the Newline Character Portable The pattern "\n" stands for the newline character, which, unfortunately, is not standard across operating systems. For example, a new line is marked in Microsoft Windows with a combination of two Unicode characters \u000d followed by \u000a whereas MacOS uses a single \u000. This can create problems when trying to move code from one platform to another. To avoid this problem, use the static method lineseparator that is found in the API class java.lang.system. static String lineseparator( ) // Returns the system-dependent line separator as a string. You can use it by itself or use concatenation to embed it within a more complicated pattern. Examples This pattern System.lineSeparator( ) "[," + System.lineSeparator( ) + "]" "[ " + System.lineSeparator( ) + "]+" Matches A single newline character A single comma or a single newline character A combination of one or more spaces and newline characters Specifying Input Patterns You can also use a pattern, along with the following method, to specify the precise format of legal input. String next( String pattern ) // Returns the next token if it matches the pattern. If the next input token doesn t match the pattern then the method throws an InputMismatchException. java.util.scanner Page 8

Example This Java code reads a vehicle s license plate number consisting of three digits followed by three upper-case letters and terminated by the system dependent line separator. Scanner in = new Scanner( System.in ); in.usedelimiter( System.lineSeparator( ) ); String input = in.next( "[0-9]{}[A-Z]{}" ); For a more detailed description of Java patterns, you should refer to the API specification for class java.util.regex.pattern. Input Validation Generally, Scanner methods throw an InputMismatchException if the next input token does not conform to what is expected. Example The following Java code, if the user were to enter the input $,5.50, would halt with the run-time error: Exception in evaluation thread java.util.inputmismatchexception Scanner in = new Scanner( System.in ); System.out.print( "Enter salary: " ); double salary = in.nextdouble( ); This behavior enables to you, by using Java s try and catch constructs, to control what happens in such situations so that your program responds to bad input in a user-friendly manner. java.util.scanner Page 9

Example The following Java code uses a loop to trap user input errors. The loop (lines 7 through ) continues to cycle so long as the user s input is not a valid floating-point number. If the user enters valid input, the loop quits. 5 6 7 8 9 0 5 6 7 8 9 0 import java.util.inputmismatchexception; double salary; Scanner in = new Scanner( System.in ); in.usedelimiter( System.lineSeparator( ) ); boolean inputok = false; // set flag to indicate bad input while (! inputok ) // while flag indicates bad input { try { System.out.println( "Enter salary: " ); salary = in.nextdouble( ); // may throw exception inputok = true; // no exception thrown } catch ( InputMismatchException ex ) { // exception thrown System.out.println( "Bad input. Try again." ); inputok = false; in.nextline( ); // drop line separator in input } } java.util.scanner Page 0

Exercises In each problem below, the first two statements are correct; there is something wrong with method call in the third statement. Circle what's wrong and explain. None of them is correct.. Scanner input = new Scanner( System.in ); double x = input.next( );. Scanner input = new Scanner( System.in ); int m = input.nextdouble( );. Scanner input = new Scanner( System.in ); int m = nextint( );. Scanner input = new Scanner( System.in ); int m = input.nextint( ); 5. Scanner input = new Scanner( System.in ); String line = input.next; 6. Scanner input = new Scanner( System.in ); String line = input.nextline( ); java.util.scanner Page

Enter the application given below into jgrasp, save it to a file and compile it. For each of the exercises that follow, run the application, enter the input given and explain why the program works or doesn t work. 5 6 7 8 9 0 5 6 7 8 9 0 public class Scanning { public static void main( String [] args ) { // declare data String name; // child's first name double height; // child's height int age; // child's age // build Scanner Scanner input = new Scanner( System.in ); // prompt for and read data System.out.println( "Name? Age? Height?" ); name = input.next( ); age = input.nextint( ); height = input.nextdouble( ); // print results System.out.println( "Name: " + name ); System.out.println( "Age: " + age ); System.out.println( "Height: " + height ); } } 7. Tom.75 8. Tom Jones.75 9. Tom.5.75 0. Tom java.util.scanner Page

. Modify application Scanning given above so that it will read a child s name that has embedded spaces.. Modify application Scanning given above so that it reads all three values from a single JOptionPane input dialog. If you modified application Scanning according to previous exercises, then retrieve the original shown on page. Add the following after line : input.usedelimiter( "," ); For each of the following exercises, run the application, enter the input given and explain why the program works or doesn t work.. Tom Jones,,.75. Tom Jones,,.75, Continuing with the Scanning application from exercises 9 and 0, change line to: input.usedelimiter( "[," + System.lineSeparator( ) + "]" ); For the following exercise, run the application, enter the input given and explain why the program works or doesn t work. 5. Tom Jones,,.75 java.util.scanner Page

For each of the following exercises: (a) Write the Java statements to scan the described values from the standard input object. (b) Write the Java statements to input and scan the described values from a single JOptionPane input dialog. In each case, you may have to change the scanner delimiter to something appropriate for the situation. 6. Input an int value into a variable named score. 7. Input a person s height (a double), weight (a double) and age (an int). Declare appropriate variables for the values. 8. Input a string and store its reference into phone. The string has no embedded spaces. 9. Input a string and store its reference into title. The title may have embedded spaces and is followed by the newline character. 0. Input a company s department name (a string with no embedded spaces) and its budget (a double).. Input a company s department name (this time allowing the department name to have embedded spaces such as INFORMATION SYSTEMS) and its budget (a double).. Input a person s name (a string that may have embedded spaces), height (a double), weight (a double) and age (an int). Declare appropriate variables for the values.. Scan a person s name (a string that may have embedded spaces), address (another string that may have embedded spaces), marital status (true or false) and number of tax exemptions (an int). Declare appropriate variables for the values.. Scan hours, minutes, seconds in the form hh:mm:ss. Read the values into three int variables. java.util.scanner Page