lundi 26 juillet 2021

Spot the difference [closed]

I am working on a small task from udemy and it is to print diagonal star pattern if the input is <= 5 here is what I wrote

            if (number < 5) {
                System.out.println("Invalid Value");
            } else {
                System.out.println();
                System.out.println();
                for(int i = 0; i < number; i++){
                    for(int j = 0; j < number; j++) {
                        if (i == 0 || (i == number - 1) || j == 0 || (j == number - 1) || (i == j) || ((j + 1) == number - (i + 1) + 1)) {
                             System.out.println("*");
                         } else {
                             System.out.println(" ");
                         }
                    }
                    System.out.println();
                }
            }
        } 

and here is is the solution I found on github

            if (number < 5) {
                System.out.println("Invalid Value");
            } else {
                // a loop which prints a new line (a row)
                System.out.println();
                System.out.println();
                for (int i = 0; i < number; i++) {
                    // a loop which prints * and a space
                    for (int j = 0; j < number; j++) {

                        // i == 0 top
                        // (i == number - 1) bottom
                        // (j == number - 1) right
                        //  j == 0 left

                        if (i == 0 || (i == number - 1) || j == 0 || (j == number - 1) || (i == j) || ((j + 1) == number - (i + 1) + 1)) {
                            System.out.print("*");
                        } else {
                            System.out.print(" ");
                        }
                    }
                    System.out.println();
                }
            }
        } 

But I am getting different results for both which is as following for what I wrote

*
*
*
*
*
*
*
*

*
*
 
 
 
 
*
*

*
 
*
 
 
*
 
*

*
 
 
*
*
 
 
*

*
 
 
*
*
 
 
*

*
 
*
 
 
*
 
*

*
*
 
 
 
 
*
*

*
*
*
*
*
*
*
*

and for the code I got from git hub the result is

*******************
**               **
* *             * *
*  *           *  *
*   *         *   *
*    *       *    *
*     *     *     *
*      *   *      *
*       * *       *
*        *        *
*       * *       *
*      *   *      *
*     *     *     *
*    *       *    *
*   *         *   *
*  *           *  *
* *             * *
**               **
******************* 

Please help me spot what is wrong.

Aucun commentaire:

Enregistrer un commentaire