【问题标题】:How do I create an application that prompts the user for an integer and returns the number of digits it has?如何创建一个应用程序提示用户输入一个整数并返回它的位数?
【发布时间】:2019-04-10 04:38:24
【问题描述】:

我已经开始写下这段代码,我想在用户提示输入整数后找到它所返回的数字。我该从哪里着手?

我目前对 Dr Java 编码还是个新手。但是,我已尝试研究这些方法,但找不到此解决方案的示例。

public class Recursion {
    public static void main(String[] args) { 
        Scanner input = new Scanner(System.in);
        System.out.println("Enter an integer.");
        int digit = input.nextInt();
        input.close();
    }
}

我预计它需要一个递归或方法来解决这个问题,我相信它需要返回数字,但我不确定它是否正确。

【问题讨论】:

    标签: drjava


    【解决方案1】:

    你可以使用这个函数来计算位数:

    function digits_count(n) {
          var count = 0;
          if (n >= 1) ++count;
    
          while (n / 10 >= 1) {
            n /= 10;
            ++count;
          }
    
      return count;
    }
    

    【讨论】:

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