Java数字串与数字相加的工具方法

来源:互联网 发布:淘宝怎么看无线端来源 编辑:程序博客网 时间:2024/05/01 19:29

最近用Java实现了个数字串(即只包含数字的字符串)与数字相加的工具方法,开发中可能会用到,代码分享如下:

Java代码 复制代码 收藏代码
  1. /**
  2. * 数字串与数字相加的处理类
  3. *
  4. * @author shawn.shen
  5. *
  6. */
  7. public class StrPlusNumber {
  8. /**
  9. * @param args
  10. */
  11. public static void main(String[] args) {
  12. String s = "99999";
  13. System.out.println(plusNum(s, 1));
  14. }
  15. /**
  16. * 实现数字串与数字的相加
  17. *
  18. * @param str 数字串,即只包含数字的字符串
  19. * @param num 数字
  20. * @return s 相加之后,新的字符串
  21. */
  22. public static String plusNum(String strNum,int num){
  23. String s = "";
  24. try {
  25. int i = Integer.parseInt(strNum);
  26. if ("0".equals(strNum.substring(0,1))) {
  27. s = strNum.substring(0, strNum.lastIndexOf(String.valueOf(i)));
  28. }
  29. s += (num + i);
  30. } catch (NumberFormatException e) { // str为非数字串时的异常处理
  31. System.out.println(e.getMessage());
  32. }
  33. return s;
  34. }
  35. }  
原创粉丝点击