En este tutorial, aprenderemos sobre Java Scanner y sus métodos con la ayuda de ejemplos.
La Scannerclase del java.utilpaquete se usa para leer datos de entrada de diferentes fuentes como flujos de entrada, usuarios, archivos, etc. Tomemos un ejemplo.
Ejemplo 1: leer una línea de texto con el escáner
import java.util.Scanner; class Main ( public static void main(String() args) ( // creates an object of Scanner Scanner input = new Scanner(System.in); System.out.print("Enter your name: "); // takes input from the keyboard String name = input.nextLine(); // prints the name System.out.println("My name is " + name); // closes the scanner input.close(); ) )
Salida
Ingrese su nombre: Kelvin Mi nombre es Kelvin
En el ejemplo anterior, observe la línea
Scanner input = new Scanner(System.in);
Aquí, hemos creado un objeto de Scannerentrada con nombre.
El System.inparámetro se utiliza para tomar la entrada de la entrada estándar. Funciona igual que recibir entradas del teclado.
Luego usamos el nextLine()método de la Scannerclase para leer una línea de texto del usuario.
Ahora que tiene una idea Scanner, exploremos más al respecto.
Importar clase de escáner
Como podemos ver en el ejemplo anterior, necesitamos importar el java.util.Scannerpaquete antes de poder usar la Scannerclase.
import java.util.Scanner;
Para obtener más información sobre la importación de paquetes, visite Paquetes Java.
Crear un objeto de escáner en Java
Una vez que importamos el paquete, así es como podemos crear Scannerobjetos.
// read input from the input stream Scanner sc1 = new Scanner(InputStream input); // read input from files Scanner sc2 = new Scanner(File file); // read input from a string Scanner sc3 = new Scanner(String str);
Aquí, hemos creado objetos de la Scannerclase que leerán la entrada de InputStream, File y String respectivamente.
Métodos de Java Scanner para tomar entradas
La Scannerclase proporciona varios métodos que nos permiten leer entradas de diferentes tipos.
| Método | Descripción |
|---|---|
nextInt() | lee un intvalor del usuario |
nextFloat() | lee un floatvalor del usuario |
nextBoolean() | lee un booleanvalor del usuario |
nextLine() | lee una línea de texto del usuario |
next() | lee una palabra del usuario |
nextByte() | lee un bytevalor del usuario |
nextDouble() | lee un doublvalor e del usuario |
nextShort() | lee un shortvalor del usuario |
nextLong() | lee un longvalor del usuario |
Ejemplo 2: NextInt () de Java Scanner
import java.util.Scanner; class Main ( public static void main(String() args) ( // creates a Scanner object Scanner input = new Scanner(System.in); System.out.println("Enter an integer: "); // reads an int value int data1 = input.nextInt(); System.out.println("Using nextInt(): " + data1); input.close(); ) )
Salida
Ingrese un número entero: 22 Usando nextInt (): 22
En el ejemplo anterior, hemos utilizado el nextInt()método para leer un valor entero.
Ejemplo 3: Java Scanner nextDouble ()
import java.util.Scanner; class Main ( public static void main(String() args) ( // creates an object of Scanner Scanner input = new Scanner(System.in); System.out.print("Enter Double value: "); // reads the double value double value = input.nextDouble(); System.out.println("Using nextDouble(): " + value); input.close(); ) )
Salida
Ingrese el valor Double: 33.33 Usando nextDouble (): 33.33
En el ejemplo anterior, hemos utilizado el nextDouble()método para leer un valor de punto flotante.
Ejemplo 4: Java Scanner next ()
import java.util.Scanner; class Main ( public static void main(String() args) ( // creates an object of Scanner Scanner input = new Scanner(System.in); System.out.print("Enter your name: "); // reads the entire word String value = input.next(); System.out.println("Using next(): " + value); input.close(); ) )
Salida
Ingrese su nombre: Jonny Walker Usando siguiente (): Jonny
En el ejemplo anterior, hemos utilizado el next()método para leer una cadena del usuario.
Aquí, hemos proporcionado el nombre completo. Sin embargo, el next()método solo lee el nombre.
Esto se debe a que el next()método lee la entrada hasta el carácter de espacio en blanco . Una vez que se encuentra el espacio en blanco , devuelve la cadena (excluyendo el espacio en blanco).
Ejemplo 5: Java Scanner nextLine ()
import java.util.Scanner; class Main ( public static void main(String() args) ( // creates an object of Scanner Scanner input = new Scanner(System.in); System.out.print("Enter your name: "); // reads the entire line String value = input.nextLine(); System.out.println("Using nextLine(): " + value); input.close(); ) )
Salida
Ingrese su nombre: Jonny Walker Usando nextLine (): Jonny Walker
En el primer ejemplo, usamos el nextLine()método para leer una cadena del usuario.
A diferencia next(), el nextLine()método lee toda la línea de entrada, incluidos los espacios. El método se termina cuando encuentra un carácter siguiente línea, .
Recommended Reading: Java Scanner skipping the nextLine().
Java Scanner with BigInteger and BigDecimal
Java scanner can also be used to read the big integer and big decimal numbers.
- nextBigInteger() - reads the big integer value from the user
- nextBigDecimal() - reads the big decimal value from the user
Example 4: Read BigInteger and BigDecimal
import java.math.BigDecimal; import java.math.BigInteger; import java.util.Scanner; class Main ( public static void main(String() args) ( // creates an object of Scanner Scanner input = new Scanner(System.in); System.out.print("Enter a big integer: "); // reads the big integer BigInteger value1 = input.nextBigInteger(); System.out.println("Using nextBigInteger(): " + value1); System.out.print("Enter a big decimal: "); // reads the big decimal BigDecimal value2 = input.nextBigDecimal(); System.out.println("Using nextBigDecimal(): " + value2); input.close(); ) )
Output
Enter a big integer: 987654321 Using nextBigInteger(): 987654321 Enter a big decimal: 9.55555 Using nextBigDecimal(): 9.55555
In the above example, we have used the java.math.BigInteger and java.math.BigDecimal package to read BigInteger and BigDecimal respectively.
Working of Java Scanner
La Scannerclase lee una línea completa y divide la línea en fichas. Los tokens son pequeños elementos que tienen algún significado para el compilador de Java. Por ejemplo,
Supongamos que hay una cadena de entrada:
He is 22
En este caso, el objeto del escáner leerá la línea completa y dividirá la cadena en tokens: " Él ", " es " y " 22 ". El objeto luego itera sobre cada token y lee cada token usando sus diferentes métodos.
Nota : De forma predeterminada, se utilizan espacios en blanco para dividir tokens.








