CodeGym /Blog Java /Random-ES /NumberFormatException en Java
Autor
Alex Vypirailenko
Java Developer at Toshiba Global Commerce Solutions

NumberFormatException en Java

Publicado en el grupo Random-ES

¿Qué es NumberFormatException en Java?

"La NumberFormatException se lanza en la conversión de una cadena no numérica a un número".
En pocas palabras, si una cadena no contiene solo datos numéricos e intenta convertirla en un número, encontrará esta excepción. Esto también se puede interpretar de otra manera. La excepción se usa como indicador si la conversión de String a un número no es posible. El número puede ser un número entero, flotante o decimal según sus requisitos. Por ejemplo, si la cadena de entrada contiene todas las letras, caracteres alfanuméricos o caracteres especiales y trata de intentar una conversión de cadena a entero , se lanzará una NumberFormatException.

Ejemplo

Veamos un ejemplo sencillo para entender esto.

import java.util.Date;

public class NumberFormatExceptionTestDriver {

	public static void main(String[] args) {

		try {
			// a valid Integer number in the input String
			String inputString = "2550";
			System.out.println("Integer.pareseInt(" + inputString + ") = " + Integer.parseInt(inputString));
		} catch (NumberFormatException e) {
			// java.lang.NumberFormatException will be thrown if the  
			// input string can not be converted to a valid integer
			System.out.println("\nNumberFormatException thrown! " + e.getMessage());
		}

		try {
			// a floating number in the input String
			// use Float.parseFloat(inputString) to avoid this exception
			String inputString = "255.0"; 
			System.out.println("Integer.pareseInt(" + inputString + ") = " + Integer.parseInt(inputString));
		} catch (NumberFormatException e) {
			System.out.println("\nNumberFormatException thrown! " + e.getMessage());
		}

		try {
			Date day = new Date();
			// date containing alpha-numeric data in the input string
			String inputString = day.toString();
			System.out.println("Integer.pareseInt(" + inputString + ") = " + Integer.parseInt(inputString));
		} catch (NumberFormatException e) {
			System.out.println("\nNumberFormatException thrown! " + e.getMessage());
		}

		try {
			// numbers with spaces in the input string
			String inputString = "1 2 3";
			System.out.println("Integer.pareseInt(" + inputString + ") = " + Integer.parseInt(inputString));
		} catch (NumberFormatException e) {
			System.out.println("\nNumberFormatException thrown! " + e.getMessage());
		}

		try {
			// all letters in the input string
			String inputString = "Lubaina Khan";
			System.out.println("Integer.pareseInt(" + inputString + ") = " + Integer.parseInt(inputString));

		} catch (NumberFormatException e) {
			System.out.println("\nNumberFormatException thrown! " + e.getMessage());
		}
	}
}

Producción

Integer.pareseInt(2550) = 2550 NumberFormatException lanzado! Para la cadena de entrada: "255.0" ¡Lanzado NumberFormatException! Para la cadena de entrada: "Mié. 11 de agosto 08:18:21 PKT 2021" ¡Lanzado NumberFormatException! Para la cadena de entrada: "1 2 3" ¡Lanzado NumberFormatException! Para cadena de entrada: "Lubaina Khan"

Conclusión

Esperamos que comprenda por qué surge NumberFormatException en Java. Si ha entendido la causa raíz, siempre puede identificar la razón y rectificarla. Si aún no tienes claro este concepto, comete más errores y aprenderás los porqués y los cómos de este problema. Hasta entonces sigue creciendo y sigue aprendiendo.
Comentarios
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION