Java provides a Scanner class to facilitate data input/output. In this section, you will learn about the Scanner class that is used to get input from the user. Java also defines various methods from the Scanner class that can convert user input into appropriate data types before conducting any operation on the data.
12. nextInt()
Answer:
int
nextInt()
nextInt()
The nextInt()
method of a Scanner
object reads in a string of digits (characters) and converts them into an int
type.
The Scanner
object reads the characters one by one until it has collected those that are used for one integer. Then it converts them into a 32-bit numeric value. Usually that value is stored in an int
variable.
The picture shows a program that reads in character data and then converts it into an integer which is stored in num
. Next the program does arithmetic with num
and stores the result in square
. Finally the result is sent to println
which converts the numeric result into characters and prints them out.
The nextInt()
method scans through the input stream character by character, gathering characters into a group that can be converted into numeric data. It ignores spaces and end-of-lines that may preceed the group.
A space or end-of-line character that follows a string of digits ends the group. A non-digit character cannot be part of a group (not even at the end.) For example,
123
and
123
are legitimate input, but
123X
is not.
Question 12:
Which of the following are legitimate input for
nextInt()
?4 45 456 923X 23 876