ProgramingTip

java.lang.NumberFormatException을 어떻게해야합니까? 입력의 경우 :“N / A”?

bestdevel 2020. 11. 21. 09:30
반응형

java.lang.NumberFormatException을 어떻게해야합니까? 입력의 경우 :“N / A”?


내 코드를 실행하는 동안 NumberFormatException다음을 얻습니다 .

java.lang.NumberFormatException: For input string: "N/A"
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.valueOf(Unknown Source)
    at java.util.TreeMap.compare(Unknown Source)
    at java.util.TreeMap.put(Unknown Source)
    at java.util.TreeSet.add(Unknown Source)`

이 예외가 발생하지 않도록해야합니까?


"N/A"정수가 아닙니다. NumberFormatException정수로 구문 분석을 많이 합니다.

구문 분석하기 전에 확인하십시오. 또는 취급 Exception하게 취급하십시오 .

  1. 예외 처리 *
try{
   int i = Integer.parseInt(input);
}catch(NumberFormatException ex){ // handle your exception
   ...
}

또는- 정수 패턴 일치 -

String input=...;
String pattern ="-?\\d+";
if(input.matches("-?\\d+")){ // any positive or negetive integer or not!
 ...
}

당신은 구문 분명히 분석 할 수 없습니다 N/Aint값. 당신은 그것을 처리하기 위해 다음과 같은 것을 할 수 있습니다 NumberFormatException.

   String str="N/A";
   try {
        int val=Integer.parseInt(str);
   }catch (NumberFormatException e){
       System.out.println("not a number"); 
   } 

이와 같은 예외 처리기를 만드십시오.

private int ConvertIntoNumeric(String xVal)
{
 try
  { 
     return Integer.parseInt(xVal);
  }
 catch(Exception ex) 
  {
     return 0; 
  }
}

.
.
.
.

int xTest = ConvertIntoNumeric("N/A");  //Will return 0

Integer.parseInt (str)NumberFormatException없습니까 구문 분석 가능한 정수가 포함되지 않은 경우 발생합니다. 아래와 같이 할 수 있습니다.

int a;
String str = "N/A";

try {   
   a = Integer.parseInt(str);
} catch (NumberFormatException nfe) {
  // Handle the condition when str is not a number.
}

"N / A"는 숫자로 변환 할 수 없습니다. 예외를 잡아서 처리하십시오. 예를 들면 :

    String text = "N/A";
    int intVal = 0;
    try {
        intVal = Integer.parseInt(text);
    } catch (NumberFormatException e) {
        //Log it if needed
        intVal = //default fallback value;
    }

참고 URL : https://stackoverflow.com/questions/18711896/how-can-i-prevent-java-lang-numberformatexception-for-input-string-na

반응형