统计信息

  • 访问数:10933
  • 博客数:142
  • 建立时间:2008-01-05
  • 更新时间:2008-05-21
我叫王超然,是一名电脑爱好者,现在在新加坡留学上高一.我立志成为一名电脑人才,愿意在这里与大家一同分享我玩转电脑的心得.O-level华文考了A-One哈哈!

P5Q2

2008-04-08 13:05:17

天气: 晴朗 心情: 高兴

/*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);
 }
 
 
}
 

 
 


加入收藏 编辑 审核

TAG: computing

我来说两句

OPEN

Powered by X-Space 1.2 © 2001-2006 Comsenz Technology Ltd