为什么我的代码只输出“O”?

时间:2013-09-24 03:49:33

标签: java

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
OX
XO
OX

但相反它打印

OO
OO
OO
OO

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

顺便说一句,这是Java。

4 个答案:

答案 0 :(得分:9)

尝试将c+r % 2更改为(c+r) % 2

%优先于+

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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

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");
            }
        }
    }
}

答案 3 :(得分: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");
        }
    }
}