【问题标题】:Looking to Create a Randomized Array using Java希望使用 Java 创建一个随机数组
【发布时间】:2017-07-05 20:35:01
【问题描述】:

我正在构建一个用户定义的数组作为游戏板。字符使用“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”以随机方式出现在整个板上,由用户通过扫描仪输入初始化。

这是生成我正在寻找的输出并且是用户定义的更新代码。

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("");
        }
    }
}

【问题讨论】:

标签: java arrays random


【解决方案1】:

主要问题是第一个循环中的错字:

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

应该是

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

其次,Math.random() 返回一个大于等于 0.0 且小于 1.0 的值(doc)。所以,(Math.random() &lt; 100); 永远是正确的。如果您想要 50% 的机会获得 O 或 .使用:

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

另外,不确定您使用1 的起始索引的动机是什么,但数组索引从0 开始。

【讨论】:

  • 约翰尼谢谢。所以我实际上已经设法实现了创建我正在寻找的东西。
  • 现在我已经构建了用户定义的游戏板,其中包含随机的“O”字符,这些字符充当定义为“”的开放面,并且能够使用用户定义的动作在棋盘上移动。这将根据用户的移动创建符号“>”、“V”、“
  • @JoshuaPeterson 为存储当前行、列、方向的播放器创建一个类。然后你需要一个循环来读取键盘并根据用户输入移动播放器。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-21
  • 1970-01-01
  • 1970-01-01
  • 2013-01-27
  • 2011-12-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多