2016-11-09 59 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