mercredi 22 juin 2016

Java Program - Patternmaker | How to make odd columns show?

for my homework I need to make a pattern using for nested loops. It needs to look like this: pattern for 5 rows and 7 columns

However, when I was writing my code I could not figure out what to do make columns, if an odd number, to appear. I figured I needed to add another If/else statement. Here is my code:

public class PatternMaker {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {

    // Declaration

   int numrows = 5;
   int numcols = 7;
   String str1= "XX";
   String str2 = "OO";
   String sep = "***";

   if (numcols % 2 == 0) {  // if columns is even
       // for each row
       for (int i = 1; i <= numrows; i++) {

           // for each column
           for (int k = 0; k < numcols/ 2; k++) {

               if ( i % 2 == 1) { // for odds
                     if(k > 0) {
                        System.out.print(sep + str1 + sep+ str2);
                        }
                    else 
                        System.out.print(str1 + sep + str2);
                } 
               else {   // for evens
                     if(k > 0) {
                        System.out.print(sep + str2 + sep + str1);
                        }
                    else 
                        System.out.print(str2 + sep + str1);
                } 
        }
           System.out.println();                         
       } 

   }





else {  // if columns is odd
       // for each row
       for (int i = 1; i <= numrows; i++) {

           // for each column
           for (int k = 0; k < (numcols/ 2); k++) {
               if ( i % 2 == 1) { // for odds
                     if(k > 0) {
                        System.out.print(sep + str1 + sep+ str2);
                        }

                    else 
                        System.out.print(str1 + sep + str2);
                } 
               else {   // for evens
                     if(k > 0) {
                        System.out.print(sep + str2 + sep + str1);
                        }

                    else 
                        System.out.print(str2 + sep + str1);                        
                } 
        }
           System.out.println();                         
       } 

} 

Aucun commentaire:

Enregistrer un commentaire