charAt,与字符'0',做差值。
java
import java.util.Scanner;
public class Main3 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String num = scanner.nextLine();
char[] arr = num.toCharArray();
int sum = 0;
for(char c : arr){
int tmp = c - '0';
sum+=tmp;
}
System.out.println(sum);
}
}
第二种解法
java
import java.util.Scanner;
public class Main10 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int i = scanner.nextInt();
// System.out.println(i);
int sum = 0;//各位数字
while(i > 0){
int tmp = i%10;
i = i /10;
sum+=tmp;
}
System.out.println(sum);
}
}