如何以更"elegant"的方式重写这行代码?
How to rewrite this lines of code in a more "elegant" way?
所以我有这行代码,我正试图找到一种更优雅的方式来编写它们:
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 loop" 方法会是答案,但我找不到解决这个问题的方法。
非常感谢你们。
int[] randomHints = new int[10];
for(int i=0;i<randomHints.length;i++)
randomHints[i] = hintsRandom.nextInt(1100) + 100;
利用数组
int[] randomHints = new int[10];
for (int i = 0; i < randomHints.length; i++) {
randomHints[i] = hintsRandom.nextInt(1200 - 100) + 100;
}
如果使用数组会更优雅:
int[] randomHints = new int[10];
...
for(int i = 0;i<randomHints.length;i++) {
randomHints[i] = hintsRandom.nextInt(1200-100) + 100;
}
ps.: 如果你需要动态数量的随机数,你可以使用数组列表
我的回答和别人基本一样,都是用数组和迭代,但是我是用Java8个流写在一行里的。我觉得这样更优雅。
int[] randomHints = new int[10];
Arrays.stream(randomHints).forEach(i -> randomHints[i] = hintsRandom.nextInt(1200 - 100) + 100);
int[] randomHints = IntStream.generate(() -> 100 + hitsRandom.nextInt(1100)).limit(10).toArray();
所以我有这行代码,我正试图找到一种更优雅的方式来编写它们:
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 loop" 方法会是答案,但我找不到解决这个问题的方法。 非常感谢你们。
int[] randomHints = new int[10];
for(int i=0;i<randomHints.length;i++)
randomHints[i] = hintsRandom.nextInt(1100) + 100;
利用数组
int[] randomHints = new int[10];
for (int i = 0; i < randomHints.length; i++) {
randomHints[i] = hintsRandom.nextInt(1200 - 100) + 100;
}
如果使用数组会更优雅:
int[] randomHints = new int[10];
...
for(int i = 0;i<randomHints.length;i++) {
randomHints[i] = hintsRandom.nextInt(1200-100) + 100;
}
ps.: 如果你需要动态数量的随机数,你可以使用数组列表
我的回答和别人基本一样,都是用数组和迭代,但是我是用Java8个流写在一行里的。我觉得这样更优雅。
int[] randomHints = new int[10];
Arrays.stream(randomHints).forEach(i -> randomHints[i] = hintsRandom.nextInt(1200 - 100) + 100);
int[] randomHints = IntStream.generate(() -> 100 + hitsRandom.nextInt(1100)).limit(10).toArray();