我想将数字拆分为单个数字。下面是我的代码。有没有办法在整齐的循环中进行拆分?

时间:2018-12-05 19:07:50

标签: java

import java.util.*;

public class NumberSplit {
static Scanner console = new Scanner(System.in);

    public static void main(String[] args) {

       int rem1, rem2, rem3, rem4;        

        System.out.print("Enter a positive integer: ");
        int num = console.nextInt();

        rem1 = num / 1000;
        num = num % 1000;

        rem2 = num / 100;
        num = num % 100;

        rem3 = num / 10;
        num = num % 10;
        rem4 = num % 10;

        System.out.println("The digits in your number are: " + rem1 + ", " + rem2 + ", " +  rem3 + ", " + rem4 + ".");
   }
}

1 个答案:

答案 0 :(得分:0)

您可以使用Stream API:

String result = Arrays.stream(String.valueOf(num).split(""))
                    .collect(joining(", ", "The digits in your number are: ", "."))