第六章第二题(求一个整数各位数字之和)(Sum the digits in an integer)
-
*6.2(求一个整数各位数字之和)编写一个方法,计算一个整数各位数字之和。使用下面的方法头:
public static int sumDigits(long n)例如:sumDigits(234)返回9(2+3+4)。 提示:使用求余操作符%提取数字,用除号/去掉提取出来的数字。例如:使用234%10(=4)提取4。然后使用234/10(=23)从234中去掉4。使用一个循环来反复提取和去掉每位数字,直到所有的位数都提取完为止。 编写程序提示用户输入一个整数,然后显示这个整数所有数字的和。
*6.2(Sum the digits in an integer) Write a method that computes the sum of the digits in an integer. Use the following method header:
public static int sumDigits(long n)For example, sumDigits(234) returns 9 (= 2 + 3 + 4). (Hint: Use the % operator to extract digits and the / operator to remove the extracted digit. For instance, to extract 4 from 234, use 234 % 10 (= 4 ). To remove 4 from 234, use 234 / 10(= 2 3 ). Use a loop to repeatedly extract and remove the digit until all the digits are extracted. Write a test program that prompts the user to enter an integer then displays the sum of all its digits.
-
参考代码:
package chapter06;
import java.util.Scanner;
public class Code_02 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
long number = input.nextInt();
System.out.println("The sum of the digits in an integer: " + sumDigits(number));
}
public static int sumDigits(long n){
int sum = 0;
while (n >= 10){
sum += n % 10;
n /= 10;
}
return (int)(sum + n);
}
}
- 结果显示:
Enter an integer: 234
The sum of the digits in an integer: 9
Process finished with exit code 0