0

i have this question to display any given number twice the specified time for instance if i want to display 6 two times it will display it 4 times next to each other like this 6666 using recursion i have a code but it gives me a stack overflow could someone please help i am new to this recursion.

public static int i = 6;
public static int j = 2;

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

System.out.print(addToTarget(i, j));


}
public static int addToTarget(int n, int x){
int index = 0;
 if (index !=j*2){
   System.out.print(i);
   index+=1;
   return addToTarget(i,index);
 }
 return i;

}
yousef
  • 1
  • 2

2 Answers2

0

Why do you even need recursion for this. See question 1235179. Which will suggest you something like

public static int addToTarget(int n, int x){
 return new String(new char[x]).replace("\0", String.valueOf(n));
}

And what a mess you have between static variables and parameters!

Community
  • 1
  • 1
Serg M Ten
  • 5,568
  • 4
  • 25
  • 48
0

you can use the recursion like this.

public static int index = 0;

public static void main(String[] args) {

int i = 6;
int j = 2;
addToTarget(i, j);
}

public static void addToTarget(int i, int j){
 if (index < j*2){
   System.out.print(i);
   index+=1;
   addToTarget(i,j);
 }

}