PDA

View Full Version : [JAVA] Stringa di numeri random di lunghezza x


miao84
06-12-2009, 14:59
Devo creare una stringa di numeri casuali di "x" cifre, ho provato cosi ma il metodo mi restituisce una stringa di numeri e lettere mentre io vorrei solo numeri:

public String randomString (int x) {
Random rnd = new Random ();
char[] arr = new char[x];

for (int i=0; i<x; i++) {
int n = rnd.nextInt (9);
arr[i] = (char) n;
}
return arr.toString();
}

morskott
06-12-2009, 15:25
Devo creare una stringa di numeri casuali di "x" cifre, ho provato cosi ma il metodo mi restituisce una stringa di numeri e lettere mentre io vorrei solo numeri:

public String randomString (int x) {
Random rnd = new Random ();
char[] arr = new char[x];

for (int i=0; i<x; i++) {
int n = rnd.nextInt (9);
arr[i] = (char) n;
}
return arr.toString();
}

public String randomString(int x){
Random rand=new Random();
String res="";
for (int i=0;i<x;i++){
res+=String.valueOf(rand.nextInt(9));
}
return res;
}
Cosė dovrebbe funzionare

miao84
06-12-2009, 15:31
e anche bene! grazie mille! devo dire che sto approfittando troppo di questo forum, ma sono troppo pigro!