2013-04-04 56 views
0

这是我的代码:错误在解析整数

TextView headerVal = (TextView) nextChild.findViewById(R.id.textView3); 
    String tt = ((String)headerVal.getText()).replaceAll(",",""); //it was 1,000 and it became 1000   
    int longueur = tt.length(); 
    String aux2 = (String) tt.substring(0,longueur - 2); 
    int contenu = (int) Integer.parseInt(aux2);// here is the error "unable to parse 1000 as an integer". 

PS:它工作在模拟器上,但我得到了我的手机

logcat的此错误:

04-04 13:04:15.210: E/AndroidRuntime(31718): FATAL EXCEPTION: main 

04-04 13:04:15.210: E/AndroidRuntime(31718): java.lang.NumberFormatException: unable to parse '1 000' as integer 

04-04 13:04:15.210: E/AndroidRuntime(31718):at java.lang.Integer.parse(Integer.java:433) 

04-04 13:04:15.210: E/AndroidRuntime(31718):at java.lang.Integer.parseInt(Integer.java:422) 

04-04 13:04:15.210: E/AndroidRuntime(31718):at java.lang.Integer.parseInt(Integer.java:382) 
04-04 13:04:15.210:E/AndroidRuntime(31718):at com.example.appui.BarGraphActivity.setColumnParts(BarGraphActivity.java:408) 
04-04 13:04:15.210: E/AndroidRuntime(31718):at com.example.appui.BarGraphActivity.access$2(BarGraphActivity.java:282) 
04-04 13:04:15.210: E/AndroidRuntime(31718):at com.example.appui.BarGraphActivity$Desired_pension.onStopTrackingTouch(BarGraphActivity.java:162) 
+0

它显示什么??任何错误? – Subburaj 2013-04-04 13:01:41

+0

无法解析1000作为整数 – user2137817 2013-04-04 13:02:12

+0

@塞巴斯蒂安没有得到您的想法,详情请 – user2137817 2013-04-04 13:04:01

回答

0

使用DecimalFormat如下:

DecimalFormat format =(DecimalFormat) DecimalFormat.getInstance(); 
format.applyPattern("#,###"); 
try { 
    integer = (Integer)format.parse(tt); 
} catch (ParseException e) { 
    System.err.println(new Date()+": "+e.getMessage()); 
} 
+0

类抛出异常 – user2137817 2013-04-04 13:19:46

+0

发布您的整个代码,它适用于我,一定是愚蠢的东西 – hd1 2013-04-04 13:23:36

+0

无法发布整个代码,因为它太长,但关于解析,它是完整的代码之后,我使用价值我解析了一些操作 – user2137817 2013-04-04 13:34:45

0
Try this 

public static void main(String[] args) { 

     String test = ",100,0,0,"; 
     int newTest; 
     test = test.replaceAll(",",""); 

     int longueur = test.length(); 
       // If the longueur length is greater than or equal to test.length() then it will return error, so put a check to see the longueur is not exceeding the test length. 
     String aux2 = (String) test.substring(0,longueur - 2); 

     newTest = Integer.parseInt(aux2); 

     System.out.println(newTest); 

    } 

结果100,如果longueur - 1返回1000

0

你只需要使用修剪功能后替换: -

String str2 = str.trim(); 

上面的代码中删除所有的空间到您的然后将字符串转换为整数: -

TextView headerVal = (TextView) nextChild.findViewById(R.id.textView3); 
String tt = ((String)headerVal.getText()).replaceAll(",",""); //it was 1,000 and it became 1000   

String str2 = tt .trim(); 
int longueur = str2 .length(); 

然后做你的任务你想要什么....

+0

修剪在开始或结束删除空格http://stackoverflow.com/questions/6932163/removing-spaces-from-string – user2137817 2013-04-04 13:33:38

+0

@ user2137817然后你必须检查此链接也 duggu 2013-04-05 04:24:40