I'm trying to practice my rather poor Java, and I came across this site. http://www.homeandlearn.co.uk/exercises/programming_exercises.html
I am doing exercise 6, and the exercise is to create a 2d string checkerboard using the words black and white. This looks something like
http://www.homeandlearn.co.uk/exercises/images/checkerboard.png
I did this with not too much problem, but I wanted to challenge myself further. I modified the program (or tried to) in order to create an ACTUAL 2d checkerboard, like a chessboard, but failed miserably.
Here's my code with swing:
import java.applet.*;
import java.awt.*;
import javax.swing.*;
public class exercise6 extends JFrame{
public Image black;
public Image white;
JPanel p = new JPanel();
public int rows = 8;
public Image checkerboard[][] = new Image[rows][rows];
public static void main(String[] args) {
for(int i=0; i<rows; i++) {
for(int j=0; j<rows; j++) {
if(i == j)
checkerboard[i][j] = white;
else if(i== j-2)
checkerboard[i][j] = white;
else if(i== j+2)
checkerboard[i][j] = white;
else if(i==j-4)
checkerboard[i][j] = white;
else if(i==j+4)
checkerboard[i][j] = white;
else
checkerboard[i][j] = black;
}
}
new exercise6();
}//ends the main method
public exercise6() {
super("Checkerboard");
setResizable(false);
setSize(800,800);
setDefaultCloseOperation(CLOSE_ON_EXIT);
p.add(checkerboard);
add(p);
setVisible(true);
}
}
Here's my code when it worked:
public class checkerboard{
public static void main(String[] args) {
int rows = 8;
String checkerboard[][] = new String[rows][rows];
for(int i=0; i<rows; i++) {
for(int j=0; j<rows; j++) {
if(i == j)
checkerboard[i][j] = "white ";
else if(i== j-2)
checkerboard[i][j] = "white ";
else if(i== j+2)
checkerboard[i][j] = "white ";
else if(i==j-4)
checkerboard[i][j] = "white ";
else if(i==j+4)
checkerboard[i][j] = "white ";
else if(i==j+6)
checkerboard[i][j] = "white ";
else if(i==j-6)
checkerboard[i][j] = "white ";
else
checkerboard[i][j] = "black ";
System.out.print(checkerboard[i][j]);
}
System.out.println();
}
}
}