Java Scanner User Input Example

How to use the Java Scanner for user input

The Java Scanner class is a simple, versatile, easy to use class that makes user input in Java relatively straight forward.

To perform user input with the Scanner class, follow these steps:

  1. Create an instance of the Scanner with the new keyword
  2. Specify the System.in as the argument for the Scanner constructor
  3. Optionally set a delimiter other than the enter key
  4. Use one of the Scanner’s nextXxx methods to convert user input into the appropriate type
  5. Use the Java user input in your program

Java Scanner import example

Found in the java.util package, Java’s Scanner class can read input from the command line and return it as a String, BigDecimal or any one of Java’s 8 primitive types.

To use the Java Scanner class, you must either:

  • import java.util.Scanner
  • import java.util.*;
  • reference package and class name, java.util.Scanner, in your code
java scanner example usage

To use the Java Scanner for user input, either import the java.util package, or use the full package and class name: java.util.Scanner.

For the most part, Java’s Scanner class is fairly easy to use, as the methods are largely self explanatory.

Examples of straight-forward Scanner methods to get data such as floats, doubles or text include:

  • nextInt()
  • nextByte()
  • nextLong()
  • nextFloat()
  • nextDouble()
  • nextLine()
  • and just plain next()

Java Scanner String example

One thing I don’t like about Java’s Scanner class, especially if it’s being used to teach Java to novice programmers, is that it introduces several advanced concepts in order for it to be used, namely:

  • import statements, as the java.util package must be imported
  • the new keyword, as an instance of the Scanner must be instantiated

But if those two advanced topics don’t intimidate the user, user input with Java’s Scanner class is a lead-pipe cinch.

import java.util.Scanner;
public class ScannerUserInput {
  public static void main(String[] args) {
    // Java Scanner String input example
    System.out.println("What is your name?");
    Scanner scanner = new Scanner(System.in);
    String name = scanner.nextLine();
    System.out.println(name + " is a nice name!");

  }
}

In this example of how to use Java’s Scanner for user input, you can see the import statement at the start of the code, along with the creation of an instance of the Scanner with the new keyword.

Java User Input Made Easy

Learn the easiest ways to handle user input in Java, and format any console output with printf.

The import can optionally be removed if Java’s Scanner class has the package referenced explicitly.

Java Scanner int example

The following example of Java user input with the Scanner class avoids having to use an import statement.

// Java Scanner int input example
System.out.println("What is your age?");
java.util.Scanner scanner = new java.util.Scanner(System.in);
int age = scanner.nextInt();
System.out.println("I remember being " + age + " years old!" );

// Java Scanner String input example
System.out.println("Where were you born?");
String city = scanner.nextLine();
System.out.println("I hope to visit " + city + " some day." );

The above example also demonstrates how one instance of the Scanner class can be used multiple times within the same program. It does not need to be instantiated with the new keyword each time it gets used.

Java Scanner hasNext() example

To continually grab input from the user, the Scanner’s hasNext() method can be used as the condition for a while loop.

This will cause the program to continually take input from the user until the program either shuts down, or a break statement is encountered.

Here’s a Scanner hasNext() example that adds numbers until the total sum exceeds 100.

System.out.println("Enter some numbers to add: ");
Scanner scanner = new Scanner(System.in);
int count = 0;
while (scanner.hasNext()) {
  count = count + scanner.nextInt();
  System.out.println(count);
  if (count > 100) {
    System.out.println("Max exceeded!");
    break;
  }
}

Java Scanner delimiter example

By default, the scanner uses the enter key to indicate the user has finished their user input. But this can be changed by through the use of the useDelimiter() method.

The following Scanner example takes a String of comma separated values (CSVs) and prints them out one at a time.

The text String is passed to the Scanner’s constructor, after which the delimiter is changed to a comma.

import java.util.Scanner;
public class Main {
  public static void main(String[] args) {
    String csv = "a,b,c,d,e";
    Scanner scanner = new Scanner(csv);
    scanner.useDelimiter(",");
    while (scanner.hasNext()) {
      System.out.println(scanner.next());
    }
  }
}

When this Java Scanner example runs, the output is:

a
b
c
d
e

Notice that the commas in the original text String are ignored.

Java Scanner char input example

Interestingly, the Java Scanner char input is not supported with through a defined method in the Scanner class.

However, it is possible to have a Scanner input one char at a time through the use of the delimiter setting and the Scanner’s hasNext() method.

The following example takes char input with the Scanner

import java.util.Scanner;
public class NextCharScanner{
  
  // Java Scanner char input example
  public static void main(String[] args) {
    System.out.println("Provide the Java Scanner char input: "); 
    Scanner charScanner = new Scanner(System.in); 
    charScanner.useDelimiter("");
    while (charScanner.hasNext()) {
      char name = charScanner.next().charAt(0);
      if (name == '\n') {
        return;
      }
    }
  }
}

Java Scanner vs Console for user input

The easiest way to garner input from the user in a Java program is through the Console class.

But Java’s Console class has two big disadvantages:

  • It does not work in IDEs like Eclipse
  • It can only return user input as a String

A more versatile approach to Java user input is the Scanner class.

And those are the ins and outs on how to use the Java Scanner for user input.

 

SearchAppArchitecture
SearchSoftwareQuality
SearchCloudComputing
SearchSecurity
SearchAWS
Close