Java中对字符串中的数字进行求和运算

字符串中的数字进行求和

  

 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         }

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 }



 



















  

猜你喜欢

转载自www.cnblogs.com/fengxia/p/10055762.html