生成二维数组中的随机数
我正在使用 Java 创建一个战舰游戏,但我在生成 2 个随机数(随机选择战舰板上的一个位置)时遇到问题。例如,计算机必须在棋盘上随机选择一个空间来放置船只(然后进行射击)。
我创建了一个二维数组:
int rows = 10;
int cols = 10;
char [][] grid;
grid = new char[rows][cols];
然后尝试了几种不同的方法来获取数组中的两个随机数,但我无法让它工作。这是我尝试过的示例:
int randomPos = (char) (Math.random() * (grid[rows][cols] + 1));
如果这没有意义,请问我一些问题。
肖恩
I am creating a game of Battleships using Java and I am having trouble generating 2 random numbers which randomly choose a place on the battleship board. For example, the computer has to randomly choose a space on the board to place the ships (and later to shoot on).
I have created a 2D array:
int rows = 10;
int cols = 10;
char [][] grid;
grid = new char[rows][cols];
And then tried several different ways to get the two random numbers in the array but I cannot get it to work. Here is an example of what I have tried:
int randomPos = (char) (Math.random() * (grid[rows][cols] + 1));
Please ask me some questions if this doesn't make sense.
Sean
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Math.random()
生成一个十进制数。平方3.5779789689689...
(或您所指的任何内容)没有任何意义,因此请使用Math.floor()
方法,该方法会四舍五入里面的数字最接近的整数。正如@Sanjay 所解释的,单独生成数字......现在你有了可以使用的实际整数。
Math.random()
generates a decimal number. It doesn't make any sense to have square3.5779789689689...
(or whatever you're referring to), so use theMath.floor()
method, which rounds the number inside to the nearest integer. And as @Sanjay explained, generate the numbers separately...Now you have actual integers that you can work with.
分别生成两个随机数并使用它们来索引您的板。详细说明:
在您的情况下,随机数的范围应在 0 到 9 之间(包括两者)。
Generate two random numbers separately and use them to index your board. To elaborate:
In your case, the range of the random number should be between 0 and 9 (inclusive both).
我不会使用 char 作为网格类型,但无论数组中的类型如何,上面的代码都可以正常工作。
I wouldn't use char as my grid type, but the code above works all the same regardless of the types of in the array.
尝试声明这是一个 ivar:
Try this declare this is an ivar: