Java:如何设置一个2D字符数组,其中指定的某些字符只占网格的一个百分比?

Java:如何设置一个2D字符数组,其中指定的某些字符只占网格的一个百分比?,java,arrays,string,character,Java,Arrays,String,Character,各位晚上好,, 我有一个问题,我必须打印一个由三个字符(X、O和一个空格“”)占据的网格数组。这些字符由用户指定为仅占一定百分比(X和O将始终相等)。 我对数组不是很在行,所以我不确定如何从数组的角度来看待这个问题,或者在这种情况下数组是否是必要的 我通过合并Math.Random和通过if使用一种案例系统来解决这个问题。我的问题是我不完全确定如何限制字符的打印 公共静态细胞类型(字符[][]组织,整数百分比空白,整数百分比X){ int n=5; int i; int j; 字符[][]框=新

各位晚上好,, 我有一个问题,我必须打印一个由三个字符(X、O和一个空格“”)占据的网格数组。这些字符由用户指定为仅占一定百分比(X和O将始终相等)。 我对数组不是很在行,所以我不确定如何从数组的角度来看待这个问题,或者在这种情况下数组是否是必要的

我通过合并Math.Random和通过if使用一种案例系统来解决这个问题。我的问题是我不完全确定如何限制字符的打印

公共静态细胞类型(字符[][]组织,整数百分比空白,整数百分比X){

int n=5;
int i;
int j;
字符[][]框=新字符[n][n];
int a=0;
int b=0;
int c=0;
对于(i=0;i如果(q>=.5&&a您可以做的第一件事是:

n=5,因此矩阵为5 x 5,则将存储25项

如果百分比x=30%,则itemsX=(int)Math.rint((n*n)*(百分比x/100))

如果percentBlank=40%,则itemsBlank=(int)Math.rint((n*n)*(percentBlank/100))

所以我们可以计算itemsO=(n*n)-(itemsBlank+itemsX)

这将为您提供矩阵中每种类型X、O或空白的项数

您必须初始化计数器:

     int countBlank int = 0; 
     int countX = 0;
     int countO = 0; 
我们随机得到了X,O或者空白字符。 我们使用:

 int q = (int) (Math.random ()*3); 
这将返回一个介于0和2之间的整数->[0,1,2]

if (q == 0) { // We obtained a Blank, add +1 to the counter and store or print to the console the character ' '
   if (countBlank < itemsBlank) {
       System.out.print("' ' "); // Or box[i][j]=' '
       countBlank +=1;
   } else {
       j-=1; // If the quota is reached Blank, subtract 1 from j to try to get other character in that position in the array.   
   }                        
} 
if (q == 1) { // We obtained a 'O'
    if (countO < itemsO) {
       System.out.print("'O' ");
       countO+=1;
    } else {
       j-=1;
    }    
}
if (q == 2) { // We obtained a 'X'
    if (countX < itemsX) {
       System.out.print("'X' ");
       countX+=1;
    } else {
       j-=1;
    }    
}     
如果(q==0){//我们得到一个空白,将+1添加到计数器,并将字符“”存储或打印到控制台
if(countBlank
在我看来,您可以通过两种方式工作:1.在数组
框[]中存储值
然后打印。2.直接到控制台输出。这对我来说是一个巨大的帮助,即使第一个条目告诉我要将字符分解为大量项目。我最终设计了一个类似的配额系统,使用了Math.Random,结果在逻辑上与此非常接近。非常感谢!(并不是想这么早就点击回车并发送评论)。
if (q == 0) { // We obtained a Blank, add +1 to the counter and store or print to the console the character ' '
   if (countBlank < itemsBlank) {
       System.out.print("' ' "); // Or box[i][j]=' '
       countBlank +=1;
   } else {
       j-=1; // If the quota is reached Blank, subtract 1 from j to try to get other character in that position in the array.   
   }                        
} 
if (q == 1) { // We obtained a 'O'
    if (countO < itemsO) {
       System.out.print("'O' ");
       countO+=1;
    } else {
       j-=1;
    }    
}
if (q == 2) { // We obtained a 'X'
    if (countX < itemsX) {
       System.out.print("'X' ");
       countX+=1;
    } else {
       j-=1;
    }    
}