-1

在我的某个函数的程序中,我必须填充 9x9 数组的 3x3 正方形。乍一看,它似乎和听起来一样微不足道,但不知何故,一个 for() 循环无法正常工作。我问了我的两个朋友并检查了几次代码,但仍然找不到任何错误,如果我们不计算一个函数,一切似乎都工作得很好。我试图将其更改为其他循环,但它也没有工作。下面我给你我的代码和结果。我试图在网上搜索类似的问题,但也找不到。先感谢您!

代码:

import java.util.Random;

public class ttabela
{

    public static void main(String[] args) {
        boolean bylo[] = new boolean[10];
        int tabela[][] = new int[9][9];
        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                tabela[i][j] = 0;
            }
        }

        wypelnianiePrzekatnych(bylo, tabela,0,2);
        clear(bylo);
        System.out.println("");
        for(int i=0;i<3;i++) {
            for (int j = 0; j < 3; j++) {
                System.out.print(tabela[i][j]+" ");
            }
            System.out.println();
        }
        System.out.println("");
        for(int x=0;x<9;x++)
            System.out.print(tabela[0][x]+" ");
    }
    static int RandomBeetween ( int min, int max)
    {
        Random random = new Random();
        int a1 = random.nextInt(max - min);
        int a2 = a1 + min;
        return a2;
    }
        static void wypelnianiePrzekatnych(boolean[] bylo, int[][] tabela,int i,int j){//i=0 j=2

            int  a = i,b=i ;

            for (;a < (j+1);a++) { //This one doesnt make any difference
                for (;b < (j+1); b++) {
                    System.out.println("p "+a+" "+b+" k");

                    tabela[a][b] = RandomBeetween(1, 10);
                    System.out.println(tabela[a][b]);
                    if (bylo[tabela[a][b]] == true) {
                        do {
                            tabela[a][b] = RandomBeetween(1, 10);

                        }while (bylo[tabela[a][b]] == true);
                        bylo[tabela[a][b]] = true;
                        System.out.println(tabela[a][b]);
                    }
                    else {
                        if (bylo[tabela[a][b]] == false)
                            bylo[tabela[a][b]] = true;
                        System.out.println(tabela[a][b]);


                    }

                }
            }
        }
        static void clear(boolean[] bylo)
        {
            for(int h=0;h<10;h++)
                bylo[h]=false;
        }
        /*public static void wypelnianieReszty()
            {

            }*/
    }

结果:

p 0 0 k
7
7
p 0 1 k
8
8
p 0 2 k
3
3

7 8 3 
0 0 0 
0 0 0 

7 8 3 0 0 0 0 0 0 
4

1 回答 1

0

问题是你的内部 for 循环只会执行一次,所以外部循环在第一次迭代后没有任何东西可以运行。

我会更详细地解释。

你开始:

 int  a = i,b=i ;

假设我们像您所做的那样传入 (..., 0, 2) 。所以a = 0, b = 0

外部 for 循环将完全按预期运行 - 代码将运行直到a > (j+1)这里没有任何问题。

问题实际上在于您的第二个 for 循环:

for (;b < (j+1); b++) {

对于第一次迭代,这将按预期运行。但在那之后的任何时候,它都不会运行——因为你已经增加了 b,这样b == (j+1).

我相信有一个相当简单的解决方案,假设我已经正确解释了您的要求:

int  a = i;
int b;

for (;a < (j+1);a++) { //This one doesnt make any difference
    b = i
    for (;b < (j+1); b++) {

这是有效的,因为它在 for 循环的每次迭代之前重置 b 的值,因此它不会立即停止。

我希望这有帮助!随时在评论中提出任何问题。

于 2020-06-20T17:51:41.257 回答