字符串中的数字进行求和
1 public class StringDemo {
2
3 public static void main(String[] args) {
4 // TODO Auto-generated method stub
5 Scanner sc = new Scanner(System.in);
6 System.out.println("输入任意字符求和");
7 String anyChar=sc.nextLine();
8 anyChar=anyChar.trim();//取出输入字符里面的空格
9 System.out.println("输入完毕开始进行求和运算");
10 String newChar="";//接受数字字符串
11 if (!anyChar.equals(null) && !anyChar.equals(newChar)) {
12 for (int i = 0; i < anyChar.length(); i++) {
13 if (anyChar.charAt(i)>=48 && anyChar.charAt(i)<=57) {//ASCII表中0-9的位置是从48到57
14 newChar+=anyChar.charAt(i);//累加
15 }
16 }
17 }
![](https://img2018.cnblogs.com/blog/1552304/201812/1552304-20181202221240209-1197768414.png)
ASCII表中0-9的位置是从48到57
1 String [] newCharB=newChar.split("");//拆分
2 int [] num=new int[newCharB.length];
3 int sum=0;
4 for (int i = 0; i < num.length; i++) {
5 num[i]=Integer.parseInt(newCharB[i]);//强制转换
6 sum+=num[i];
7 }
8 System.out.println("和为"+sum);
9 System.out.println("求和完毕,谢谢使用");
10 }
11
12 }