Scanner Class in java to get user input | java.util.Scanner

The Scanner class is part of the java.util class library. and it is used to get user input

java.util.Scanner

java.util.Scanner is a class in the Java API used to create a Scanner object, an extremely versatile object that you can use to input alphanumeric characters from several input sources and convert them to binary data.

The Scanner Class

The scanner class is a simple text scanner for reading input values of primitive types or input strings. It breaks its input into tokens using its delimiter(s), which are white space characters (space, tab, newline) unless specified otherwise. These tokens may be converted to into values of the appropriate types.

Example Using the Scanner class

import java.util.Scanner;
public class TellMeAboutYou
{
 public static void main(String[] args)
 {
 int age;
 String name;

 Scanner scan = new Scanner(System.in);

 System.out.print("Enter your name");
 name = scan.nextLine();

 System.out.print("Enter your age");
 age = scan.nextInt();

 System.out.println("Pleased to meet you, " + name + "!");
 System.out.println("Your age in dog years: " + age*10.5);
 }
}

Scanner class Constructors:

Scanner(InputStream source)
Scanner(File source)
Scanner(String source)
Creates a Scanner object to scan (read) values from the specified source.
e.g., Scanner console = new Scanner(System.in);

Scanner class Selected Methods:

String nextLine( )

Reads and returns the next line of input as a string. (Specifically, it reads and returns all the remaining characters on the line as a character string, and then moves to the next line)

String next()

Reads and returns the next input token as a character string

double nextDouble()

Reads and returns a double value. If the next token cannot be translated to a
double, throws InputMismatchException.

int nextInt()

Reads and returns an int value. If the next token cannot be translated to an int, throws InputMismatchException

boolean hasNextLine()

Returns true if there is another line of input. Does not read past the line.

boolean hasNext()

Returns true if there is another token. Does not read past the token

boolean hasNextDouble()

Returns true if there is another token that can be translated as a double. Does not read past the token.

boolean hasNextInt()

Returns true if there is another token that can be translated as a int. Does not read past the token.

Leave a Comment