2013-05-24 3 views
7

이 오류의 원인은 무엇인지 이미 알고 있습니다. 사용자가 대화 상자에 아무것도 입력하지 않은 상태에서 대소 문자를 처리하는 방법을 모르겠습니다. 캐릭터 라인을 int로 구문 분석하는 버튼 빈 문자열을 int로 구문 분석 할 수 없으므로 오류가 발생합니다. 나는 이것을하는 방법에 대한 연구를 해왔지만 만족스러운 결과를 찾지 못했습니다.java.lang.NumberFormatException : Invalid int : ""in android

문제점 : 나머지 코드를 실행하기 전에 대화 상자에 텍스트가 있는지 확인하려면 어떻게합니까?

답변

10

일부 코드는 구문 도움이 될하지만 기본적으로

if ("".equals(text) // where text is the text that you get from an EditText or wherever you get it 
{ // give message to enter valid text; } 

또한, 당신은 try/catch와 서라운드 수 있으며, NumberFormatException이를 잡아 내 응용 프로그램이 충돌합니다. 같은 예외가 발생 Ans By의

시도에 코드를 넣어 SIMPLE-이다 { }

캐치()

블록 이 코드는 잘랐다.이 작품은 나를 위해.

public void setAge(String age) { 

    final Calendar c = Calendar.getInstance(); 
    int yearCurrent = c.get(Calendar.YEAR); 
    try { 
     int yearPrev = (int) Integer.parseInt(age.substring(0, 4));//this line was causing the error 
     int ageYear=yearCurrent-yearPrev; 
     ageUser="Age : "+Integer.toString(ageYear); 
    } 
    catch(NumberFormatException numberEx) { 
     System.out.print(numberEx); 
    } 


} 
1

문제점 : 나머지 코드를 실행하기 전에 대화 상자에 텍스트가 있는지 확인하려면 어떻게합니까?

해결책 : if 성명. 당신이 여분의 의존성을 마련 할 수 있다면 그 또한 유니 코드를 처리하기 때문에

int parseToInt(String maybeInt, int defaultValue){ 
    if (maybeInt == null) return defaultValue; 
    maybeInt = maybeInt.trim(); 
    if (maybeInt.isEmpty()) return defaultValue; 
    return Integer.parseInt(maybeInt); 
} 

, 내가 대신 트림/IsEmpty 함수의 StringUtils.isBlank를 사용, 일반 랭 StringUtils에 끌어 당길 것입니다. 다음과 같은 오류가 발생시킨 적절한 메시지

1
String text = editText.getText().toString(); 
    if(!text.equals("") && text.matches("^\\d+$")){ 
     cast to int 
    } 
0

를 인쇄

관련 문제