如何分别打印给定数字的每个数字?

问题描述 投票:0回答:3

我写了一个应该分别打印每个数字的代码。这是一个例子。

printDigits(1362) prints
2
6
3
1

printsDigits(985) prints
5
8
9

您可以使用/ 10% 10将数字分解成数字。

我已经按照我的教学方式开始了一些代码,但是我不确定如何处理其他变量。请看一下:

public class Main {

  public static void main(String[] args) {
    System.out.println(printDigits(1362));
    System.out.println(printDigits(985));
    }

  public static int printDigits(int x){
    int y = x % 10;
    while (x > 0){
      x = y;
      System.out.println(x);
      x = x / 10;
    }
   return x;
   }
}
java while-loop module public
3个回答
0
投票

为什么不将参数x转换为String,然后读取String中的每个Char,因为String是Char的数组。如果输出必须为int,则将Char转换为int。


0
投票

您需要在循环内写int y = x % 10;以“拆开”每个数字并打印您已经“抽出”的数字y。删除函数调用周围的System.out.println。您不需要返回数字,因此可以将返回类型更改为void

public class Main {
    public static void main(String[] args) {
        printDigits(1362);
        System.out.println();
        printDigits(985);
    }

    public static void printDigits(int x) {
        while (x > 0) {
            int y = x % 10;
            System.out.println(y);
            x = x / 10;
        }
        return x;
    }
}

0
投票

printDigits方法应该像这样:

public static void printDigits(int x) {
    int y;
    while (x > 0) {
        y = x % 10;
        System.out.println(y);
        x = x / 10;
    }
}

并且方法的调用将像这样:

printDigits(1362); // without the System.out.println()
© www.soinside.com 2019 - 2024. All rights reserved.