2013-10-26 89 views
-4

這是我的任務。我不知道如何實現這個方法。我該如何實現我的parseInt(String str)方法?

實現一個Integer parseInt(String str)的方法throws NumberFormatException將使用輸入字符串,該字符串必須包含唯一數字並且不從零開始,並返回一個數字,該數字必須從該行的轉換中獲得。不允許使用默認類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。 用於解析Stringint的源代碼可能類似於:

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

這可以實現通過讀取留下的字符串,它也不過是從零開始的索引中的每個字符。

這是解決問題的一種方法。我不想提供代碼,以便您有機會參與其中。

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; 
}