Ayush Agarwal
Ayush Agarwal's Blog

Ayush Agarwal's Blog

Taking Input In Java - The Scanner Class!!

Taking Input In Java - The Scanner Class!!

Ayush Agarwal's photo
Ayush Agarwal

Published on Dec 4, 2020

3 min read

Subscribe to my newsletter and never miss my upcoming articles

The Java Scanner class breaks the input into tokens using a delimiter that id whitespace by default. Scanner class permits to read and parse various values.

Syntax to use Scanner class: " import java.util.Scanner; " (Write this at the top of the program)

Sample Code to understand the Scanner Class:

import java.util.Scanner; // Using the Scanner class to take input
class MultiplyTwoNumbers{
   public static void main(String[] args){

      int a,b,c;
      // Create a Scanner
      Scanner s=new Scanner(System.in);
      // Take input of two numbers
10 5

Here we have used "nextInt()", which is used to take integer inputs. Similarly we have different methods to take different types of input.

Let us see how we can do that:

  1. nextBoolean() - Reads a boolean value
  2. nextByte() - Reads a byte value
  3. nextDouble() - Reads a double value
  4. nextFloat() - Reads a float value
  5. nextInt() - Reads a integer value (as we have used in the above example)
  6. nextLine() - Reads a String value
  7. nextLong() - Reads a long value
  8. nextShort() - Reads a short value

Note: If you enter wrong input (e.g. String in a numerical input), you will get an exception/error message (like "InputMismatchException").

So, this was all about the Scanner Class and taking input in Java. To learn and understand more try and practice some other methods for different input types.

See you in the next blog next Friday!! Also check out my other Java Blogs to understand few more concepts.

Share this