Java – Scanner class and Getting User Input using Java




Java Tutorial for Beginners
Java Tutorial for Beginners

Java Scanner class

  • Java Scanner class simplifies console input. It can be used to read from files and Strings (among other sources).
  • It also can be used for powerful pattern matching – we will not cover pattern matching in this class.
  • Scanner is in the Java.util package. So you must: import java.util.Scanner;

 

Creating Scanner objects

  • We can create a Scanner object by invoking several different constructors.
    • Scanner(File source)
      Constructs a new Scanner that produces values scanned from the specified file.
    • Scanner(InputStream source)
      Constructs a new Scanner that produces values scanned from the specified input stream.
    • Scanner(Readable source)
      Constructs a new Scanner that produces values scanned from the specified source.
    • Scanner(String source)
      Constructs a new Scanner that produces values scanned from the specified string.

 

 

Scanner class

  • The Scanner class basically parses input from the source into tokens by using delimiters to identify the token boundaries.
  • The default delimiter is whitespace:
    • [ \t\n\x0B\f\r]

 

System’s static fields

  • static PrintStream err
    The “standard” error output stream.
  • static InputStream in
    The “standard” input stream.
  • static PrintStream out
    The “standard” output stream.
  • Remember: You have been using System.out since your first “Hello World” program.
  • Now we see System.in is an InputStream

 

Scanner

  • Scanner will read a line of input from its source (our examples will be from System.in but we have already seen other sources are possible)
  • Example:

 

/*************************************************************************
 * Getting User Input using Java Example
 *
 *************************************************************************/

import java.util.Scanner;
public class MyClass {
	public static void main(String[] args) {
		Scanner scan = new Scanner (System.in);
		System.out.println("Enter some String : ");
		String user_input_string = scan.nextLine();
		System.out.println("Enter some Number : ");
		long user_input_Long =scan.nextLong();
		System.out.println("\nThe entered String is");
		System.out.print(user_input_string);
		System.out.println("\nThe entered Number is");
		System.out.print(user_input_Long);
	}
}

OUTPUT:

Enter some String :
Mark
Enter some Number :
25

The entered String is
Mark
The entered Number is
25

 

  • This example reads a single int from System.in and outputs it to System.out. It does not check that the user actually entered an int.

 

Next Methods

String next()
Finds and returns the next complete token from this scanner.

boolean nextBoolean()
Scans the next token of the input into a boolean value and returns that value.

byte nextByte()
Scans the next token of the input as a byte.

double nextDouble()
Scans the next token of the input as a double.

float nextFloat()
Scans the next token of the input as a float.

int nextInt()
Scans the next token of the input as an int.

String nextLine()
Advances this scanner past the current line and returns the input that was skipped.

long nextLong()
Scans the next token of the input as a long.

short nextShort()
Scans the next token of the input as a short.

 

InputMismatchExceptions

  • InputMismatchException: This exception can be thrown if you try to get the next token using a next method that does not match the type of the token

 

hasNext methods

boolean hasNext()
Returns true if this scanner has another token in its input.

boolean hasNextBoolean()
Returns true if the next token in this scanner’s input can be interpreted as a boolean value using a case insensitive pattern created from the string “true|false”.

boolean hasNextByte()
Returns true if the next token in this scanner’s input can be interpreted as a byte value in the default radix using the nextByte() method.

boolean hasNextDouble()
Returns true if the next token in this scanner’s input can be interpreted as a double value using the nextDouble() method.

boolean hasNextFloat()
Returns true if the next token in this scanner’s input can be interpreted as a float value using the nextFloat() method.

boolean hasNextInt()
Returns true if the next token in this scanner’s input can be interpreted as an int value in the default radix using the nextInt() method.

BooleanhasNextLine()
Returns true if there is another line in the input of this scanner.

boolean hasNextLong()
Returns true if the next token in this scanner’s input can be interpreted as a long value in the default radix using the nextLong() method.

boolean hasNextShort()
Returns true if the next token in this scanner’s input can be interpreted as a short value in the default radix using the nextShort() method.

 

Another example

Scanner sc = new Scanner (System.in);

System.out.print ("Enter first int: ");

while (sc.hasNextInt())

{

int i = sc.nextInt();

System.out.println("You entered " + i);

System.out.print ("Enter another int: ");

}

 

Scanner

  • The Scanner class has more powerful abilities. For example, you can:
    • Change the delimiters
    • Use regular expressions
    • Read input in different radixes (radices or bases)

Partner Sites

VideoToGifs.com

EasyOnlineConverter.com

SqliteTutorials.com





Be the first to comment

Leave a Reply

Your email address will not be published.


*