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+"를 입력하면 위 코드의 출력은 다음과 같습니다.
사용자가 올바른 형식의 문자열 "25F"를 입력하지 않으면 다음과 같이 출력됩니다.
사용자가 문자열 "Twenty Five"를 입력하면 다음과 같이 출력됩니다.
사용자가 "null" 문자열을 입력하면 다음과 같이 출력됩니다.
사용자가 문자열 값을 부동 소수점 "40.78"로 입력하면 출력은 다음과 같습니다.
When the user enters a string “25”, which is a valid string. The output is:
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:
When a user enters a string “23”, the output is:
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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

이 기사에서는 Java 프로젝트 관리, 구축 자동화 및 종속성 해상도에 Maven 및 Gradle을 사용하여 접근 방식과 최적화 전략을 비교합니다.

이 기사에서는 Maven 및 Gradle과 같은 도구를 사용하여 적절한 버전 및 종속성 관리로 사용자 정의 Java 라이브러리 (JAR Files)를 작성하고 사용하는 것에 대해 설명합니다.

이 기사는 카페인 및 구아바 캐시를 사용하여 자바에서 다단계 캐싱을 구현하여 응용 프로그램 성능을 향상시키는 것에 대해 설명합니다. 구성 및 퇴거 정책 관리 Best Pra와 함께 설정, 통합 및 성능 이점을 다룹니다.

이 기사는 캐싱 및 게으른 하중과 같은 고급 기능을 사용하여 객체 관계 매핑에 JPA를 사용하는 것에 대해 설명합니다. 잠재적 인 함정을 강조하면서 성능을 최적화하기위한 설정, 엔티티 매핑 및 모범 사례를 다룹니다. [159 문자]

Java의 클래스 로딩에는 부트 스트랩, 확장 및 응용 프로그램 클래스 로더가있는 계층 적 시스템을 사용하여 클래스로드, 링크 및 초기화 클래스가 포함됩니다. 학부모 위임 모델은 핵심 클래스가 먼저로드되어 사용자 정의 클래스 LOA에 영향을 미치도록합니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

WebStorm Mac 버전
유용한 JavaScript 개발 도구

맨티스BT
Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

SublimeText3 Linux 새 버전
SublimeText3 Linux 최신 버전

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기
