java方法的使用

 

写一个方法,使其计算一个整数中的各个数字的和(整数12345各个数字1,2,3,4,5的和为15)。使用以下的方法头部:
public static int sumDigits(long n)

import java.util.Scanner;
public class arrytest {
    public static void main(String[] args) {
        Scanner input=new Scanner(System.in);
        long number = input.nextLong();//用户输入
        System.out.print("The sum of digits for "+number); 
        System.out.println(" is:" + sumDigits(number));//利用方法输出结果
      }
    //定义计算整数中各数字之和的方法(自定义函数)
    public static int sumDigits(long n) {
    int temp = (int)Math.abs(n);//取绝对值后转换为int型(默认Double)
    int sum = 0;//定义sum计算各个数位的和
    while (temp != 0) {
      int remainder = temp % 10;//remainder用来记录各个数位
      sum += remainder;//累加各个数位和
      temp = temp / 10;//减去累加过得数位
    }
    return sum;//返回计算的结果
  }
}

 

 

 

https://blog.csdn.net/weixin_43759910/article/details/89343624

posted @ 2019-04-16 22:17  皇棠  阅读(149)  评论(0)    收藏  举报