简体   繁体   中英

for loop inside for loop error

In Android app I want to assign different tags for first and second buttons (after you press any of those). My code is bellow. LogCat shows me that it executes inner for loop once and then turns off VM and also gives message "threadid=1: thread existing with uncaught exception (group=0x409961f8)" . Thank You for help.

int marked = 0;
    int i = 0;
    int a = i + 1;

    for ( i = 0; i < priorities.size(); i++ ) 
    {
            Log.d(TAG, "Setting button one tag: " + i );
            Log.d(TAG, "blablabla rank2 " + priorities.get(i).rank);
            button_one.setTag(i);
            button_one.setText(priorities.get(i).name);

            for (a = i + 1; a <= priorities.size(); a++)
            {
            Log.d(TAG, "Setting whilee: " + i );
            Log.d(TAG, "blablabla while " + priorities.get(i).rank);
            button_two.setTag(a);
            button_two.setText(priorities.get(a).name);

            }       
    }

I can't be sure but I don't think you really want to use a nested for loop in this situation. Chances are you want this instead:

int marked = 0;
int i = 0;
int a = i + 1;

for ( i = 0; i < priorities.size(); i++ ) 
{
        Log.d(TAG, "Setting button one tag: " + i );
        Log.d(TAG, "blablabla rank2 " + priorities.get(i).rank);
        button_one.setTag(i);
        button_one.setText(priorities.get(i).name);

        Log.d(TAG, "Setting whilee: " + i );
        Log.d(TAG, "blablabla while " + priorities.get(i).rank);
        button_two.setTag(i);
        button_two.setText(priorities.get(i).name);
}

If you really do want the nested loop, You're not being consistent with your loop counter (the outer loop is zero indexed, but the inner loop is one indexed, and you're operating on the same types of object. In that case you'd want this:

int marked = 0;
int i = 0;
int a = i + 1;

for ( i = 0; i < priorities.size(); i++ ) 
{
        Log.d(TAG, "Setting button one tag: " + i );
        Log.d(TAG, "blablabla rank2 " + priorities.get(i).rank);
        button_one.setTag(i);
        button_one.setText(priorities.get(i).name);

        for (a = i; a < priorities.size(); a++)
        {
            Log.d(TAG, "Setting whilee: " + i );
            Log.d(TAG, "blablabla while " + priorities.get(i).rank);
            button_two.setTag(a);
            button_two.setText(priorities.get(a).name);
        }       
}

Though I'm not 100% sure. It's difficult to tell without definitions for all of your variables (what are button_one and button_two? what is priorities?)

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