下面是我的代码,我已经能够获得数字之和,但我不知道如何干净地分离和打印整数的各个数字。它可以在我的“do”循环中完成吗?
import java.util.*;
public class Ch5PgEx1 {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
int num;
int sum;
int remainder;
int count;
System.out.print("Please enter an integer: ");
num = console.nextInt();
System.out.println();
sum = 0;
count = 0;
do {
remainder = num % 10;
sum = sum + remainder;
num = num / 10;
count++;
}
while (num > 0);
System.out.print("There are " + count + " digits in your number. \nThe sum of the individual digits is:" + sum);
System.out.println();
}
}
最佳答案
要打印它们,只需添加打印行
do { remainder = num % 10; sum = sum + remainder; num = num / 10; count++; System.out.println(remainder); } while (num > 0); /* Please enter an integer: 123456789 9 8 7 6 5 ...
将它们存储在数组中
int[] res = new int[Integer.toString(num).length()]; do { remainder = num % 10; sum = sum + remainder; num = num / 10; res[count++] = remainder; // LINE 1 } while (num > 0); /* Please enter an integer: 123456789 [9, 8, 7, 6, 5, 4, 3, 2, 1] ...
以
[1, 2, 3, 4, 5, 6, 7, 8, 9]
方式获取数组:- 将
LINE 1
更改为res[res.length -++count] = approximation;
- 将
关于java - 一个 Java 程序,获取一个整数,分隔各个数字并给出数字之和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53622534/