unwanted static method....
Hi
I have a static method which is supposed to return a random number based on previous returned random numbers... but as it is static it continually returns the same number... however, simply removing static throws me the error "cannot be referenced from static context"
if it is any help here is the method:
public static int setRnd(int[] curInt, int tried) {
//hmm static... change output?
int lclRnd = 0;
boolean triedAll = true;
curInt[tried] = tried; //we have already tried this # a it is passed as a non accepted #
for(int r = 0; r < curInt.length; r++){
if(curInt[r] == 0){//if this option still hasn't been tried there must be atleast one number left
triedAll = false;
System.out.println("We haven't tried all");
break;
}
}
if(triedAll){ //tried all was already set to true and can only be changed if a number has not yet been tried
lclRnd = 0; //return 0 to tell it to reset
} else {
while(curInt[lclRnd] == 0){
lclRnd = (int)(Math.random() * 9) + 1;
System.out.println("Rnd: " + lclRnd + "Array[lclrnd] " + curInt[lclRnd]);
if(curInt[lclRnd] == 0){
curInt[lclRnd] = lclRnd;
}
}
}
return lclRnd;
}
> Hi
> I have a static method which is supposed to return a
> random number based on previous returned random
> numbers... but as it is static it continually returns
> the same number...
No, that would have nothing to do with it. It's just that your implementation must be wrong. It should likely remain static if the method itself does not need to access any instance-specific members (or other non-static methods in this class).
Sorry if this is a stupid question, but why not use something similar to:
import java.util.Random;
public class RandomTest {
static Random r = new Random();
public static void main(String[] args) {
int range = Integer.parseInt(args[0]);
for (int i = 0; i < 100; i++) {
System.out.println(r.nextInt(range));
}
}
}
Cheers, Neil
Or how about:
import java.util.List;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.Collections;
public class Test {
private static List ints = new ArrayList();
private static Iterator iterator;
static {
for (int i = 1; i <= 9; i++)
ints.add(new Integer(i));
Collections.shuffle(ints);
iterator = ints.iterator();
}
public static int nextInt() {
if (!iterator.hasNext()) {
Collections.shuffle(ints);
iterator = ints.iterator();
}
return ((Integer) iterator.next()).intValue();
}
public static void main(String[] args) {
for (int i = 0; i < 30; i++)
System.out.println(nextInt());
}
}
Cheers, Neil