2012-10-27 4 views
0

입력 문자열에 NumberFormatException이 있는지 확인하는 것이 가능합니까? ""?java.lang.NumberFormatException을 검사 할 수 있습니까?

if(pasientNavnFelt.getText() == null || pasientNrFeIt.getText() == null) 
{ 
    utskriftsområde.setText("ERROR, insert values"); 
} 

if(pasientNavnFelt.getText() != null || pasientNrFeIt.getText() != null) 
{ 
    // rest of code here if the program had values in it 
} 
:

if(pasientNavnFelt.getText() == "" || pasientNrFeIt.getText() == "") 
{ 
    utskriftsområde.setText("ERROR, insert values"); 
} 

if(pasientNavnFelt.getText() != "" || pasientNrFeIt.getText() != "") 
{ 
    // rest of code here if the program had values in it 
} 

나는 또한 null를 시도를 :

나는 사용자가 어떤 값을 넣어하지 않은 경우 오류 메시지가 NumberFormatException이 대신 나올 것이다 그래야 내 프로그램을 작성하려

나는 아직도 얻을 :

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""

,536,

값이 있으면 프로그램이 제대로 작동합니다.

+2

물론 예외를 잡으십시오. –

+1

try-catch 블록을 통합하여 예외를 처리하십시오. –

답변

2

==로 문자열을 비교하지 마십시오. ==은 두 객체가 동일하고 두 객체가 같은 문자를 가지고 있는지 검사하지 않습니다. 문자열을 비교하려면 equals()을 사용하십시오. 말했다

, 당신은 실제로 예외를 잡을 필요가 문자열이 유효한 정수임을 확인합니다 :

try { 
    int i = Integer.parseInt(s); 
    // s is a valid integer 
} 
catch (NumberFormatException e) { 
    // s is not a valid integer 
} 

이 기본 자바 물건입니다. Java tutorial over exceptions을 읽으십시오.

+0

완벽하게 작동 함, thx =) – Madde

1

시도 :

if(pasientNavnFelt.isEmpty() || pasientNrFeIt.isEmpty()) { 
    utskriftsområde.setText("ERROR, insert values"); 
} 
else { 
    ... 
} 
+0

주목할 가치가있는 OP의 원래 이슈 중 하나는'.equals (...) '보다는 String equality에'=='을 사용하는 것이 었습니다. –

0

두 번째 조건이 잘못되었습니다. 당신이 말하려고하면, null이 있다면, 오류, 그렇지 않으면 뭔가를하십시오. 당신은 null 오류가 있다면, 그들 중 하나가 null이 아니면 나머지를 수행 할 것입니다. 두 가지 문자 변경은 두 번째 "||" "& &"으로 변경하십시오. 하지만 실제로 원하는 것은 실제로는 다음과 같습니다.

if(pasientNavnFelt.getText() == null || pasientNrFeIt.getText() == null) 
     { 
      utskriftsområde.setText("ERROR, insert values"); 
     } 
    else 
     { <rest of code here if the program had values in it>} 
관련 문제