简体   繁体   中英

I'm trying to print this without just doing println for each line

I want to print this by using nest for lops and/or if statements

ABABABAB
BABABABA
ABABABAB
BABABABA
ABABABAB
BABABABA
ABABABAB
BABABABA
public class chess {

    public static void main(String[] args) {
            // TODO Auto-generated method stub


            for (int i=0; i<4; i++)
            {
                for (int r = 0; r < 1; r++)
                {
                    if (r%2== 0)
                    {
                            System.out.print("A");

                    }

                    if (r%2==1)
                    {
                            System.out.print("B");

                    }
                }

                for (int x = 0; x < 1; x++)
                {
                    if (x%2== 0)
                    {
                            System.out.print("B");

                    }

                    if (x%2 == 1)
                    {
                            System.out.print("A");

                    }
                }

            }

    }

}

output is just: ABABABAB

I don't want to just do System.out.println("BABABABA") back & forth.

THANKS! I'm new to coding and any help is appreciated.

With this code, you should obtain what you want without using System.out.println() once.

You just check if the sum of i and j is a pair and print A if it is, B if it is not.

for (int i = 0 ; i < 8 ; i++){
    for (int j = 0 ; j < 8 ; j++){
        if ((i+j)%2 == 0) System.out.print("A");
        else System.out.print("B");
    }
    System.out.print("\n");
}

Avoid if's whenever possible:

for (int i = 0 ; i < 8 ; i++){
    for (int j = 0 ; j < 8 ; j++){
        System.out.print( (char)('A' + (i+j)%2) );
    }
    System.out.println();
}

(You can replace %2 with %3, %4,... for other interesting patterns.)

for (int i = 0; i < 8; i++)
{
    if(i % 2 == 0)
    {
        for (int r = 0; r < 8; r++)
        {
            if (r % 2 == 0)
            {
                 System.out.print("A");
            }
            if (r % 2 == 1)
            {
                 System.out.print("B");
            }
        }
    }
    else
    {
        for (int r = 0; r < 8; r++)
        {
            if (r % 2 == 0)
            {
                 System.out.print("B");
            }
            if (r % 2 == 1)
            {
                 System.out.print("A");
            }
        }
    }
    System.out.print("\n");
}

Changing the value i iterates up to will change the number of rows, and changing the value r iterates up to will change the number of A 's and B 's you print out per row.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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