我该如何实现我的parseInt(String str)方法?

时间:2013-10-26 18:44:16

标签: java implementation parseint

这是我的任务。我不知道如何实现这个方法。

实现Integer的方法parseInt(String str)抛出NumberFormatException,它将获取输入字符串,该字符串必须仅包含数字并且不从零开始,并返回一个数字,该数字必须从该行的转换中获得。不允许使用默认类Java的方法。 这就是我解决它的方式:

public class Pars {

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

}

}

2 个答案:

答案 0 :(得分:4)

这可以通过从左边读取字符串中的每个字符来实现,这只是零索引。

这是解决问题的一种方法。我不想提供代码,以便您有机会参与其中。

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

答案 1 :(得分:2)

可以找到此任务的解决方案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; 
}