任意一个4位数,要求算出各位数字的和。   例如 1234 ,那么他的各位数字的和就是1+2+3+4  请各位帮忙给我编写下。

解决方案 »

  1.   

    X/1000 得到千位上的数字a,
    (X mod 1000)/100 得到百位上的数字b,
    (X mod 100)/10 得到十位上的数字c,
    X mod 10 得到个位数字d,  a+b+c+d
      

  2.   

    a为任意的四位数:
    a/1000+a%1000/100+a%1000%100/10+a%1000%100%10
      

  3.   


    import java.util.Scanner;
    public class Main {
    public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.println("请输入一个四位数:");
    String str = input.next();

    //判断输入的是否为4位整数
    if(!str.matches("[1-9]\\d{3}")) {
    System.out.println("输入的数字不合法!");
    return;


    //取得各个位
    int num = Integer.parseInt(str);
    int a1 = num / 1000;
    int a2 = num % 1000 / 100;
    int a3 = num % 100 / 10;
    int a4 = num %10;
    int result = a1 + a2 + a3 + a4;
    System.out.println("各位数字之和为:" + result);
    }
    }
      

  4.   

    import java.util.*;
    public class Exam4
    {
    public static void main(String args)
    {
    Scanner scanner = new Scanner(System.in);
        System.out.println("请输入一个四位数"); }} 
    我到这里就写不出来了  请各位指点下吧
      

  5.   

    import java.util.Scanner;public class Main {    public static void main(String[] args) {
            Scanner input = new Scanner(System.in);
            System.out.println("请输入一个四位数:");
            String str = input.next();
            int sum = 0;
            char[] c = new char[10];
            c = str.toCharArray();//将字符串转化成字符数组
            for (int i = 0; i <= 3; i++) {
                sum += (int) (c[i] - '0');//转化成int型
            }
            System.out.println("各位数字之和为:" + sum);
        }
    }
      

  6.   

    import java.util.Scanner;
    public class Main {
        public static void main(String[] args) {
            Scanner input = new Scanner(System.in);
            System.out.println("请输入一个四位数:");
            String str = input.next();
            
            //判断输入的是否为4位整数
            if(!str.matches("[1-9]\\d{3}")) {
                System.out.println("输入的数字不合法!");
                return;
            } 
            
            //取得各个位
            int num = Integer.parseInt(str);
            int a1 = num / 1000;
            int a2 = num % 1000 / 100;
            int a3 = num % 100 / 10;
            int a4 = num %10;
            int result = a1 + a2 + a3 + a4;
            System.out.println("各位数字之和为:" + result);
        }
    }