2016-11-09 55 views
0

我想将字符串转换为整数,但是当我尝试打印结果时,我无法获得正确的输出。我想将字符串转换为整数,但我不能打印结果

package com.company; 

public class Main { 

    public static void main(String[] args){ 
     String str ="-123456"; 
     int i = atoi(str); 
     System.out.println(i); 
    } 

    public static int atoi(String str){ 
     if (str == null || str.length() < 1) 
      return 0; 
     str = str.trim(); 
     char flag = '+'; 

     int i = 0; 
     if (str.charAt(0) == '-'){ 
      flag = '-'; 
      i++; 
     } else if (str.charAt(0) == '+'){ 
      i++; 
     } 

     double result = 0; 
     while (str.length() > 1 && str.charAt(i) >= '0' && str.charAt(i) <= '9'){ 
      result = result * 10 + (str.charAt(i)-'0'); 
      i++; 
     } 

     if (flag == '-'){ 
      result = -result; 
     } 

     if (result > Integer.MAX_VALUE){ 
      return Integer.MAX_VALUE; 
     } 
     if (result < Integer.MIN_VALUE){ 
      return Integer.MIN_VALUE; 
     } 
     return (int) result; 
    } 
} 

This is the result after I run the code

+0

请注意,除非这是一个练习,否则您可以使用'Integer.parseInt(String str)'而不是实现自己的'atoi'。 – Aaron

+0

我想用'Integer.parseInt()'不是答案吗?关于你的代码,错误是'while(str.length()> 1',因为str不会改变,所以这个条件总是成立的。 – jaudo

回答

0

更改为:注意我< str.length(),而不是str.length()> 1

说明:你的错误是 “索引超出范围” 你的意思'试图访问一个不在直线长度范围内的字符,在这种情况下str.charAt(7)不存在,所以你必须限制i小于长度的长度串。

while (i < str.length() && str.charAt(i) >= '0' && str.charAt(i) <= '9'){ 
     result = result * 10 + (str.charAt(i)-'0'); 
     i++; 
} 
+0

解释为什么这个工作会更有用。例如让OP知道str .length()永远不会随着当前代码而改变。 –

+0

在解释中添加,谢谢! – cullan