Java Reference
In-Depth Information
Display 2.8
Methods of the Scanner Class (part 2 of 2)
Scanner_Object_Name .nextBoolean()
Returns the next value of type boolean that is typed on the keyboard. The values of true
and false are entered as the strings "true" and "false" . Any combination of upper- and/or
lowercase letters is allowed in spelling "true" and "false" .
Scanner_Object_Name .nextLine()
Reads the rest of the current keyboard input line and returns the characters read as a value of
type String . Note that the line terminator '\n' is read and discarded; it is not included in the string
returned.
Scanner_Object_Name .useDelimiter ( New_Delimiter );
Changes the delimiter for keyboard input with Scanner_Object_Name . The New_Delimiter is a
value of type String . After this statement is executed, New_Delimiter is the only delimiter that
separates words or numbers. See the subsection “Other Input Delimiters”, later in this chapter,
for details.
Keyboard Input Using the Scanner Class
You can use an object of the class Scanner to read input from the keyboard. To make the
Scanner class available for use in your code, you should include the following at the start of
the file that contains your program (or other code that does keyboard input):
import java.util.Scanner;
Before you do any keyboard input, you must create an object of the class Scanner as
follows:
Scanner Object_Name = new Scanner(System.in);
where Object_Name is any (nonkeyword) Java identifier. For example,
Scanner keyboard = new Scanner(System.in);
The methods nextInt , nextDouble , and next read a value of type int , a value of type
double , and a word, respectively. The method nextLine reads the remainder of the
current input line including the terminating '\n' . However, the '\n' is not included in the
string value returned. Other input methods are given in Display 2.8.
SYNTAX
Int_Variable = Object_Name .nextInt()
Double_Variable = Object_Name .nextDouble();
String_Variable = Object_Name .next();
String_Variable = Object_Name .nextLine();
 
 
Search WWH ::




Custom Search