I have to use public static String pattern(int n) method, this head is given. Th
ID: 3580168 • Letter: I
Question
I have to use public static String pattern(int n) method, this head is given.
The pattern method accepts a single integer as a parameter. If that integer is less than 1, the pattern method should return an error message "Argument must be greater than or equal to 1". Otherwise, the method should return a string containing a pattern of integers as demonstrated in the table below. There is a space between each integer pair and a newline ( ) after each integer greater than 5. The underlines and boldface are hints to help you see that pattern and are not included in the String created by your program. Because of the length of the string, do not test with values of n greater than 10. n String that is returned (bold and underline only shown to help you recognize pattern) This produces a numeric pattern symmetric about n where each half before and after n is also symmetric around n-1. The newline after printing any integer larger than 5 provides a nice line length and also makes the pattern of the bigger numbers along the right edge reading down. If you get the normal pattern, that will just happen. Don't think about it. Output for an input of 7 is:Explanation / Answer
1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 5 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 6
1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 5 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 7
1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 5 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 6
1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 5 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1
------------------------------------------------------------------------------------------------------------------------
Code:
public String pattern(int n){
return patternUtil(n, "1");
}
public String patternUtil(int n, String result)
{
if(n == 0) {
return result;
}
char curChar = result.charAt(0);
String newResult = "";
int counter = 0;
for(int i = 0; i< result.length(); i++) {
char character = result.charAt(i);
if(character != curChar) {
newResult = newResult + counter;
newResult = newResult + curChar;
counter = 0;
curChar = character;
}
counter ++;
}
newResult = newResult + counter;
newResult = newResult + curChar;
return patternUtil(n -1 , newResult);
}