by Pierpont
(求一個整數各位數字之和)編寫一個方法,計算一個整數各位數字之和。使用下面的方法頭:
public static int sumDigits(long s)
例如: sumDigits(234)傳回9(2+3+4)。
編寫程式提示使用者輸入一個整數,然後顯示這個整數所有的數字的和。
import java.util.Scanner;
public class Practice_6_2 {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer:");
int n = input.nextInt();
System.out.println(sumDigits(n));
}
public static int sumDigits(long n) {
int i = 0;
while(n != 0){
i += (int)(n % 10);
n = n / 10;
}
return i;
}
}
輸出示例:
Enter an integer:234
9