1. 程式人生 > >Java中對字串中的數字進行求和運算

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 }