[英]Checkerboard pattern in java with nested for loops and 2x2 grouping
I'm totally stumped on this introductory java homework question. 我对这个介绍性的Java作业问题完全感到困惑。 We have to use nested for loops to make an m by n checkerboard composed of X's and O's.
我们必须使用嵌套的for循环来制作由X和O组成的m×n棋盘。 M is the number of rows and N is the number of columns.
M是行数,N是列数。 I can make a general checkerboard pattern with the code below but the thing I'm having trouble wrapping my head around is they want the characters to be grouped in to 2x2 groupings.
我可以使用下面的代码制作一个普通的棋盘格图案,但是我无法解决的问题是他们希望将字符分组为2x2分组。 So for the code posted below the end result should look like this:
因此,对于下面发布的代码,最终结果应如下所示:
XXOO
XXOO
OOXX
I'm sure it's not that difficult but I've tried everything I can think of for several hours and still can't seem to figure it out. 我敢肯定这并不困难,但是我已经尝试了好几个小时才能想到的一切,但似乎仍然无法解决。 I'm getting super frustrated which isn't helping things either :/ Thanks in advance for any and all help!
我非常沮丧,这也无济于事://在此先感谢您的所有帮助!
public class Homework
{
public static void main (String[] args)
{
int m = 3;
int n = 4;
for(int rows = 0; rows<m; rows++)
{
for(int cols = 0; cols<n; cols++)
{
if((rows+cols)%2 ==0) System.out.print("X");
else System.out.print("O");
}
System.out.println();
}
}
}
For each value of rows
and cols
, you'll print X
if they are both 0 or 1 OR if they are both 2 or 3. The second-to-last bit in the value contains that information; 对于
rows
和cols
每个值,如果它们均为0或1或均为2或3,则将打印X
值的倒数第二位包含该信息; it's 0
if it's 0 or 1, and 1
if it's 2 or 3. You'll need to know that particular bit on both values. 它是
0
,如果是0或1, 1
,如果是2或3,您需要知道两个值的特定位。 Use value & 2
to extract the second-to-last bit. 使用
value & 2
提取倒数第二位。
Print X
if both are the same (both 0 or both 1), and O
if they aren't the same. 如果两个都相同(均为0或都为1),则打印
X
如果它们不相同,则打印O
XX | OO
|
XX | OO
(1) | (2)
----+----
(3) | (4)
OO | XX
|
OO | XX
Print the X
if both second-to-last bits are the same, else print O
. 如果两个倒数第二位相同,则打印
X
,否则打印O
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.