我叫王超然,是一名电脑爱好者,现在在新加坡留学上高一.我立志成为一名电脑人才,愿意在这里与大家一同分享我玩转电脑的心得.O-level华文考了A-One哈哈!
天气: 晴朗
心情: 高兴
/*P5Q2
* Wang Chaoran
* Description:
2 (Summing 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 2 + 3 + 4 = 9.
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 (= 23)
Use a loop to repeatedly extract and remove the digit until all the digits are extracted.
*/
import java.util.Scanner;
public class P5Q2{
public static void main(String[] args){
//Input
Scanner scan = new Scanner(System.in);
System.out.println("Please input an integer: ");
long input = scan.nextInt();
//Output
System.out.println(sumDigits(input));
System.out.println("Please input an integer!");
}
//Method to calculate sum
public static int sumDigits(long n){
int sum=0;
while(n!=0){
sum += n%10;
n /= 10;
}
return Math.abs(sum);
}
}
导入论坛查看(30)回复(0)引用(0)好评(0) 差评(0)
加入收藏
编辑
审核
TAG:
computing