输入
aaa 110 2 300 bc 400d
输出
812
使用 Integer.parseInt 如果能转成数值,则累加,否则放弃继续下一个循环处理。
核心知识点是判断是否是数字。
public class leo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入字符串:");
String line = scanner.nextLine();
int total = 0;
String numLine = line.replaceAll("[^0-9]", " ");
for (String i : numLine.split("\\s+")) {
if (!i.equals("")) {
total = total + Integer.parseInt(i);
}
}
System.out.println("total:" + total);
}
}