if you want program print even number between 2 & 20
如果您想要程序打印2到20之间偶数
for(int i=2;i<=20;i++)
{
if(i%2 == 0)
print(i)
}
Start at 2 and increment by 2 to get the even numbers:
从2开始,再递增2,得到偶数:
int[] array = new int[10]
for(int counter=2; counter <= 20; counter += 2) {
array[counter/2 - 1] = counter
}
or
或
int[] array = new int[10]
for(int i=0; i <= 10; i++) {
array[i] = i*2 + 2
}
int[] array = new int[10];
for (int i = 0, j = 1; i < array.length && j <= 20; j++) {
if (j % 2 == 0) {
array[i] = j;
i++;
}
}
System.out.println(Arrays.toString(array));
Java 8: int[] array = IntStream.range(1, 11).map(x -> x * 2).toArray();
Java 8:int[]数组=IntStream.range(1,11).map(x->x*2).toArray();
Or, to just print: IntStream.range(1, 11).map(x -> x * 2).forEach(System.out::println);
或者,只打印:IntStream.range(1,11).map(x->x*2).forEach(System.out::println);
From java-9 you can use IntStream.iterate
to create int
array
在Java-9中,您可以使用IntStream.iterate创建int数组
int[] arr= IntStream.iterate(2, i->i<=20, i->i+2).toArray();
for Integer
array you can use Stream.iterate
对于整型数组,可以使用Stream.iterate
Integer[] ary = Stream.iterate(2, i->i<=20, i->i+2).toArray(Integer[]::new);
Using your code as a start, this will work:
使用您的代码作为起点,这将会起作用:
int[] array = new int[10];
for(int counter=0; counter<array.length; counter++) {
array[counter] = (counter + 1) * 2;
}
System.out.println(Arrays.toString(array));
The following will also work with Eclipse Collections:
下面的代码还将与Eclipse集合一起使用:
int[] array = IntInterval.evensFromTo(2, 20).toArray();
System.out.println(Arrays.toString(array));
Note: I am a committer for Eclipse Collections
注意:我是一名Eclipse集合的提交者
this is also an option
这也是一种选择
int i, value;
int nums[] = new int[10];
for (i = 0, value = 2; i < nums.length; value = value + 2, i = i + 1) {
nums[i] = value;
}
for (i = 0; i < nums.length; i++) {
System.out.println(nums[i]);
}
Below is an example using do-while.
下面是一个使用do-While的示例。
you can simply define a range of expected even numbers using minVal and maxVal.
你可以简单地使用minVal和maxVal定义一个期望的偶数范围。
Program will execute and return list of ordered even numbers for given range. Assuming input values are correct even numbers. You can improve to apply validations.
程序将执行并返回给定范围内的有序偶数列表。假设输入值是正确的偶数。您可以改进以应用验证。
public class EvenNumberGenerator {
static int minVal=2; //enter valid min value even number
static int maxVal = 20; //enter valid max value even number
public static void main(String[] args) {
List<Integer> evenNumbers = new ArrayList();
do {
if(minVal % 2 == 0) {
evenNumbers.add(minVal);
}
minVal++;
} while (!evenNumbers.contains(maxVal));
System.out.println(evenNumbers);
// evenNumbers.toArray(); in case you need an array
}
}
OUTPUT
输出量
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
for (int i = 0, j = 0; i < array.length; i++, j += 2)
array[i] = j;
更多回答
我是一名优秀的程序员,十分优秀!