Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.


1 Answers

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");
}
like image 111
Yassin Hajaj Avatar answered Jan 02 '26 10:01

Yassin Hajaj