Use Scanner to get a Valid Integer from console in Java

Description

The following code shows how to use Scanner to get a Valid Integer from console.

Example


/* w  ww  . j a v a  2  s  .  c  om*/
import java.util.InputMismatchException;
import java.util.Scanner;

public class Main {
  static Scanner sc = new Scanner(System.in);

  public static void main(String[] args) {
    System.out.print("Enter an integer: ");
    int i = GetInteger();
    System.out.println("You entered " + i);
  }

  public static int GetInteger() {
    while (true) {
      try {
        return sc.nextInt();
      } catch (InputMismatchException e) {
        sc.next();
        System.out.print("That's not " + "an integer. Try again: ");
      }
    }
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    I/O »




Binary File
Byte Array
CharSet
Checksum
Console
Create Copy Move Delete
Directory
Drive
Encode Decode
File Attribute
File Lock
File System
GZIP
Jar File
NIO Buffer
Path
Scanner
StreamTokenizer
Temporary File
Text File
Zip