簡體   English   中英

尋求使用Java創建隨機數組

[英]Looking to Create a Randomized Array using Java

我正在將用戶定義的數組構建為游戲板。 字符使用“ O”和“。” 必須隨機化,並且“ O”必須出現多次。

到目前為止,這就是我所擁有的。

import java.util.Scanner;


public class PacMan {

    public static void main(String[] args) 
    {


        Scanner input = new Scanner(System.in);
        System.out.println("Input total rows:");
        int row = input.nextInt();
        System.out.println("Input total columns:");
        int column = input.nextInt();



        boolean[][] cookies = new boolean[row+2][column+2];
        for (int i = 1; i <= row; i++)
            for (int j = 1; j <= column; j++);
                cookies [row][column] = (Math.random() < 100);

        // print game
        for (int i = 1; i <= row; i++) 
        {
            for (int j = 1; j <= column; j++)
                if (cookies[i][j]) System.out.print(" O ");
                else             System.out.print(". ");
            System.out.println();
        }
    }
}

例如,輸出產生一個5 x 5的網格,但是“ O”僅出現一次並且在網格的右下角。

協助將“ O”和“。”隨機化。 並在整個電路板上以隨機方式顯示“ O”,並由用戶通過Scanner輸入進行初始化。

這是更新的代碼,該代碼生成我正在尋找的輸出並由用戶定義。

import java.util.*;
public class PacManTest
{
    public static void main(String[] args)
    {
        char O;
        Scanner input = new Scanner(System.in);
        System.out.println("Input total rows:");
        int row = input.nextInt();
        System.out.println("Input total columns:");
        int column = input.nextInt();

        char board[][] = new char[row][column];

        for(int x = 0; x < board.length; x++)
        {
            for(int i = 0; i < board.length; i++)
            {
                double random = Math.random();
                if(random >.01 && random <=.10)
                {
                    board[x][i] = 'O';
                }

                else {
                    board[x][i] = '.';
                }
                System.out.print(board[x][i] + " ");
            }
            System.out.println("");
        }
    }
}

主要問題是第一個循環中的錯字:

cookies [row][column] = (Math.random() < 100);

應該

cookies [i][j] = (Math.random() < 100);

其次, Math.random()返回一個大於或等於0.0且小於1.0 (doc)的值 因此, (Math.random() < 100); 永遠是真的。 如果您希望有50%的機會獲得O或。 采用:

cookies[i][j] = Math.random() < 0.5;

另外,不確定使用起始索引1而是數組索引從0開始的動機是什么。

暫無
暫無

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

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