Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to make a simple chess board in java. The input is integer n and the output must be n×n Chessboard. * represents black field and (space) represents white field. For Example, for n=5 the Chess board would be like this:

* * *
 * * 
* * *
 * * 
* * *

so far i already wrote the code like this but it has no white field just black field (*).

code

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
363 views
Welcome To Ask or Share your Answers For Others

1 Answer

The idea is to make your black and white fields dependent of both of your for-loop counters.

for(int i =0; i < n; i++) 
{
  for(int j = 0; j < n; j++)
  {
    if( (i+j) % 2 == 0){
      System.out.print("*");
    }
    else {
      System.out.print(" ");  
    }
  }
  System.out.println("");
}

or switch the " " and "*" to let your chessboard start with a white field in the upper left corner.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...