简体   繁体   English

无法在Java中将String转换为int

[英]Cannot convert String to int in Java

In my program I need to convert a String to Int. 在我的程序中,我需要将String转换为Int。

    String str = new String(request.getData());

    String [] setting = str.split(" ");        
    String bs = setting[1];

The value of bs is 1024, I use System.out.println to test it, and it displays on the screen with "1024". bs的值是1024,我使用System.out.println来测试它,它在屏幕上以“1024”显示。

But when I use 但是当我使用时

    int blockSize = Integer.parseInt(bs); 

it will return an exception point to the line of Integer.parseInt : 它会将一个异常点返回到Integer.parseInt行:

Exception in thread "main" java.lang.NumberFormatException: For input string: "1024"
  at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
  at java.lang.Integer.parseInt(Integer.java:458)
  at java.lang.Integer.valueOf(Integer.java:554)

Can someone help me to solve it? 有人可以帮我解决吗? Thanks. 谢谢。

I suspect you have some hidden unicode character in the string bs , you can remove the non-digits with: 我怀疑你在字符串bs有一些隐藏的unicode字符,你可以删除非数字:

bs = bs.replaceAll("\\D", "");
int blockSize = Integer.parseInt(bs);

The code above will also convert the string "1a2" to 12 , but that doesn't seem your case. 上面的代码也将字符串"1a2"转换为12 ,但这似乎不是你的情况。

试试这段代码:

 String bs = setting[1].trim().toString();
    while( (!bs.matches("\\d+")) && (bs.length > 1)) 
    {
        bs = bs.substring(1);
    }

    if (bs.matches("\\d+")
    {
        int blockSize = Integer.parseInt(bs);
    }
    else
    {
        int blockSize = -1;
    }
    /* !! Then, check for "-1" in your application of 
          block size #runtime_exception_prevention */

This will continue to remove the offensive non digit bits down to 1, as necessary, until a digit is found or only one character remains in the string. 这将继续根据需要将令人反感的非数字位删除至1,直到找到一个数字或字符串中只剩下一个字符。 The second check prevents the exception and returns a flagged value. 第二次检查可防止异常并返回标记值。 Checking for this flagged value will intercept runtime exceptions. 检查此标记值将拦截运行时异常。 NB: I wrote this code in the comment block, please forgive any minor errors, I will gladly correct. 注意:我在评论块中写了这段代码,请原谅任何小错误,我很乐意纠正。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM