Skip to content

Files

Latest commit

ed2b32f · Oct 12, 2019

History

History
48 lines (38 loc) · 1.72 KB

File metadata and controls

48 lines (38 loc) · 1.72 KB

Java 程序:将Integer分解为数字

原文: 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 user
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter any number:");
        num = scanner.nextInt();
        scanner.close();

        //making a copy of the input number
        temp = num;

        //counting digits in the input number
        while(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--;
        }
    }
}

输出:

Java Program to break Integer into Digits