Java오류 Numberformatexception for Input String수정

Haider Ali 2023년10월12일
  1. Java의 예외
  2. Java에서 입력 문자열에 대한 numberformatexception 처리
Java오류 Numberformatexception for Input String수정

이 가이드는 Java에서 입력 문자열에 대한 numberformatexception을 방지하는 방법을 알려줍니다. 이를 완전히 이해하려면 Java에서 예외 처리의 몇 가지 기본 사항을 따라가야 합니다. 좀 더 자세히 살펴보겠습니다.

Java의 예외

예외는 일부 조건을 처리하는 데 사용되는 클래스입니다. 이 클래스와 그 하위 클래스는 응용 프로그램을 만드는 동안 잡아야 하는 특정 조건을 나타내는 Throwable 형식입니다.

일반적으로 두 가지 유형의 예외가 표시됩니다. 확인된 예외 및 확인되지 않은 예외로 알려져 있습니다.

확인된 예외는 컴파일 타임 예외 아래에 있는 반면 확인되지 않은 예외는 RuntimeException 아래에 있습니다. 프로그래머는 예외 클래스에서 확장하여 사용자 정의 예외를 만들 수 있습니다.

여기 예외에 대해 자세히 알아보십시오.

Java에서 입력 문자열에 대한 numberformatexception 처리

일반적으로 try...catch 메서드를 사용하여 예외를 처리합니다. Java의 입력 문자열에 대한 numberformatexception은 동일합니다.

문자열을 입력으로 보내고 정수로 구문 분석할 때 numberformatexception이 발생해야 합니다. try...catch 방법을 사용하여 오류를 전달하면 오류를 피할 수 있습니다.

다음 자체 설명 코드를 살펴보십시오.

import java.util.*;
public class Main {
  public static void main(String args[]) {
    String var = "N/A";

    // When String is not an integer. It must throw NumberFormatException
    // if you try to parse it to an integer.
    // we can avoid from Exception by handling Exception.
    // Exception Is usually Handle by try Catch Block.
    try {
      int i = Integer.parseInt(var);
      // if var is not a number than this statement throw Exception
      // and Catch Block will Run
      System.out.println("Number");
    } catch (NumberFormatException ex) { // handling  exception
      System.out.println(" Not A Number");
    }
  }
}

출력:

Not A Number

위의 코드에서 var 문자열 구문 분석이 작동하지 않는 것을 볼 수 있습니다. 확인해야 하는 조건입니다.

그래서 try...catch 블록을 사용하여 처리했습니다. 문자열 값이 숫자가 아니면 catch 블록이 실행됩니다.

작가: Haider Ali
Haider Ali avatar Haider Ali avatar

Haider specializes in technical writing. He has a solid background in computer science that allows him to create engaging, original, and compelling technical tutorials. In his free time, he enjoys adding new skills to his repertoire and watching Netflix.

LinkedIn

관련 문장 - Java Exception