Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Bhawani Shankar
Bhawani Shankar
954 Points

Why my code is not printing X pattern

This is my code please help!

package pattern;

public class Xpattern {

public static void main(String[]args) {
       for(int i=1;i<5;i++){
           for(int j=1;j<5;j++){
               if (i==j||i+j==5-1){
                   System.out.print(" * ");
               }
               else{
                   System.out.print(" ");
               }
               System.out.println();
               }
           }
       }

}

what pattern do you want. Its printing something if you send System.out.println() in previous block. something like this.

 *   *  
  *   
 *   *  
    * 

for code:

public static void main (String[] args) throws java.lang.Exception
    {
           for(int i=1;i<5;i++){
            for(int j=1;j<5;j++){
               if (i==j||i+j==5-1){
                   System.out.print(" * ");
               }
               else{
                   System.out.print(" ");
               }
           }System.out.println();
       }
    }

1 Answer

try something like this.

see the comments inside the code for explanation:

    public static void main (String[] args) throws java.lang.Exception
    {
        // printing x shape;
        //print v and inverted v(outline of a pyramid)that is '\' and '/'
        int n=5;
                //printing V
        for (int i=1; i<n; i++)
        {
                        //printing '\ '
            for (int j=n-i; j<n-1; j++)
            {
                System.out.print(" ");
            }
            System.out.print("*");
            for (int j=i; j<n-1; j++)
            {
                System.out.print(" ");
            }

                        //printing '/'
            for (int j=i; j<n-1; j++)
            {
                System.out.print(" ");
            }
            System.out.println("*");

        }
                //printing inverted v
        for (int i=1; i<n; i++)
        {
            for (int j=i; j<n-1; j++)
            {
                System.out.print(" ");
            }
            System.out.print("*");
            for (int j=1; j<i; j++)
            {
                System.out.print(" ");
            }

        for (int j=1; j<i; j++)
            {
                System.out.print(" ");
            }

            System.out.println("*");

        }

    }