Java Reference
In-Depth Information
Nest loops
I n this chapter, you will learn about the statements that control a program's flow of execu-
tion. There are three categories of program control statements: selection statements, which
include the if and the switch ; iteration statements, which include the for , while , and do-
while loops; and jump statements, which include break , continue , and return . Except for
return , which is discussed later in this topic, the remaining control statements, including
the if and for statements to which you have already had a brief introduction, are examined
in detail here. The chapter begins by explaining how to perform some simple keyboard in-
put.
Input Characters from the Keyboard
Before examining Java's control statements, we will make a short digression that will allow
you to begin writing interactive programs. Up to this point, the sample programs in this
book have displayed information to the user, but they have not received information from
the user. Thus, you have been using console output, but not console (keyboard) input. The
main reason for this is that Java's input capabilities rely on or make use of features not
discussed until later in this topic. Also, most real-world Java programs and applets will be
graphical and window based, not console based. For these reasons, not much use of console
input is found in this topic. However, there is one type of console input that is relatively
easy to use: reading a character from the keyboard. Since several of the examples in this
chapter will make use of this feature, it is discussed here.
To read a character from the keyboard, we will use System.in.read( ) . System.in is the
complement to System.out . It is the input object attached to the keyboard. The read( )
method waits until the user presses a key and then returns the result. The character is re-
turned as an integer, so it must be cast into a char to assign it to a char variable. By default,
console input is line buffered . Here, the term buffer refers to a small portion of memory
that is used to hold the characters before they are read by your program. In this case, the
buffer holds a complete line of text. As a result, you must press ENTER before any character
that you type will be sent to your program. Here is a program that reads a character from
the keyboard:
Search WWH ::




Custom Search