【发布时间】:2020-08-11 12:58:03
【问题描述】:
我正在练习算法,假设我们有一个包含元素 2, 3, 9, 12, 7, 18 的数组,那么 我只想打印 18,因为它是 9 的两倍。当我打印结果时,它总是显示更多的行,但是,打印的数字(如果有的话)很好。如何管理正确显示结果? (仅使用数组。)我知道这是一个愚蠢的问题,但我尝试了很多方法,结果只会更糟。
现在,它向我展示了这个示例(140 是正确的,但不需要另一行):
The following number is doubled of another number from the array: 0
The following number is doubled of another number from the array: 0
The following number is doubled of another number from the array: 140
The following number is doubled of another number from the array: 0
The following number is doubled of another number from the array: 0
我的代码:
public class DoubleNums {
public static void main(String[] args) {
Random random = new Random();
int[] array = new int[50];
int[] even;
int[] doubleNum;
int count = 0;
int doubles = 0;
for (int i = 0; i < array.length; i++) {
array[i] = random.nextInt(200);
System.out.println(array[i] + " ");
}
for (int j = 0; j < array.length; j++) {
even = new int[array.length];
if (array[j] % 2 == 0) {
even[count] = array[j];
count++;
}
for (int k = 0; k < array.length; k++) {
doubleNum = new int[array.length];
if (array[j] / 2 == array[k]) {
even[doubles] = k;
doubles++;
System.out.println("The following number is doubled of another number from the array: " + even[doubles]);
}
}
}
System.out.println("Number of even nums: " + count);
}
}
【问题讨论】:
-
您应该检查
j不等于k。此外,您可以在第二个 for 循环(外部循环)中重用名称i -
您使用 'array[j] / 2 == array[k]' 作为条件。因为一切都是整数,记住 5/2 == 2,所以最好使用 'array[j] = (array[k] * 2)'