简体   繁体   English

通过二维数组中随机生成的数字打印字符数

[英]Printing the number of char's by a randomly generated number in a 2D Array

I was wondering how to go about randomly generating a number, and then having it print that number as a character. 我想知道如何随机生成一个数字,然后将其打印为字符。 This is what I have so far. 到目前为止,这就是我所拥有的。

import java.util.Scanner;
public class Main
{
    public static void main (String[] args){
    Scanner scan = new Scanner(System.in);

    int[][] ground = new int[12][12];
    int mineNum;

    System.out.print ("Please Enter an Integer");

    int num = scan.nextInt();

    if(num > -1 && num <145){
        for (int i=0; i<ground.length; i++){
            for (int j = 0; j < ground[i].length;j++){
                ground[i][j] = mineNum;
            }
        }
    }
}

I'm thinking that you definitely have to have the random int stored in a variable. 我认为您绝对必须将随机int存储在变量中。 But from there I want to have the random int's that the user put in and translate that as X', and input those x's randomly into the array, so I would have to translate that number into number of char, and then insert it randomly into the array with another for? 但是从那里我想得到用户放入的随机int并将其转换为X',然后将那些x随机输入到数组中,因此我将不得不将该数字转换为char的数量,然后将其随机插入与另一个数组? The idea is to look something like , for example, say mineNum is 5, it would look something like this once printed for a 3x9 grid. 这个想法是看起来像,例如,mineNum是5,一旦为3x9网格打印,它将看起来像这样。

0 0 0 0 X 0 X 0 0 0 0 0 0 X 0 X 0 0

0 0 X 0 0 0 0 0 0 0 0 X 0 0 0 0 0 0

0 0 0 0 XX 0 0 0 0 0 0 0 XX 0 0 0

One option would be to generate 5 distinct random numbers within the dimensions of your 2D grid which would represent Xs. 一种选择是在2D网格的尺寸范围内生成5个不同的随机数,它们代表Xs。 Then fill everything else with Os. 然后用OS填充其他所有内容。 I generate random numbers between 0 and dim^2 - 1 . 我生成介于0和dim^2 - 1 2-1之间的随机数。 Then I add them to a set until the desired number of random positions has been reached. 然后,将它们添加到集合中,直到达到所需的随机位置数量为止。 Finally, I convert those numbers to x/y dimensions to place the Xs onto the board. 最后,我将这些数字转换为x / y尺寸,以将Xs放置在板上。

Scanner scan = new Scanner(System.in);

int dim = 5;
char[][] ground = new char[dim][dim];
Set<Integer> xSet = new HashSet<>();

System.out.print ("Please Enter an Integer");
int mineNum = scan.nextInt();

Random rand = new Random();
while (xSet.size() < mineNum) {
    int randomNum = rand.nextInt(dim*dim);
    xSet.add(randomNum);
}

// default everything to being Os
for (int r=0; r < dim; ++r) {
    for (int c=0; c < dim; ++c) {
        ground[r][c] = 'O';
    }
}

// then overwrite with Xs
for (int num : xSet) {
    int x = num % dim;
    int y = num / dim;
    ground[x][y] = 'X';
}

System.out.println(Arrays.deepToString(ground).replace("], ", "]\n").replace("[[", "[").replace("]]", "]"));

[O, O, O, O, O]
[O, O, O, X, X]
[O, O, X, O, O]
[O, O, X, O, O]
[O, O, O, X, O]

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM