Converting a String with spaces to an Integer in java

前端 未结 5 1715
温柔的废话
温柔的废话 2021-02-19 21:59

I\'m trying to convert a String variable into an integer, only the String looks like this (for example):

String string = \" 12\";

And so the St

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-19 22:45

    To make sure that your code does not throw NumberFormatException or even NullPointerException, when you get number from user, use apache common classes:

    import org.apache.commons.lang3.StringUtils;
    import org.apache.commons.lang3.math.NumberUtils;
    .....
    // '1' is the default value which is returned when the string can not be converted to int
    // The StringUtils.trimToEmpty do both left and right trim
    int number = NumberUtils.toInt(StringUtils.trimToEmpty( "  12 ",1)) = 12; 
    

提交回复
热议问题