0

The assignment: "Write a program that takes a positive integer n and displays an n x n checkerboard. Write the program so that it works for different values of n by changing only one line in your code. Use un-editable textfield objects in a gridpane and change the colors using css.

I can't wrap my head around why my code only generates two rows and too many columns? I'm just trying to make 5x5. Sorry for the lack of javadoc comments.

    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.control.TextField;
    import javafx.scene.layout.GridPane;
    import javafx.stage.Stage;


    public class SD_Checkerboard extends Application {
    @Override
    public void start(Stage s) {
     //Create the integers for creating the grid.
    int n=5;
    int row;
    int column;



    //Create the gridpane.
    GridPane grid = new GridPane();

     for(row=0; row<n; row++) {
     for(column=0; column<n; column++) {
   TextField box = new TextField();
   box.setEditable(false);

   if(row + column % 2== 1){
     box.setStyle("-fx-background-color: black");
     grid.add(box,column,row);
   }
   else {
    box.setStyle("-fx-background-color: white");
    grid.add(box,column,row);
   }

   }
   }
     s.setScene(new Scene(grid));
     s.setTitle("Checkerboard");
      s.show();

    }

    public static void main(String[] args) {
      launch(args); 
      }

     }
James_D
  • 201,275
  • 16
  • 291
  • 322

1 Answers1

1

Like multiplication and division, modulo arithmetic has a higher precedence than addition. So row + column % 2 should be (row + column) % 2.

The text fields are there, they're just not getting colored the way you think: basically once you get to row=2 they are all white (because row + column % 2 is the same as row + (column % 2), which is always >1 if row>1).

James_D
  • 201,275
  • 16
  • 291
  • 322