-4

これが私の仕事です。このメソッドを実装する方法がわかりません。

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!");
    }

}

}

4

2 に答える 2

6

このタスクの解決策は、ここにあります。Stringaを anに解析するためのソース コードは次のintようになります。

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; 
}
于 2013-10-26T19:01:28.390 に答える
4

これは、文字列内の各文字を左から読み取ることで実現できますが、これはゼロのインデックスに他なりません。

これは、問題を解決する 1 つの方法です。コードを提供したくないので、コードを作成する機会が得られます。

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;
}
于 2013-10-26T19:01:52.413 に答える