Reading input in Java with Scanner

Ask the user for input with the Scanner class. With a simulated console where you type and the "program" responds.

Scanner es la forma más sencilla de leer lo que el usuario escribe por teclado. Se crea con new Scanner(System.in) y ofrece métodos como nextInt(), nextDouble(), next() (una palabra) y nextLine() (la línea entera).

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("¿Cómo te llamas? ");
        String nombre = sc.nextLine();
        System.out.print("¿Cuántos años tienes? ");
        int edad = sc.nextInt();
        System.out.println("Hola " + nombre + ", en 10 años tendrás " + (edad + 10));
        sc.close();
    }
}

Interactive console

Este es el programa de arriba, funcionando. Escribe tu respuesta y pulsa Enter (o el botón).

The classic bug: nextInt() then nextLine()

nextInt() lee el número pero deja el salto de línea (\n) sin consumir. El siguiente nextLine() lee ese \n vacío y parece que «se salta» la pregunta. Solución: un sc.nextLine() extra para limpiar, o usar siempre nextLine() y convertir con Integer.parseInt().

Validating input

Nunca confíes en lo que teclea el usuario. hasNextInt() te dice si lo siguiente es un entero antes de leerlo.

System.out.print("Introduce un número: ");
while (!sc.hasNextInt()) {
    System.out.print("Eso no es un número. Otra vez: ");
    sc.next();               // descarta lo que no sirve
}
int n = sc.nextInt();

Reading several values

Si el usuario escribe varios datos separados por espacios, puedes leerlos uno a uno con varias llamadas.

Scanner vs BufferedReader

Check what you've learned