java - How to print out an X using nested loops -


i have searched through find simple solution problem.

i have method called

printcross(int size,char display) 

it accepts size , prints x char variable receives of height , width of size.

the calling method printshape(int maxsize, char display) accepts maximum size of shape , goes in loop, sending multiples of 2 printcross method until gets maximum.

here code not giving me desired outcome.

public static void drawshape(char display, int maxsize)   {     int currentsize = 2; //start @ 2 , increase in multiples of 2 till maxsize      while(currentsize<=maxsize)     {       printcross(currentsize,display);       currentsize = currentsize + 2;//increment multiples of 2     }   }  public static void printcross(int size, char display) { (int row = 0; row<size; row++)           {               (int col=0; col<size; col++)               {                   if (row == col)                     system.out.print(display);                   if (row == 1 && col == 5)                     system.out.print(display);                   if (row == 2 && col == 4)                    system.out.print(display);                   if ( row == 4 && col == 2)                    system.out.print(display);                   if (row == 5 && col == 1)                    system.out.print(display);                   else                     system.out.print(" ");                 }             system.out.println();      } } 

is because hardcoded figures loop? did lot of math unfortunately it's way have been close achieving desired output.

if printcross() method received size of 5 instance, output should this: x   x  x x   x  x x x   x 

please have spent weeks on , seem going nowhere. thanks

the first thing have find relationships between indices. let's have square matrix of length size (size = 5 in example):

  0 1 2 3 4 0 x       x 1   x   x 2     x 3   x   x 4 x       x 

what can notice in diagonal (0,0) (4,4), indices same (in code means row == col).

also, can notice in diagonal (0,4) (4,0) indices sum 4, size - 1 (in code row + col == size - 1).

so in code, loop through rows , through columns (nested loop). on each iteration have check if conditions mentioned above met. logical or (||) operator used avoid using 2 if statements.

code:

public static void printcross(int size, char display) {     (int row = 0; row < size; row++) {         (int col = 0; col < size; col++) {             if (row == col || row + col == size - 1) {                 system.out.print(display);             } else {                 system.out.print(" ");             }         }         system.out.println();     } } 

output: (size = 5, display = 'x')

x   x  x x    x    x x  x   x 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -