Really strange for recursive

Hi guys,

I am using jdk1.5.0_05 under windows xp. My code is below:

import org.apache.commons.lang.RandomStringUtils;

public class StringUtilsTest {

public static void main(String[] args) {

int y=0;

for(int i = 0;i<10;i++){

String s = getRandomNumeric();

System.out.println("s = "+s);

}

}

private static String getRandomNumeric(){

System.out.println("start");

String s1 = RandomStringUtils.randomNumeric(4);

if(Integer.parseInt(s1) < 1000){

getRandomNumeric();

}

return s1;

}

}

and the output i got is:

start

s = 6511

start

s = 8869

start

s = 6088

start

start

s = 0068

start

s = 7693

start

s = 2637

start

s = 4096

start

s = 6396

start

s = 2318

start

s = 9624

As u notice that when the 4th time the getRandomNumeric() is called, the value is less than 1000 so it recurse again. But the value return still < 1000, which is 0068. All I want is the get a random number, which is not < 1000. Please help, Thanks !

regards,

Mark

[1205 byte] By [kmthiena] at [2007-10-2 1:57:57]
# 1
> if(Integer.parseInt(s1) < 1000){> return getRandomNumeric();> }
warnerjaa at 2007-7-15 19:39:04 > top of Java-index,Java Essentials,Java Programming...
# 2
the problem is that when you recurse you are not setting s1 = getRandomNumeric()so when it gets a value higher than 1000 it is not passed back up the line and the first value 0068 is still in s1.Also you should use the code tags
Drakonslaira at 2007-7-15 19:39:04 > top of Java-index,Java Essentials,Java Programming...
# 3

You could use the nextInt method of class Random. Say you want a random number between 1000 and (but not including) 10000 then you do,

static Random rnd = new Random(); // once in class

//

int r = 1000 + rnd.nextInt(9000); // for each random number

String s = String.valueOf(r); // turn to String

.....uja at 2007-7-15 19:39:04 > top of Java-index,Java Essentials,Java Programming...