2013-10-26 1 views
-4

내 작업은 다음과 같습니다. 이 방법을 구현하는 방법을 모르겠습니다.parseInt (String str) 메서드를 구현하려면 어떻게해야합니까?

정수의 메소드를 구현합니다. parseInt (String str)는 NumberFormatException을 던집니다. 입력 문자열은 숫자 만 포함하고 0부터 시작하지 않아야하며 행의 변환에서 가져와야하는 숫자를 반환합니다. 기본 클래스 Java의 메소드를 사용할 수 없습니다.

공용 클래스 파스 {

public static void main(String[] args) { 
    String s = " "; 
    int res = 0; 

    int[] arr = new int[s.length()]; 
    try { 
     for (int i = 0; i < s.length(); i++) { 
      arr[i] = s.trim().charAt(i); 
     } 

     try { 
      for (int i = arr.length - 1, j = 1; i >= 0; i--, j *= 10) { 
       if ((arr[0] - 48) <= 0 || (arr[i] - 48) >= 10) { 
        throw new NumberFormatException(); 
       } else { 
        res += (arr[i] - 48) * j; 
       } 
      } 
      System.out.println(res); 
     } catch (NumberFormatException n) { 
      System.out.println("Enter only numbers ."); 
     } 

    } catch (StringIndexOutOfBoundsException str) { 
     System.out.println("Don't enter a space!"); 
    } 

} 

}

+0

몇 가지 문제가 발생하면 가장 먼저 시도하고 코드를 게시하는 것이 가장 좋습니다. 그렇지 않으면 당신은 어떤 부정적인 표를 얻을 것이다. – Buddha

+0

나는 시험해 보았다. 그리고 나서 그것은 나에게 떠올랐다.) –

답변

1

이 작업을위한 솔루션 here을 찾을 수 있습니다 는 내가 그것을 해결 방법은 다음과 같습니다. 제로의 인덱스에 불과하다 왼쪽 문자열의 각 문자를 읽어

public int ConvertStringToInt(String s) throws NumberFormatException 
{ 
    int num =0; 
    for(int i =0; i<s.length();i++) 
    { 
     if(((int)s.charAt(i)>=48)&&((int)s.charAt(i)<=57)) 
     { 
      num = num*10+ ((int)s.charAt(i)-48); 
     } 
     else 
     { 
      throw new NumberFormatException(); 
     } 

    } 
    return num; 
} 
+0

링크에서 게시물을 보았지만 너무 복잡합니다. –

3

이 달성 될 수있다 : intString을 구문 분석에 대한 소스 코드는 다음과 같다 할 수있다.

이것은 문제를 해결하는 한 가지 방법입니다. 나는 당신이 그것에 일할 기회를 얻을 수 있도록 코드를주고 싶지 않다.

set n = 0; 
for(int i = 0; i < inputStr.length(); i++) 
{ 
    find ascii value of the character; 
    if the ascii value is not between 48 and 57 throw a number format exception; 
    if valid substract 48 from the ascii value to get the numerical value; 
    n = n * 10 + numerical value calculated in previous step; 
}