0
public class checkerBoard
{
    public static void main(String[] args)
    {

        int m = 6; //m is rows
        int n = 2; //n is columns

        char o = 'O';
        char x = 'X';

        for (int r = 1; r <= m; r++)
        {
            for (int c = 1; c <= n; c++)
            {
                if (c+r % 2 == 0)               
                    System.out.print(x);

                else
                    System.out.print(o);

                if (c == n)
                    System.out.print("\n");
            }
        }
    }
}

应该是打印

XO

XO

但相反,它打印

哦哦哦
哦哦哦
_
_

这可能是一个非常明显的解决方案,但我是新手(显然)并且无法弄清楚我做错了什么。

顺便说一下,这是 Java。

4

4 回答 4

9

尝试更改c+r % 2(c+r) % 2.

%优先于+.

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

于 2013-09-24T03:51:54.340 回答
0

尝试更改if (c+r % 2 == 0)if((c+r) % 2 == 0)

于 2013-09-24T03:54:16.710 回答
0

将您的 c+r 括在括号内,因为 % 运算符优先于 + 运算符,这导致模数在 sum 之前执行并导致错误。

public class checkerBoard
{
    public static void main(String[] args)
    {

        int m = 6; //m is rows
        int n = 2; //n is columns

        char o = 'O';
        char x = 'X';

        for (int r = 1; r <= m; r++)
        {
            for (int c = 1; c <= n; c++)
            {
                if ((c+r) % 2 == 0)               
                    System.out.print(x);

                else
                    System.out.print(o);

                if (c == n)
                    System.out.print("\n");
            }
        }
    }
}
于 2013-09-24T03:56:15.280 回答
0

问题是%优先于+. 所以,你的代码,最后,必须是这样的:

public class checkerBoard { 
    public static void main(String[] args)  {

        int m = 6; //m is rows
        int n = 2; //n is columns

        char o = 'O';
        char x = 'X';

        for (int r = 1; r <= m; r++) {
            for (int c = 1; c <= n; c++) {
                if ((c+r) % 2 == 0){ //% takes precedence over +                
                    System.out.print(x);
                } else {
                    System.out.print(o);
                }
            }

            System.out.print("\n");
        }
    }
}
于 2013-09-24T04:03:33.830 回答