我的程序显示用户反向输入的10位数字,但我希望它只反向显示偶数。我尝试写一个if statemnt numbers[i]%2=0
,但它没有用。这是我的代码:
Scanner input = new Scanner (System.in);
int[] numbers = new int[10];
System.out.println("Enter "+numbers.length+" integer numbers: ");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = input.nextInt();
}
System.out.println("\nThe reverse of entered even numbers: ");
for (int i = numbers.length-1; i >=0; i--) {
System.out.print(numbers[i] + " ");
} System.out.print("\n"); }
答案 0 :(得分:2)
你所描述的尝试应该有效,即:
for (int i = numbers.length-1; i >=0; i--) {
if (numbers[i] % 2 == 0) {
System.out.print(numbers[i] + " ");
}
}
对所发生的事情的一个解释是,你真的做了if
声明:
if (numbers[i]%2=0) { ... }
因为你正在进行作业而不是检查相等而失败。
答案 1 :(得分:1)
int[] numbers = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Arrays.stream(numbers)
.boxed()
.sorted(Collections.reverseOrder())
.filter(i -> i % 2 == 0)
.forEach(System.out::println);
<强>更新强>
在单行上输出,其间有空格:
int[] numbers = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
String output = Arrays.stream(numbers)
.boxed()
.sorted(Collections.reverseOrder())
.filter(i -> i % 2 == 0)
.map(String::valueOf)
.collect(Collectors.joining(" "));
System.out.println(output);
答案 2 :(得分:0)
使用陈述
纠正它if (numbers[numbers.length - 1] % 2 == 0) {
//.....
}