![](/img/trans.png)
[英]NumberFormatException while trying to parser string to an int
[英]NumberFormatException when trying to convert String to int while using split() method
string = "#1x#2#3#4#5#6#";
String array[] = string.split("#");
for(int count=0;count<=6;count++){
// String temp = array[count];
String temp1 = array[count].substring(0,1).trim();//here temp1="1"
// String temp1 = "1"; //this is possible
log (Integer.parseInt( temp1));// i cant convert the array which is populated by split("delimiter") why ??
}
這是數組:
array[]=("1","2","3","4","5","6"}
當我將其聲明為正常的String數組時,但在此示例中,當我使用split並在此處填充String數組時,我可以將String array []轉換為整數。
我准備解釋您是否也聽不懂。 幫幫我嗎? 錯誤是
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
我的問題是Integer.parseInt(string_array_populated_by_split_method [count])拋出異常
這里的返回值是字符串“ 1”,即Integer.parseInt(“ 1”)..這個“ 1”是通過split()方法生成的
提前致謝。
你正在做一個
substring(0, 0)
返回""
,並且""
不能轉換為int。 如果要獲得第一個字符,則需要執行以下操作:
substring(0, 1)
那為什么要修剪單個字符,我不知道...
編輯
您的新問題是:
您的String以#
開頭的事實意味着您數組中的第一個值將為""
,並且這引起了問題。 您可以做的是測試String長度是否大於0:
for(String current : array){
if(current.length() > 0) {
String temp1 = current.substring(0,1);
log (Integer.parseInt( temp1));
}
}
或者,您也可以確保開頭的String不是以#
開頭。
我將包括在內以對非數字進行拆分,這樣您就只能得到數字:
String array[] = string.split("\\D");
如果輸入結束或以定界符開頭,我也會跳過所有空白。
首先,您的示例字符串包含“ 1x”,因此僅使用“#”作為分隔符將得到“ 1x”,您無法將其解析為int。
其次,如果在分隔符之前沒有任何內容,則可以通過拆分返回空字符串。 因此您應該檢查是否為空字符串。
您的程序應類似於:
String string = "#1x#2#3#4#5#6#";
String array[] = string.split("\\D");
for (int count = 0; count < array.length; count++) {
if (!array[count].isEmpty()) {
System.out.println(Integer.parseInt(array[count]));
}
當split()遇到兩個相應的定界符時,它將返回一個空字符串。 在1和2之間,您有一個逗號和一個空格。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.