Java 实例v将Integer分解为数字

来源:这里教程网 时间:2026-02-17 20:17:01 作者:

在本教程中,我们将编写一个 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 实例v将Integer分解为数字

相关推荐