Wrong shape when program run

73 Views Asked by At
import java.util.Scanner;
public class Ideone
{

    public static void main(String[] args) 
    {
        int reader;
        Scanner kBoard = new Scanner(System.in);
        do
        {
            System.out.println("Insert a number of rows: ");

                reader = kBoard.nextInt();
                printDiamond(reader); 


        }while(reader != 0);

    }

    public static void printWORD(int n)
    {
        if(n >= 1)
        {
          System.out.print("SAMPLE");
            printWORD(n - 1);
        }
    }

    public static void printTopTriangle(int rows)
    {
        int x = 1;
        for(int j = (rows - 1); j >= 0; j--,x +=2)
        {
            printSpaces(j);
            printWORD(x);
            System.out.print("\n");
        }
    }

    public static void printSpaces(int n)
    {
        if(n >= 1)
        {
            System.out.print(" ");
            printSpaces(n - 1);
        }
    }

    public static void printBottomTriangle(int rows, int startSpaces)
    {
        int x = 1 + (2*(rows - 1));
        for(int j = startSpaces; j <= (rows) && x > 0; j++,x -=2)
        {
            printSpaces(j);
            printWORD(x);
            System.out.print("\n");
        }
    }
    public static void printBottomTriangle(int rows)
    {
        int x = 1 + (2*(rows - 1));
        for(int j = 0; j <= (rows - 1) && x > 0; j++,x -=2)
        {
            printSpaces(j);
            printWORD(x);
            System.out.print("\n");
        }
    }

    public static void printDiamond(int rows)
    {
        printTopTriangle((int)rows/2 + 1);
        printBottomTriangle((int)rows/2, 1);
    }
}

My program is supposed to show a Diamond Shape made out of the word "SAMPLE." But when I run it, it displays a space ship shape. How do I fix this error so it would print a perfect Diamond with the word "SAMPLE"?

3

There are 3 best solutions below

0
On BEST ANSWER

Change these methods as follows:

public static void printTopTriangle(int rows)
   ...
   printSpaces(j*6);



public static void printBottomTriangle(int rows, int startSpaces)
   ...
   printSpaces(j*6);

Note: 6 is the length of the constant SAMPLE

0
On

Because of the size of "SAMPLE" (6 chars), you have to indent with System.out.print(" "); (ie. 6 spaces not 1).

Runnable demo: http://ideone.com/JHTU6C

NB: I didn't fix anything else (you might want to check if an int exists before asking for it with nextInt())

0
On

If you change "SAMPLE" with "*" or any other char you get a diamond shape. You get a space ship shape because you don't put enough spaces in printSpaces method. Number of spaces should be close the number of chars that you print in printWORD method. Put 5 or 6 spaces in printSpaces method and you will get something close to a diamond.