Question by Francis McHydesinyourpants: Help me with a java programming “checkerboard” Exercise?
I have a java programming assignment for college that i have been stuck on for a while. the brief is:
Write a Java program called HappyFaces that displays the folowing checkerboard pattern:
:-):-):-):-):-):-)
(-:(-:(-:(-:(-:(-:
:-):-):-):-):-):-)
(-:(-:(-:(-:(-:(-:
:-):-):-):-):-):-)
(-:(-:(-:(-:(-:(-:

I thought i had it but i just cant seem to get it write. My code looks like this:
public class HappyFaces
{
public static void main(String[] args)
{
int x=1;
int y=1;
int z=1;

while (z <= 3) { while (x<=6) { System.out.print(":-)"); x++; } System.out.println(""); while (y <= 6) { System.out.print("(-:"); y++; } System.out.println(""); z++; } } } im not asking for people to do my work for me here. I just would like some pointers so i can see where i am going wrong Best answer:

Answer by JD
Since you are using loops within loops you need to reinitialize the variables before use every time, otherwise the variable check will fail the next time the loop runs since it will already be equal to 6. So either do x=1 and y=1 to reinitialize or use for loops instead of whiles.

Add your own answer in the comments!

One thought on “Help me with a java programming “checkerboard” Exercise?”

  1. what u have is more or less too hard coded
    see if this makes sense to you…

    public class HappyCheckers {

    public static void main(String[] args) {
    String s = “”;
    int rows = 6;
    int cols = 6;
    for (int i = 0; i <= rows; i++) { for (int j = 0; j <= cols; j++) { System.out.print( s = (i % 2 == 0) ? ":-)" : "(-:"); } System.out.println(); } } } ............. if the line: s = (i % 2 == 0) ? ":-)" : "(-:"); does not make sense to you, you could rewrite that as: for (int i = 0; i <= rows; i++) { if (i % 2 == 0) { s = ":-)"; } else { s = "(-:"; } for (int j = 0; j <= cols; j++) { System.out.print(s); } System.out.println(); }

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.