How does Integer.parseInt(string) actually work?

后端 未结 7 1879
南笙
南笙 2020-12-02 20:43

Was asked this question recently and did not know the answer. From a high level can someone explain how Java takes a character / String and convert it into an int.

M

7条回答
  •  星月不相逢
    2020-12-02 21:04

    public class StringToInt {
    
        public int ConvertStringToInt(String s) throws NumberFormatException
        {
            int num =0;
            for(int i =0; i=48)&&((int)s.charAt(i)<=59))
                {
                    num = num*10+ ((int)s.charAt(i)-48);
                }
                else
                {
                    throw new NumberFormatException();
                }
    
            }
            return num; 
        }
    
        public static void main(String[]args)
        {
            StringToInt obj = new StringToInt();
            int i = obj.ConvertStringToInt("1234123");
            System.out.println(i);
        }
    
    }
    

提交回复
热议问题