generate a number exclude some android button click -


i'd generate numbers in range. ex 1 10 , don't repeate ones had been generated.

on main activity:

int[] ex = {}; random rnd = new random(); 

my click button generate numbers:

        public void onclick(view v) {              string f = from.gettext().tostring();             int ff = integer.parseint(f);             string t = to.gettext().tostring();             int tt = integer.parseint(t);              int val = getrandomwithexclusion(ff, tt, ex);             string item = integer.tostring(val);             toast.maketext(mainactivity.this, item, toast.length_short).show();              ex = add(ex, val);             log.d("this array", "arr: " + arrays.tostring(ex));          } 

add function add generated numbers ex[]:

public static int[] add(int[] initialarray , int newvalue) {     int[] newarray = new int[initialarray.length + 1];     system.arraycopy(initialarray, 0, newarray, 0, initialarray.length);     newarray[newarray.length - 1] = newvalue;     return newarray; } 

and function not working (it repeating numbers , after 10 tries (1 10 range) shows fatal exception:

public int getrandomwithexclusion(int start, int end, int... exclude){     int rangelength = end - start - exclude.length;     int randomint = rnd.nextint(rangelength) + start;      (int anexclude : exclude) {         if (anexclude > randomint) {             return randomint;         }          randomint++;     }      return randomint; } 

why repeating numbers? , why after 10 button clicks (range 1 10) shows exception:

java.lang.illegalargumentexception: n must positive

it sounds better approach trying generate random number hasn't been generated create list of valid (unique) values , randomize list.

list<string> numbers = arrays.aslist("1", "2", "3", "4", "5", "6", "7", "8", "9", "10"); collections.shuffle(numbers); 

now list e.g. [7, 6, 1, 5, 10, 3, 9, 4, 8, 2] , can iterate on it.


Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -