Java Reference
In-Depth Information
18
// prompt for and read name
19
System.out.println(
"Please enter the name:"
);
20
String theName = input.nextLine();
// read a line of text
myAccount.setName(theName);
// put theName in myAccount
21
22
System.out.println();
// outputs a blank line
23
24
// display the name stored in object myAccount
25
System.out.printf(
"Name in object myAccount is:%n%s%n"
,
26
myAccount.getName()
);
27
}
28
}
// end class AccountTest
Initial name is: null
Please enter the name:
Jane Green
Name in object myAccount is:
Jane Green
Fig. 3.2
|
Creating and manipulating an
Account
object. (Part 2 of 2.)
Scanner
Object for Receiving Input from the User
Line 10 creates a
Scanner
object named
input
for inputting the name from the user. Line
19 prompts the user to enter a name. Line 20 uses the
Scanner
object's
nextLine
method to
read the name from the user and assign it to the
local
variable
theName
. You type the name
and press
Enter
to submit it to the program. Pressing
Enter
inserts a newline character after
the characters you typed. Method
nextLine
reads characters (including white-space charac-
ters, such as the blank in
"Jane
Green"
) until it encounters the newline, then returns a
String
containing the characters up to, but
not
including, the newline, which is
discarded
.
Class
Scanner
provides various other input methods, as you'll see throughout the
book. A method similar to
nextLine
—named
next
—reads the
next
word
. When you press
Enter
after typing some text, method
next
reads characters until it encounters a
white-space
character
(such as a space, tab or newline), then returns a
String
containing the characters
up to, but
not
including, the white-space character, which is
discarded
. All information
after the first white-space character is
not lost
—it can be read by subsequent statements that
call the
Scanner
's methods later in the program.
Instantiating an Object—Keyword
new
and Constructors
Line 13 creates an
Account
object and assigns it to variable
myAccount
of type
Account
.
Variable
myAccount
is initialized with the result of the
class instance creation expression
new Account()
. Keyword
new
creates a new object of the specified class—in this case,
Ac-
count
. The parentheses to the right of
Account
are
required
. As you'll learn in Section 3.4,
those parentheses in combination with a class name represent a call to a
constructor
, which
is
similar
to a method but is called implicitly by the
new
operator to
initialize
an object's
instance variables when the object is
created
. In Section 3.4, you'll see how to place an
ar-
gument
in the parentheses to specify an
initial value
for an
Account
object's
name
instance
variable—you'll enhance class
Account
to enable this. For now, we simply leave the paren-
theses
empty
. Line 10 contains a class instance creation expression for a
Scanner
object—