> Java > java지도 시간 > 본문

Java의 NumberFormatException

WBOY
풀어 주다: 2024-08-30 16:14:14
원래의
656명이 탐색했습니다.

NumberFormatException은 사용자가 문자열을 숫자 값으로 변환하려고 할 때 발생하는 Java의 확인되지 않은 예외입니다. NumberFormatException은 Java.lang.NumberFormatException 패키지에 정의된 Java의 내장 클래스입니다. IllegalArgumentException 클래스는 확인되지 않은 예외이므로 NumberFormatException의 상위 클래스이므로 강제로 처리하고 선언할 필요가 없습니다. NumberFormatException은 입력 문자열의 형식이 불법이고 적절하지 않기 때문에 함수가 문자열을 정수, 부동 소수점, 이중 등과 같은 숫자 값으로 변환하거나 형식화(변환)할 수 없을 때 실제로 parsXXX() 함수에 의해 발생합니다. . 예를 들어, Java 프로그램에서는 명령줄 인수를 통해 사용자 입력이 문자열 형식의 텍스트 필드로 받아들여지는 경우가 있습니다. 그리고 이 문자열을 일부 산술 연산에 사용하려면 먼저 래퍼 클래스의 parsXXX() 함수를 사용하여 데이터 유형(특정 숫자 유형)으로 구문 분석하거나 변환해야 합니다.

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

NumberFormatException 클래스의 계층 구조는 다음과 같습니다.

객체 ->Throwable -> 예외 ->RuntimeException ->NumberFormatException.

구문

다음은 java.io에 대한 선언입니다. PrintWriter 클래스입니다.

public class NumberFormatException extends IllegalArgumentException implements Serializable
{
// Constructors of the NumberFormatException class
}
로그인 후 복사

위는 다음으로 확장되는 NumberFormatException의 구문입니다.

IllegalArgumentException class and implements Serializable
로그인 후 복사

Java에서 NumberFormatException이 어떻게 작동하나요?

문자열을 숫자로 변환하려고 하면 NumberFormatException이 발생합니다. 이러한 종류의 변환은 Integer.parseInt(), Float.parseFloat() 등과 같은 함수를 사용하여 수행됩니다. s가 문자열 유형이고 해당 값이 문자열 "30"인 Integer.parseInt(s) 함수를 호출한다고 가정하면 함수는 문자열 값을 int 30으로 올바르게 변환합니다. 그런데 무슨 일이 일어났나요? s의 값이 "30"으로 가정되는 경우(이는 불법입니다.) 함수가 실패하고 예외(NumberFormatException)가 발생합니다. 이 예외를 처리하기 위해 이에 대한 catch 블록을 작성할 수 있습니다. 예외가 처리되지 않으면 프로그램이 중단됩니다.

아래에서 볼 수 있듯이 NumberFormatException이 발생하는 데는 여러 가지 이유가 있습니다.

  • 변환하려고 제공된 문자열이 null일 수 있습니다. 예 :Integer.parseInt(null);
  • 제공된 문자열의 길이는 0일 수 있습니다. 예 :Integer.parseInt(“”);
  • 제공된 문자열에 숫자가 없을 수 있습니다. 예:Integer.parseInt(“Thirty”);
  • 제공된 문자열은 정수 값을 나타내지 않을 수 있습니다. 예 :Integer.parseInt(“FG67”);
  • T 제공된 문자열이 비어 있을 수 있습니다. 예 :Integer.parseInt(“”);
  • 제공된 문자열은 후행 공백일 수 있습니다. 예 :Integer.parseInt(“785”);
  • 제공된 문자열은 선행 공백일 수 있습니다. 예 :Integer.parseInt(" 785 ");
  • 제공된 문자열에는 영숫자가 포함될 수 있습니다. 예 :Long.parseLong(“F5”);
  • 제공된 문자열은 범위를 벗어나 지원되는 데이터 유형일 수 있습니다. 예: Integer.parseInt(“139”);
  • 제공된 문자열과 변환에 사용되는 함수는 데이터 유형이 다를 수 있습니다.예:Integer.parseInt(“3.56”);

건축자

  • NumberFormatException(): 이 생성자는 자세한 특정 메시지 없이 NumberFormatException을 생성합니다.
  • NumberFormatException(String s): 이 생성자는 특정 메시지를 자세히 포함하여 NumberFormatException을 생성합니다.

Java에서 NumberFormatException을 구현하는 예

아래는 구현 예입니다.

예시 #1

다음으로, PrintWriter 클래스 생성자를 사용하여 PrintWriter 객체를 생성하고 여기에 쓸 파일 이름을 전달하는 다음 예제를 통해 NumberFormatException을 더 명확하게 이해하기 위해 Java 코드를 작성합니다.

코드:

//package p1;
import java.util.Scanner;
public class Demo
{
public static void main( String[] arg) {
int age;
Scanner sc = new Scanner(System.in);
System.out.println("Please Enter your age : ");
//throws Exception as if the input string is of illegal format for parsing as it as null or alphanumeric.
age = Integer.parseInt(sc.next());
System.out.println("Your age is : " +age);
}
}
로그인 후 복사

출력:

사용자가 "25+"를 입력하면 위 코드의 출력은 다음과 같습니다.

Java의 NumberFormatException

사용자가 올바른 형식의 문자열 "25F"를 입력하지 않으면 다음과 같이 출력됩니다.

Java의 NumberFormatException

사용자가 문자열 "Twenty Five"를 입력하면 다음과 같이 출력됩니다.

Java의 NumberFormatException

사용자가 "null" 문자열을 입력하면 다음과 같이 출력됩니다.

Java의 NumberFormatException

사용자가 문자열 값을 부동 소수점 "40.78"로 입력하면 출력은 다음과 같습니다.

Java의 NumberFormatException

When the user enters a string “25”, which is a valid string. The output is:

Java의 NumberFormatException

Explanation: As in the above code, the age value is accepted from the user in string format, which further converts into the integer format by using the Integer.parseInt(sc.next()) function. While the user an illegal input string or not a well-formatted string, the NumberFormatException occurs, it throws, and the program terminates unsuccessfully. So to provide the valid string, it should be taken care that an input string should not be null, check an argument string matches the type of the conversion function used and also check if any unnecessary spaces are available; if yes, then trim it and so all care must be taken.

Example #2

Next, we write the java code to understand the NumberFormatException where we generate the NumberFormatException and handle it by using the try-catch block in the program, as below –

Code:

//package p1;
import java.util.Scanner;
public class Demo
{
public static void main( String[] arg) {
int age;
Scanner sc = new Scanner(System.in);
try
{
System.out.println("Please Enter your age : ");
//throws Exception as if the input string is of illegal format for parsing as it as null or alphanumeric.
age = Integer.parseInt(sc.next());
System.out.println("Your age is : " +age);
} catch(NumberFormatException e)
{
System.out.println("The NumberFormatExceptionoccure.");
System.out.println("Please enter the valid age.");
}
}
}
로그인 후 복사

When the user enters a string “23F”, the output is:

Java의 NumberFormatException

When a user enters a string “23”, the output is:

Java의 NumberFormatException

Explanation: As in the above code try-catch block is used. It is always a good practice to enclose lines of code that can throw an exception in a try-catch block by which it handles the NumberFormatException and prevents it from generating the Exception.

Conclusion

The NumberFormatException in java is an unchecked exception that occurs when a not well-formatted string is trying to converts into a numeric value by using the parseXXX() functions. The NumberFormatException is a built-in class in which is defined in the Java.lang.NumberFormatException package.

위 내용은 Java의 NumberFormatException의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!