Reputation: 11
I am trying to stop this recursive loop in Java.
I have made a program which prints numbers like Output :1 2 3 4 5 6 5 4 3 2 1 0 1 2 3 4 5 6 5 4 3 2 1
It's like creating a wave of increasing and decreasing numbers. But i want to stop, when it gets more than the length of the string. Can anyone give an alternate way.
boolean isboolean = true;
public void recursive(int data, String s) {
int counter = 0;
Loop1:
while (isboolean) {
counter++;
data = data + 1;
System.out.print(data + " ");
if (data > 5) {
isboolean = false;
}
if (counter > s.length()) break Loop1;
}
Loop2:
while (!isboolean) {
data = data - 1;
System.out.print(data + " ");
if (data == 0) {
isboolean = true;
}
}
recursive(data, s);
}
I want to stop this wave of numbers when it gets more than String s length. And prints output: 1 2 3 4 5 6 5 4 3 2 1 0 1 2 3 4 5 6 5 4 3 2 1 but stops, when it's more than string length.
Upvotes: 0
Views: 224
Reputation: 352
For your needs you don't need a recursive loop, this will do what you want
So for your needs you would put min
as 0 max
as 6 and offset
as 0:
private static void numberWave(String text, int min, int max, int offset) {
for (int i = min+offset; i < text.length()+min+offset ; i++) {
int deltaMX = max-min;
int counterMod = ((i)%(deltaMX));
int upWards = min+counterMod+1;
int downWards = min+(deltaMX-counterMod-1);
boolean counterPart = (i)%(deltaMX*2)<deltaMX;
System.out.print((counterPart?upWards:downWards)+" ");
}
}
Input: numberWave("Hello world" , 0 , 6 , 0 )
Output: 1 2 3 4 5 6 5 4 3 2 1 0 1 2 3
Upvotes: 0
Reputation: 3866
A better approach would be to pass the counter
value rather than using an error-prone global variable for counter
(because it will result in incorrect values if called more than once). And secondly, you can simplify both of your loops into a single loop:
public void recursive(int data, String s, int counter) {
boolean increment = true;
while (counter <= s.length()) {
counter++;
if (increment)
data += 1;
else
data -= 1;
System.out.print(data + " ");
if (increment && data > 5) {
increment = false;
} else if (!increment && data == 0) {
break;
}
}
if (counter <= s.length()) {
recursive(data, s, counter);
}
}
And call your method like this:
recursive(0, "abcdefghijklmno", 1);
Output:
1 2 3 4 5 6 5 4 3 2 1 0 1 2 3
Upvotes: 0
Reputation: 3629
With few corrections:
1- declare counter outside
2- make length conditions to both loops
3- stop recursion when length reaches
4- counter should be incremented in both loops.
5- no need for labeled loop now.
boolean isboolean= true;
int counter = 0;
public void add(int data, String s) {
//Loop1:
while (isboolean && counter <= s.length()) {
counter++;
data = data + 1;
System.out.print(data + " ");
if (data > 5) {
isboolean = false;
}
}
//Loop2:
while (!isboolean && counter<= s.length()) {
counter++;
data = data - 1;
System.out.print(data + " ");
if (data == 0) {
isboolean = true;
}
}
if (counter<=s.length())
add(data, s);
}
Upvotes: 3