In the last method I'm trying to call printPattern
inside of a for loop, but I have no idea what I'm doing wrong. I'm using BlueJ, so I'm not sure if the code will be different in Eclipse.
Here's the program:
public class recursion
{
private int count;
private String printPattern(int count, int itterations)
{
int i;
String line= "";
for(i=0; i <= count; i++)
{
if (i > itterations)
{
line = line + i;
}
else {line = line + "*";}
}
line = line + reverseLine(line);
return line;
}
private String reverseLine (String line)
{
int size;
String linerev = "";
for (int i = line.length() - 1; i >= 0; i--)
{
linerev= linerev + line.charAt(i);
}
return linerev;
}
private void addLineandReverse (int n)
{
int w= n;
//for loop
//calls function print pattern
//add itteration ++
//prints out
for (n= 9; n <= printPattern; n++)
{
System.out.println();
}
}
}
Here is what I wish the output of the program to look like:
123456789987654321
*2345678998765432*
**34567899876543**
***456789987654***
****5678998765****
*****67899876*****
******789987******
*******8998*******
********99********
******************
You are using the function as limit for the stop condition of the for loop. But that seems wrong as I don't think the function is ment to return the result for a condition, it returns a string.
I'm not sure what you are trying to accomplish with calling the function. and why you are reassigning n to 9.
Either way to call the printPattern method you have to use this syntax:
printPattern(aNumber, anotherNumber)
Code that would work (but probably not output what you want) would be:
public void addLineandReverse (final int n)
{
//for loop
// calls function print pattern
// add itteration ++
//prints out
for (int i = 0; i <= n; ++n) {
System.out.println(printPattern(w, n));
}
}
Ok I took your requirements and adjusted your code and stayed as close as I could to your design (its not the design that I would take to tackle this problem but it works.
public class Recursion {
public static void main(String[] args) {
final Integer count = 9;
final Recursion recursion = new Recursion(count);
recursion.addLineAndReverse();
}
public Recursion(final Integer count) {
this.count = count;
}
private final int count;
public String printPattern(final int lineNumber) {
String line= "";
for(int i = 1; i <= count; ++i){
if (i >= lineNumber) {
line += i;
} else {
line += "*";
}
}
line += reverseLine(lineNumber);
return line;
}
public String reverseLine(final int lineNumber)
{
String line= "";
for(int i = count; i >= 1; --i){
if (i >= lineNumber) {
line += i;
} else {
line += "*";
}
}
return line;
}
public void addLineAndReverse(){
for (int i = 1; i <= count + 1; ++i){
System.out.println(printPattern(i));
}
}
}