Write a complete Java program called PatternMakerWithMethods according to the fo
ID: 3804428 • Letter: W
Question
Write a complete Java program called PatternMakerWithMethods according to the following guidelines.
Use the following fixed (hard-coded) string values for the first string, the second string, and the separator string in the method you call to print the pattern.
String firstString = "XX";
String secondString = "OO";
String separator = "||";
Use methods to get the number of rows and columns (each an integer between 1 and 10 inclusive) and to print the pattern.
The method to print the pattern should take two integers as arguments: the number of rows to print and the number of columns to print. In that method, you should hard-code the string values for the first string, the second string, and the separator string.
The program must use nested for loops to print a rectangular array of alternating first and second strings of the pattern, separated by the separator string and such that the first string in the first row uses the first string provided by the user, but each subsequent row alternates the starting string between the second string the user provided and the first string the user provided.
So, for instance, if the user enters 5 for the number of rows, 7 for the number of columns, and the firstString is "XX", the secondString is "OO", and the separator is "***", your program should print the following rectangular pattern.
Explanation / Answer
/**
*
* @author Sam
*/
public class PatternPrint {
static String firstString = "XX";
static String secondString = "OO";
static String separator = "||";
public static void main(String[] args) {
printer(5, 7);
}
private static void printer(int x, int y){
int i, j;
for(i = 1; i<=x; i++) {
for (j = 1; j<y; j++){ //Inner j loop prints y-1 columns with seperator
if((i+j)%2 == 0) //it checks which string to print, first or the second
System.out.print(firstString+separator); //and prints accordingly
else
System.out.print(secondString+separator);
}
if ((i+j)%2==0) //and after the loop we print the appropiate string without seperator
System.out.println(firstString);
else
System.out.println(secondString);
}
}
}
I tried my best to keep the code simple. I hope that you like the same. Please let me know in the comment section if you face any difficulties.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.