2016-09-12 184 views
0

我不知道在我的代碼中將字符串解析爲int部分時出了什麼問題。在解析之前,一切看起來都正確。無法將字符串解析爲int

import java.io.IOException; 

public class TheWindow { 

    public static void main(String[] args) throws IOException{ 

     String s = "13.16"; 
     double d = Double.parseDouble(s); 
     System.out.println(d); 
     char[] ch = s.toCharArray(); 
     char[] ch2 = new char[s.length()]; 
     for(int i = 0; i < ch.length; i++){ 
      if(ch[i] == '.'){ 
       break; 
      }else{ 
       ch2[i] = ch[i]; 
      } 
     } 
     String s2 = new String(ch2); 
     System.out.println(s2); 
     try{ 
      s2.trim(); 
      int newI = Integer.parseInt(s2); 
      System.out.println(newI); 
     }catch(Exception e){ 
      System.out.println("Failed"); 
     } 
    } 
} 
+1

是什麼錯誤消息說?如果您想知道出了什麼問題,最好閱讀它而不是丟棄它。我懷疑你的'ch2'結尾有一些空字符,你打破了循環,但是你不會讓'ch2'變小。你可以使用你的調試器來遍歷代碼,找出每一行正在做什麼以及哪裏出錯。 –

回答

0

您的代碼的問題在於,當'。'符號出現時,您正在跳出for循環。字符已達到。

由於您創建了長度爲5的ch2,這意味着最後三個空格爲空。當你把它放入字符串String s2 = new String(ch2)然後三個特殊字符被添加到字符串的末尾,一個用於ch2字符數組中的每個空白空間。

爲了解決這個問題然後設置ch2陣列的長度是兩個,或如果要動態地確定的長度,執行「' in the的String with s.indexOf(」。「)and then set the length of the array to one minus the index of '」的索引。

這應該解決你的問題,如你的問題所述。

+0

非常有幫助!謝謝! –

3

您還沒有存儲從trim()隨時隨地返回String。你既可以做:

s2 = s2.trim(); 
int newI = Integer.parseInt(s2); 

int newI = Integer.parseInt(s2.trim()); 
0
s2 = s2.trim(); 

改變這部分代碼在try塊。

您正在修剪字符串,但未將其分配給引用該字符串的變量,因爲該字符串空間仍然被排除,並且解析此類字符串會引發異常。

0

Java對象是不可變的,這意味着它們不能被改變,字符串是Java中的對象。

您的線路s2.trim()將返回修剪版本,但不會直接修改s2。但是,您並未將它存儲在任何地方,因此當您在下一行解析它時,它將與未修改的s2一起使用。

你想要的是s2 = s2.trim(),將存儲修剪版本回。

0

據我瞭解,你要截斷小數。如果是這樣,那麼你可以找到小數位和子串字符串,然後解析它。

注意:您可能想要爲仍然無法解析的字符串添加一些嘗試捕獲。

private static int tryParseInt(String str) { 
    int decimalIndex = str.indexOf("."); 

    if (decimalIndex != -1) { 
     return Integer.parseInt(str.substring(0, decimalIndex)); 
    } else { 
     return Integer.parseInt(str); 
    } 
} 

public static void main(String[] args) { 
    System.out.println(tryParseInt("13.16")); // 13 
} 
0

您的ch2數組中有未初始化的字符。您可以在修剪前將它們設置爲空格,或使用其他字符串構造函數。例如:

 public static void main(String[] args) { 

     String s = "13.16"; 
     double d = Double.parseDouble(s); 
     System.out.println(d); 
     char[] ch = s.toCharArray(); 
     char[] ch2 = new char[s.length()]; 
     int i = 0; 
     for(i = 0; i < ch.length; i++){ 
      if(ch[i] == '.'){ 
       break; 
      }else{ 
       ch2[i] = ch[i]; 
      } 
     } 
     String s2 = new String(ch2, 0, i); 
     System.out.println(s2); 
     try{ 
      s2.trim(); 
      int newI = Integer.parseInt(s2); 
      System.out.println(newI); 
     }catch(Exception e){ 
      System.out.println("Failed"); 
     } 
    } 

}