【问题标题】:How to rewrite this lines of code in a more "elegant" way?如何以更“优雅”的方式重写这行代码?
【发布时间】:2015-03-03 15:01:22
【问题描述】:

所以我有这行代码,我正在尝试找到一种更优雅的方式来编写它们:

         int randomHints1 = hintsRandom.nextInt(1200-100) + 100;
         int randomHints2 = hintsRandom.nextInt(1200-100) + 100;
         int randomHints3 = hintsRandom.nextInt(1200-100) + 100;
         int randomHints4 = hintsRandom.nextInt(1200-100) + 100;
         int randomHints5 = hintsRandom.nextInt(1200-100) + 100;
         int randomHints6 = hintsRandom.nextInt(1200-100) + 100;
         int randomHints7 = hintsRandom.nextInt(1200-100) + 100;
         int randomHints8 = hintsRandom.nextInt(1200-100) + 100;
         int randomHints9 = hintsRandom.nextInt(1200-100) + 100;
         int randomHints10 = hintsRandom.nextInt(1200-100) + 100;

我猜“for 循环”方法会是答案,但我找不到解决此问题的方法。 非常感谢你们。

【问题讨论】:

    标签: java for-loop int


    【解决方案1】:
    int[] randomHints = new int[10];
    for(int i=0;i<randomHints.length;i++)
        randomHints[i] = hintsRandom.nextInt(1100) + 100;
    

    【讨论】:

      【解决方案2】:

      利用数组

      int[] randomHints = new int[10];
      for (int i = 0; i < randomHints.length; i++) {
          randomHints[i] = hintsRandom.nextInt(1200 - 100) + 100;
      }
      

      【讨论】:

        【解决方案3】:

        如果你使用数组会更优雅:

        int[] randomHints = new int[10];
        ...
        for(int i = 0;i<randomHints.length;i++) {
            randomHints[i] = hintsRandom.nextInt(1200-100) + 100;
        }
        

        ps.:如果您需要动态数量的随机数,您可以使用数组列表

        【讨论】:

          【解决方案4】:

          我的答案和其他人基本一样,都是用数组和迭代,但是我用Java 8流写成一行。我认为它更优雅。

          int[] randomHints = new int[10];
          Arrays.stream(randomHints).forEach(i -> randomHints[i] = hintsRandom.nextInt(1200 - 100) + 100);
          

          【讨论】:

          • 这是一个不错的方法!
          【解决方案5】:
          int[] randomHints = IntStream.generate(() -> 100 + hitsRandom.nextInt(1100)).limit(10).toArray();
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2017-03-31
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2023-02-05
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多