Java User Input

Java User Input


User Input In Java
Scanner class is used to read input from users, We will discuss them as follows -
  • The scanner is the complement of Formatter. Added by JDK 5.
  • Scanner reads formatted input and converts it into its binary form. 
  • Although it has always been possible to read formatted input, it required more effort than most programmers would prefer.
  • Because of the addition of Scanner, it is now easy to read all types of numeric values, strings, and other types of data, whether it comes from a disk file, the keyboard, or another source.
  • you can use Scanner to read a number from the keyboard and assign its value to a variable. As you will see, given its power, Scanner is surprisingly easy to use.
The Scanner class is packaged in java.util. Scanner
To use Scanner to read from the keyboard, you must first create a Scanner linked to console input. To do this, you will use the following constructor -
Scanner(InputStream from)
  • This creates a Scanner that uses the stream specified by from as a source for input. You can use this constructor to create a Scanner linked to the console input.
Scanner conin = new Scanner(System.in); 
  • This works because System.in is an object of type InputStream. After this line executes, conin can be used to read input from the keyboard. 
  • Once you have created a Scanner, it is a simple matter to use it to read numeric input.
  • In general, a Scanner reads tokens from the underlying source that you specified when the Scanner was created. 
In general, to use Scanner, follow this procedure -
  1.  Determine if a specific type of input is available by calling one of Scanner’s hasNextX methods, where X is the type of data desired.
  2. If input is available, read it by calling one of Scanner’s nextX methods.
  3. Repeat the process until input is exhausted
IMPORTANT -
  • Scanner defines two sets of methods that enable you to read input. The first are the hasNextX methods.
  •  For example, calling hasNextInt( ) returns true only if the next token to be read is an integer.
  • If the desired data is available, then you read it by calling one of Scanner’s nextX methods.
  • To read the next integer, call nextInt( ).
Example -
Scanner conin = new Scanner(System.in);
int i;
// Read a list of integers.
while(conin.hasNextInt()) {
i = conin.nextInt();
// ...
}

 
Methods For Scanner Class -
Example -
Output - here is the sample run -
 By default, a Scanner splits input tokens along whitespace, but you can also specify your own delimiter pattern in the form of a regular expression: 
Example -
Output-