簡體   English   中英

我如何用隨機值填充二維數組

[英]How Do i populate a 2d array with random values

我有一項任務,以0-9之間的隨機數填充數組。 然后以矩形格式打印出來。 我已經很難嘗試將隨機整數放入數組中。 請指出正確的方向

import java.util.*;
public class ThreebyFour
{
    public static void main (String[] args)
    {
     int values[][] = new int[3][4];
     for (int i = 0; i < values.length; i++) 
     {
        for (int j = 0; j < values.length; j++) 
        {
          values[i][j] = ((int)Math.random());
         System.out.println(values[i][j]);
        }
     }
 }
}

代碼中的外觀問題:

喜歡:

values[i][j] = ((int)Math.random());

由於隨機值的返回值介於0和1之間的互斥[0,1)之間,因此會將所有元素分配為零,而轉換為整數的結果將返回零。

和這個:

for (int j = 0; j < values.length; j++) 

如果您計算該行的元素,第二個for循環會更好...就像我在評論中所寫的那樣...

即做:

for (int j = 0; j < values[i].length; j++) {

固定代碼:

public static void main(String[] args) {
    int values[][] = new int[3][4];
    for (int i = 0; i < values.length; i++) {
        // do the for in the row according to the column size
        for (int j = 0; j < values[i].length; j++) {
            // multiple the random by 10 and then cast to in
            values[i][j] = ((int) (Math.random() * 10));
            System.out.print(values[i][j]);
        }
        // add a new line
        System.out.println();
    }
    System.out.println("Done");
}

您可以執行Math.round (Math.random() * 10) 我建議閱讀Javadoc並了解random()方法的作用。

https://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#random()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM