简体   繁体   English

使用Java中的数组创建滑动数字拼图板

[英]Creating a sliding number puzzle board using arrays in Java

So I'm kind of new to Java and decided to create a sliding number puzzle of some sort. 因此,我是Java的新手,因此决定创建某种类型的滑动数谜题。 Here's what I have : 这是我所拥有的:

int[] puz = {1,2,3,
             4,5,6,
             7,8,9}
for(int i=0; i<puz.length; i++){
    System.out.println(puz[i]);
}

The 1 is supposed to be the blank spot but I'll figure that out later. 1应该是空白点,但我稍后会弄清楚。 My problem is that the code prints: 我的问题是代码显示:

1
2
3
4
5
6
7
8
9

when I want it to print: 当我要打印时:

1 2 3
4 5 6
7 8 9

I've also tried doing a nested loop that I'm too embarrassed to show on here due to how hideous it was. 我也曾尝试做一个嵌套循环,由于它是如此的丑陋,我对此感到很尴尬而无法在这里展示。 Would I try using a 2d array instead? 我会尝试使用二维数组吗?

I guess you could try... 我想你可以尝试...

int puz = {1,2,3,4,5,6,7,8,9};
int n = Math.ceil(Math.sqrt(puz.length));
for (int i = 0; i < puz.length; i++) {
    System.out.print(puz[i] + ((i + 1) % n == 0 ? "\r\n" : " ");
}

Try creating a variable counter and increment it every time you iterate through the loop. 尝试创建一个变量计数器,并在每次循环时对其进行递增。 Using a modulus operator, divide it by 3 and when remainder is 0, create a new line. 使用模运算符,将其除以3,然后当余数为0时,创建新行。

int puz = {1,2,3,4,5,6,7,8,9};

int counter = 1;
for(int i=0; i<puz.length; i++){
    System.out.print(puz[i]);
    if (counter % 3 == 0){
        System.out.println("");
    }
    counter++;
}

The trick here is to use the modulus operator. 这里的窍门是使用模运算符。 This operator divides one number by another, and returns the remainder. 该运算符将一个数除以另一个,然后返回余数。 In java (and everywhere else as far as I know), % is the modulus operator. 在Java中(据我所知,在其他所有地方), %是模数运算符。 If you want every third number to have a line break after it, simply divide by three using modulus division, like so: 如果要让第三个数字后面有换行符,只需使用模数除以三,例如:

int[] puz = {1,2,3,4,5,6,7,8,9};
    //For what it's worth, you don't have this semicolon in your question, so I added it in.
for(int i=0; i<puz.length; i++){
    System.out.print(puz[i] + " ");
    if(i % 3 == 2){//It's equal to 2 because you start at 0 and not 1.
        System.out.println("");
    }
}

This code, when executed, prints the following, which is what you wanted: 该代码在执行后会打印出您想要的内容:

1 2 3 
4 5 6 
7 8 9 

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

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