[英]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.