原文: https://beginnersbook.com/2019/02/java-program-to-break-integer-into-digits/
在本教程中,我们将编写一个 java 程序来将输入整数分成数字。例如,如果输入的数字是 912,则程序应显示数字2,1,9以及它们在输出中的位置。
Java 示例:将整数分成数字
这里我们使用Scanner类来从用户获取输入。在第一个while循环中,我们计算输入数字中的数字,然后在第二个while循环中,我们使用模数运算符从输入数字中提取数字。
package com.beginnersbook;import java.util.Scanner;public class JavaExample{public static void main(String args[]){int num, temp, digit, count = 0;//getting the number from userScanner scanner = new Scanner(System.in);System.out.print("Enter any number:");num = scanner.nextInt();scanner.close();//making a copy of the input numbertemp = num;//counting digits in the input numberwhile(num > 0){num = num / 10;count++;}while(temp > 0){digit = temp % 10;System.out.println("Digit at place "+count+" is: "+digit);temp = temp / 10;count--;}}}
输出:

