[英]Fill double array with random numbers and then print even and odd numbers from that array
所以這是我的問題。 我必須編寫一個程序,該程序將用隨機數填充數組(沒關系),然后只需要打印偶數索引號或只打印奇數值( j
)。 嘗試過這種方法,但是當我放入if
語句時,它顯示了每個偶數(索引和值-數組中的第二個),所以它出錯了。 我該怎么辦?
import java.util.Random;
public class Array {
public static void main(String[] args)
{
int rows = 5;
int colu = 2;
Random r = new Random();
int [][] array = new int [rows][colu];
for(int row = 0; row < array.length; row++)
{
for(int col = 0; col < array[row].length; col++)
{
array[row][col] = r.nextInt(10);
}
}
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < array[i].length; j++)
{
if(array[i][j]%2 == 0){
System.out.print(array[i][j] + " ");
}
}
}
System.out.println();
}
}
謝謝
我將為此采取行動,但是我不確定我是否還了解。
int array[][] = new int[row][col];
// ... populate the array with random numbers, works fine...
// Let's traverse the first column.
for (int i = 0; i < row; i++) {
int value = array[i][0]; // col 0 means first column
if (value % 2 == 0) {
// ...
}
}
// Let's traverse the second column.
for (int i = 0; i < row; i++) {
int value = array[i][1]; // col 1 means second column
// ...
}
你是這個意思嗎? 如果是這樣,您是否看到了模式,以及如何將其概括化並使代碼更小一些?
只需在您的“ if”語句中實現此公式即可:
(數×2)/ 4 == 0。 您將永遠得到偶數。 您可以處理其余的:D
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.