for循环内部循环错误

时间:2012-08-14 19:19:07

标签: android for-loop

在Android应用中,我想为第一个和第二个按钮分配不同的标签(按下其中任何一个后)。我的代码是吼叫。 LogCat向我显示它执行内部for循环一次然后关闭VM并且还提供消息 “threadid = 1:线程存在未捕获异常(group = 0x409961f8)” 。谢谢你的帮助。

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);

            }       
    }

1 个答案:

答案 0 :(得分:1)

我无法确定,但我不认为你真的想在这种情况下使用嵌套的for循环。您可能希望这样:

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);
}

如果你确实想要嵌套循环,那么你的循环计数器就不一致了(外部循环是零索引的,但是内部循环是一个索引,并且你在相同类型的对象上运行。在这种情况下,你想要这个:

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);
        }       
}

虽然我不是100%肯定。没有所有变量的定义很难说(什么是button_one和button_two?什么是优先级?)