【发布时间】:2017-02-13 01:15:36
【问题描述】:
我正在尝试运行一个程序,该程序输出输入整数的每个数字的总和。我将如何读取数字并输出每个数字?
示例:输入为 4053,输出为“4+0+5+3 = 12”。
import java.util.Scanner;
public class Digits{
public static void main(String args[]) {
//Scans in integer
Scanner stdin = new Scanner(System.in);
System.out.println("Enter in a number: ");
int number = stdin.nextInt();
//Set sum to zero for reference
int sum = 0;
int num = number; //Set num equal to number as reference
//reads each digit of the scanned number and individually adds them together
//as it goes through the digits, keep dividing by 10 until its 0.
while (num > 0) {
int lastDigit = num % 10;
sum = sum + lastDigit;
num = num/10;
}
}
}
这是我用于计算单个数字总和的代码,现在我只需要输出单个数字的帮助。任何提示和技巧将不胜感激。
【问题讨论】:
-
输出是什么意思?
-
扫描仪必须一次读取每个数字以创建数字,然后将其分解为每个数字。为什么不一次只读一个字符?
-
在循环遍历数字时只需打印出
lastDigit的每个值。 -
@PeterLawrey。一方面,您需要验证您确实得到了一个整数,扫描仪可以很好地为您完成。
-
@PeterLawrey 另外,要加起来,您需要将数字单独转换为数字。一开始就一次完成似乎更有效率。
标签: java while-loop