解析整数时出错

时间:2013-04-04 12:59:32

标签: android parsing

这是我的代码:

  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)

3 个答案:

答案 0 :(得分: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());
 }

答案 1 :(得分: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

答案 2 :(得分: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();

那么你的任务就是你想要的......