第二章第六题(求一个整数各位数的和)(add the digits in an integer)

**2.6(求一个整数各位数的和)编写程序,读取一个0和1000之间的整数,并将该整数的各位数字相加。例如:整数是932,各位数字之和为14。

提示:利用操作符%提取数字,然后使用操作符 / 移除提取出来的数字。例如:932%10=2,932/10=93。
下面是一个运行示例:
Enter a number between 0 and 1000:999
The sum of the digits is 27

**2.6(add the digits in an integer) Write a program that reads an integer between 0 and 1000 and adds all the digits in the integer.for example :the integer is 932,the Summation of all its digits is 14.

Hint: Use the % operator to extract digits, and use the / operator to remove the extracted digit.For instance,932 % 10 = 2 and 932 / 10 = 93.
Here is a simple run:
Enter a number between 0 and 1000:999
The sum of the digits is 27

下面是参考答案代码:

import java.util.*;

public class SumDigitsQuestion6 {
	public static void main(String[] args) {
		int NumLess1000,OneDigit,TenDigit,HundredDigit,SumDigits;

		System.out.print("Enter a number between 0 and 1000 : ");
		Scanner NumInput = new Scanner(System.in);
		NumLess1000 = NumInput.nextInt();
		
		HundredDigit = NumLess1000 / 100;
		TenDigit = NumLess1000 / 10 % 10;
		OneDigit = NumLess1000 % 10;
		SumDigits = HundredDigit + TenDigit + OneDigit;

		System.out.println("The sum of the digits is " + SumDigits);

		NumInput.close();
	}
}

运行效果:
在这里插入图片描述

注:编写程序要养成良好习惯
如:1.文件名要用英文,具体一点
2.注释要英文
3.变量命名要具体,不要抽象(如:a,b,c等等),形式要驼峰化
4.整体书写风格要统一(不要这里是驼峰,那里是下划线,这里的逻辑段落空三行,那里相同的逻辑段落空5行等等)

你可能感兴趣的:(#,第二章课后习题答案)