Use Java to determine the number of digits of the input integer and calculate the sum

 Topic: Enter a number, determine the number of digits of the integer entered, and calculate the sum of the digits.

import java.util.Scanner;

public class Judge {

	public static void main(String[] args) {
		int num, i = 0, x = 0;
		System.out.println("请输入一个正整数:");
		Scanner scan = new Scanner(System.in);
		num = scan.nextInt();
		while (num != 0) { // 循环条件
			x = x + num % 10; // 求各位数字之和
			num = num / 10; // 判断这是个几位数的条件
			i++; // 记录运行判断几次运行条件
		}
		System.out.println("这个正整数是" + i + "位数," + "各位数字之和为" + x + "。");

	}
}

 

Guess you like

Origin blog.csdn.net/cpm011023/article/details/114435630