gpt4 book ai didi

java - 如何使用数组创建嵌套 for 循环以从 java 中的一组数字中提取特定数字?

转载 作者:行者123 更新时间:2023-12-01 19:19:25 25 4
gpt4 key购买 nike

所以,我试图创建一个嵌套的 for 循环来从一组数字中提取所有偶数,但我希望它停在 238,而不是一路遍历所有数字。这是我到目前为止所得到的,但我觉得我做错了什么。更具体地说,我需要能够读取下面列出的所有数字,然后按照显示的顺序提取所有偶数,且不超过 238。

public class test {
public static void main(String[] args) {
int[] numbers = {
951, 402, 984, 651, 360, 69, 408, 319, 601, 485, 980, 507, 725, 547, 544,
615, 83, 165, 141, 501, 263, 617, 865, 575, 219, 390, 984, 592, 236, 105, 942, 941,
386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345,
399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950, 626, 949, 687, 217,
815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81, 379, 843, 831, 445, 742, 717,
958, 609, 842, 451, 688, 753, 854, 685, 93, 857, 440, 380, 126, 721, 328, 753, 470,
743, 527};

int[] arr = {};
for (int i = 0; i < arr.length; i++) {
int el = arr[i];
System.out.println(el);
}

int[] input = {};
for (int i = 0; i < 238; i++) {
for (i = 0; i < 238; i++) {
if ( i >= 237) {
break;
}
}
}
}
}

最佳答案

这个怎么样:

  • 过滤所有小于或等于要求的值 (max = 238)
  • 过滤所有偶数值
<小时/>
public static int[] findAllEvenNumbers(int[] arr, int max) {
return IntStream.range(0, arr.length)
.filter(v -> v <= max)
.filter(v -> (v & 1) == 0).toArray();
}

关于java - 如何使用数组创建嵌套 for 循环以从 java 中的一组数字中提取特定数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59378881/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com