简体   繁体   中英

How can I avoid this error with while JAVA Android

I'm designing an app, what it does is a kind of "secret friend", I tell the app obviously not to repeat the person playing with the selected person, see this:

if (lista2.isEmpty())
{
    (Toast.makeText(getApplicationContext(), this.getString(R.string.nospace), Toast.LENGTH_LONG)).show();
    return;
} else {
    Random random = new Random();

    int start2;
    do
    {
        start2 = random.nextInt(lista2.size() - 0) + 0;
    }
    while (lista2.get(start2).equals(spinner1.getSelectedItem().toString()));
}

At the while, sometimes the app crash, because there's no more items on lista2 , just the same person( spinner1.selectedItem ), how can I solve this?

What you should do is to

  1. first remove the person(spinner1.selectedItem from lista2
  2. Then do a random get

This way, you need not use the do-while loop

just do a check first

 if (lista2.isEmpty())
    {
        (Toast.makeText(getApplicationContext(), this.getString(R.string.nospace), Toast.LENGTH_LONG)).show();
        return;
    } else {
        //do a check here
        for(int i = 0; i < lista2.size(); i++){
            if(!lista2.get(start2).equals(spinner1.getSelectedItem().toString())){
                break;
            }
            if(i == lista2.size() - 1){
                Toast.makeText(getApplicationContext(), this.getString(R.string.nospace), Toast.LENGTH_LONG)).show();
                return;
            }
        }

        Random random = new Random();

        int start2;
        do
        {
            start2 = random.nextInt(lista2.size() - 0) + 0;
        }
        while (lista2.get(start2).equals(spinner1.getSelectedItem().toString()));
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM