【问题标题】:Why does my method sometimes print multiple lines?为什么我的方法有时会打印多行?
【发布时间】:2017-11-07 05:34:25
【问题描述】:

所以我有这个方法

public int sumMathRandomAndSystemTime(){

    n = 1 + ((int) (Math.random() * 10)+ 
            (int) (System.currentTimeMillis() % 10));

    if(n > 10){
        sumMathRandomAndSystemTime();
    }
    System.out.println(n);
    return n;

}  

我想要的只是打印一个介于 1 和 10 之间的随机数 (n) 一次。但是由于某种原因,当我调用该方法时,它确实打印了一个随机数,但有时只打印一次,有时它会打印 10 次、5 次等数字。为什么会发生这种情况?

这是我的输出示例

10
10
10
10
10

【问题讨论】:

  • 因为它是递归的。
  • 这个方法有什么意义?
  • 好的,但是我如何摆脱多行打印?有什么建议吗?
  • 如果您在 n 大于 10 时尝试打印。使用 else 块包装您的打印方法调用
  • 移除递归调用。它甚至什么都不做(除了打印)

标签: java random systemtime


【解决方案1】:

如果原始随机数大于 10,您的代码将打印多行:每个递归调用一行。

你可以改变你的代码来解决这个问题:

public int sumMathRandomAndSystemTime(){

    int n = getRandomNumber();
    System.out.println(n);
    return n;

}

public int getRandomNumber() {
    int n = 1 + ((int) (Math.random() * 10)+
            (int) (System.currentTimeMillis() % 10));

    if(n > 10){
        n = getRandomNumber();
    }
    return n;
}

一般来说,更简单的代码是:

public int sumMathRandomAndSystemTime(){
    Random random = new Random();
    int n = random.nextInt(10);
    System.out.println(n);
    return n;
}

【讨论】:

    【解决方案2】:

    如果您只想打印一个介于 1 和 10 之间的随机数,请尝试这样的操作...

            int n;
            do
            {
              n = 1 + ((int) (Math.random() * 10) + (int) (System.currentTimeMillis() % 10));
            } while(n > 10);
    
            return n;
    

    【讨论】:

      【解决方案3】:

      在sumMathRandomAndSystemTime()之后添加return语句;称呼。

      public static int sumMathRandomAndSystemTime(){
          n = 1 + ((int) (Math.random() * 10)+ 
                  (int) (System.currentTimeMillis() % 10));
          if(n > 10){
              sumMathRandomAndSystemTime();
              return n;
          }
          System.out.println(n);
          return n;
      }  
      

      也许这张图可以畅通无阻。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-12
        • 1970-01-01
        相关资源
        最近更新 更多