User Input/Output
User Input/Output
Taking Input:
To use the Scanner class, we need to import the java.util.Scanner package.
Now the Scanner class has been imported. We create an object of the Scanner class to use the methods within it.
The System.in is passed as a parameter and is used to take input.
Note: Your object can be named anything, there is no specific convention to follow. But we normally name our object sc for easy use and implementation.
There are four ways to create an object of the scanner class. Let us see how we can create Scanner objects:
A. Reading keyboard input:
B. Reading String input:
C. Reading input stream:
D. Reading File input:
So how does a Scanner class work?
The scanner object reads the entered inputs and divides the string into tokens. The tokens are usually divided based upon whitespaces and newline.
Example:
The above input will be divided as “Maxon”, “19”, “78.95” and “O”. Then the Scanner object will iterate over each token and then it will read each token depending upon the type of Scanner object created.
Now, we have seen how Scanner object is created, different ways to create it, how it reads input, and how it works.
Let us see different methods to take inputs.
Below are the methods that belong to the scanner class:
Method | Description |
nextLine() | Accepts string value |
next() | Accept string till whitespace |
nextInt() | Accepts int value |
nextFloat() | Accepts float value |
nextDouble() | Accepts double value |
nextLong() | Accepts long value |
nextShort() | Accepts short value |
nextBoolean() | Accepts Boolean value |
nextByte() | Accepts Byte value |
Example:
Output:
Entering the wrong type of input, or just messing up with the order of inputs in the above example will give an error.
For same example when we change the order of inputs it gives the following output:
Here we get an InputMismatchException.