如何区分数字和字符串

Ram*_*hna 0 java string integer

我有一个字符串

String s="Raymond scored 2 centuries at an average of 34 in 3 innings.";
Run Code Online (Sandbox Code Playgroud)

我需要找到字符串中只有数字的总和,而不会遇到任何异常.这里的总和应该是2 + 34 + 3 = 39.如何让编译器理解String和Integer之间的区别.

Coo*_*tri 5

您应该按空格(或通过正则表达式,从您的问题中不清楚)将输入字符串拆分为String标记数组,然后遍历此数组.如果Integer.parseInt(token)调用没有产生NumberFormatException异常,那么它返回一个整数,您应该将其添加到numbers列表中以便进一步处理(或者立即添加到总和)

String inputString = "Raymond scored 2 centuries at an average of 34 in 3 innings.";
String[] stringArray = inputString.split(" ");//may change to any other splitter regex
List<Integer> numbers = new ArrayList<>();
for (String str : sArr) {
   try {
       numbers.add(Integer.parseInt(str)); //or may add to the sum of integers here
   } catch (NumberFormatException e){
        System.out.println(e);
   }
}
//todo any logic you want with the list of integers
Run Code Online (Sandbox Code Playgroud)