【问题标题】:Rephrased Inquiry: Outputting Digits of Number in Correct Order Using Loops and Modulus改写查询:使用循环和模以正确的顺序输出数字的位数
【发布时间】:2015-11-13 03:45:56
【问题描述】:

我之前发布的问题措辞不佳,我深表歉意。这是我真正想要的:我必须创建一个 DigitsDisplay 应用程序,它会提示用户输入一个非负整数,然后在单独的行上显示每个数字。应列出数字,因此个位数位于底部。我不知道这个数字会有多大。

示例: 12456

1

2

4

5

6

有谁知道如何使用循环和模数来做到这一点?没有花哨的东西,只是一个简单的 while 语句。 这是我目前所拥有的:

int digit;
        System.out.print("Enter a #: ");
        digit = console.nextInt();

        int count = 0;

        while (digit != 0) {
            count += 1;
            digit = digit % 10;
            System.out.println(digit);
        }

但它不工作,我不知道如何让它工作。

【问题讨论】:

    标签: java loops while-loop modulus


    【解决方案1】:

    将余数存储在一个 int 变量中,并在每次迭代中使用 / 更改您的数字。 您可以在 stack 中的每次迭代中推送余数,最后,您可以弹出所有项目。

        int remainder=0;
        Stack<Integer> stack = new Stack<Integer>();
    
        while (digit != 0) {
                    count += 1;
                    remainder= digit % 10;
                    digit=digit/10;
                    stack.push(remainder);
    
                }
    
       while(!stack.isEmpty())
          System.out.println(stack.pop());
    

    如果你不想使用堆栈,你也可以使用递归来实现它。

    public class test {
        public static void main(String a1[]) {
            int digit = 1234;
            printData(digit);
    
        }
    
        public static void printData(int number) {
            if (number == 0)
                return;
            int remainder = number % 10;
            number = number / 10;
            printData(number);
            System.out.println(remainder);
    
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-28
      • 1970-01-01
      • 1970-01-01
      • 2014-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多