Home » Core Java » util » Scanner » java.util.Scanner Example

About Armando Flores

Armando Flores
Armando graduated from from Electronics Engineer in the The Public University Of Puebla (BUAP). He also has a Masters degree in Computer Sciences from CINVESTAV. He has been using the Java language for Web Development for over a decade. He has been involved in a large number of projects focused on "ad-hoc" Web Application based on Java EE and Spring Framework.

java.util.Scanner Example

In this example, we will show the range of functionality provided by the java.util.Scanner class. A simple text scanner which can parse primitive types and strings using regular expressions.

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

The resulting tokens may then be converted into values of different types using the various next methods.

For example, this code allows a user to read a number from System.in:

    Scanner sc = new Scanner(System.in);
    int i = sc.nextInt();

The scanner can also use delimiters other than whitespace. This example reads several items in from a string:

    String input = "1 fish 2 fish red fish blue fish";
    Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
    System.out.println(s.nextInt());
    System.out.println(s.nextInt());
    System.out.println(s.next());
    System.out.println(s.next());
    s.close();

The following code shows you how you can use the Scanner class to read input form the console. To start, you create a Scanner object passing System.in (which is the keyboard) as a parameter to the Constructor. Like the System.out object, the System.in object is created by Java automatically. Because of that, you can use this object with a Scanner object whenever you want to get console input.

Once you’ve created a Scanner object, you can use the next methods to read data from the console. The method you use depends on the type of data you need to read. To read string data, for example, you use the next method. To read integer data, you use the nextInt method. To read double data, you use the the nextDouble method. And to read all of the data on a line, you use the nextLine method. When one of the methods of the Scanner class is run, the application waits for the user to enter data with the keyboard. To complete the entry, the user presses the Enter key.

Since the Scanner class is in the java.util package, you’ll want to include an import statement whenever you use this class.

1. Example of java.util.Scanner class

JavaUtilScannerExample.java

package com.javacodegeeks.examples;

import java.util.Scanner;

public class JavaUtilScannerExample {

	public static void main(String[] args) {
		// Create a Scanner object
		try (Scanner scanner = new Scanner(System.in)) {

			// Read values from Console

			// A String value
			System.out.print("Enter Item Code: ");
			String itemCode = scanner.next();

			// A double value
			System.out.print("Enter Price: ");
			double price = scanner.nextDouble();

			// An int value
			System.out.print("Enter Quantity: ");
			int quantity = scanner.nextInt();

			// Display entered values
			double total = price * quantity;
			System.out.println();
			System.out.printf("%d %s @ %f = %f", quantity, itemCode, price, total);

			// Read three int values
			System.out.printf("Enter three integer values: ");
			int i1 = scanner.nextInt();
			int i2 = scanner.nextInt();
			int i3 = scanner.nextInt();
			
			// Calculate the average and display the result
			int avg = (i1 + i2 + i3) / 3;
			
			System.out.printf("Average: %d", avg);
		} catch (Exception e) {
			e.printStackTrace(System.err);
		}
	}
}

Let’s explain the methods used in the above example.

  • public Scanner(InputStream source) – Constructs a new Scanner that produces values scanned from the specified input stream. Bytes from the stream are converted into characters using the underlying platform’s default charset.
  • public String next() – Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.
  • public double nextDouble() – Scans the next token of the input as a double. This method will throw InputMismatchException if the next token cannot be translated into a valid double value. If the translation is successful, the scanner advances past the input that matched.
  • public int nextInt() – Scans the next token of the input as an int.

If we run the above code, we will get the following results:

Enter Item Code: 1
Enter Price: 10
Enter Quantity: 5

5 1 @ 10.000000 = 50.000000

Enter three integer values: 1 2 3
Average: 2

2. Common use of java.util.Scanner class

A common programming task involves parsing a string of text into words or “tokens” that are separated by some set of delimiter characters, such as spaces or commas.

ScannerTokenizingText.java

package com.javacodegeeks.examples;

import java.util.Scanner;

public class ScannerTokenizingText {
	@SuppressWarnings("resource")
	public static void main(String[] args) {
		String text = "4231, Java Programming, 1000.00";
		
		Scanner scanner = new Scanner(text).useDelimiter("\\s*,\\s*");
		int checkNumber = scanner.nextInt();
		String description = scanner.next();
		float amount  = scanner.nextFloat();
		
		System.out.printf("/***** Tokenizing Text *****/\n\n");
		
		System.out.printf("String to tokenize: %s\n", text);
		System.out.printf("checkNumber: %d\n", checkNumber);
		System.out.printf("description: %s\n", description);
		System.out.printf("amount: %f", amount);
	}
}

Let’s explain the methods used in the above example.

  • public float nextFloat() – Scans the next token of the input as a float. This method will throw InputMismatchException if the next token cannot be translated into a valid float value as described below. If the translation is successful, the scanner advances past the input that matched.
  • public Scanner useDelimiter(String pattern) – Sets this scanner’s delimiting pattern to a pattern constructed from the specified String. An invocation of this method of the form useDelimiter(pattern) behaves in exactly the same way as the invocation useDelimiter(Pattern.compile(pattern)). Invoking the reset() method will set the scanner’s delimiter to the default.

If we run the above code, we will get the following results:

/***** Tokenizing Text *****/

String to tokenize: 4231, Java Programming, 1000.00
checkNumber: 4231
description: Java Programming
amount: 1000.000000

3. Not so common use of java.util.Scanner class

The java.util.Scanner provides a single API for not only parsing indi‐ vidual primitive types from strings, but reading them from a stream of tokens.

The Scanner API is smarter and can use Locales to parse numbers in specific languages with more elaborate conventions. You can specify a Locale other than the default with the useLocale() method.

JavaNetURLMoreMethodsExample.java

package com.javacodegeeks.examples;

import java.util.InputMismatchException;
import java.util.Locale;
import java.util.Scanner;

public class ScannerUncommonUses {
	@SuppressWarnings("resource")
	public static void main(String[] args) {

		// Parsing primitive numbers
		boolean bl = new Scanner("false").nextBoolean();
		byte b = new Scanner("16").nextByte();
		int n = new Scanner("42").nextInt();
		long l = new Scanner("99999999999").nextLong();
		float f = new Scanner("4.2").nextFloat();
		double d = new Scanner("99.99999999").nextDouble();

		System.out.printf("/***** Parsing primitive numbers *****/\n\n");
		System.out.printf("boolean: %b\n", bl);
		System.out.printf("byte: %d\n", b);
		System.out.printf("int: %d\n", n);
		System.out.printf("long: %d\n", l);
		System.out.printf("float: %f\n", f);
		System.out.printf("double: %f\n\n", d);

		// Using Locale to parse numbers in specific languages
		try {
			double doubleLocale = new Scanner("1.234,56").useLocale(
					Locale.ITALIAN).nextDouble();

			System.out.printf("/***** Using Locales to parse numbers in specific languages *****/\n\n");
			System.out.printf("double (Locale = Italy): %f", doubleLocale);
		} catch (InputMismatchException ime) {
			ime.printStackTrace(System.err);
		}
	}
}

Let’s explain the methods used in the above example.

If we run the above code, we will get the following results:

/***** Parsing primitive numbers *****/

boolean: false
byte: 16
int: 42
long: 99999999999
float: 4.200000
double: 100.000000

/***** Using Locales to parse numbers in specific languages *****/

double (Locale = Italy): 1234.560000

4. Download the source code

You can download the source code of this example from here: JavaUtilScannerClass.zip

(0 rating, 2 votes)
1 Comment Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
narisip Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
narisip
Guest

what is this,,,,,, still not understanding everybody!!!!