if语句上的双开括号?这是什么?

时间:2014-08-25 02:44:24

标签: android if-statement audio-player android-music-player

我正在使用来自管理音乐的互联网的一些示例代码。代码的一部分是暂停音乐并准备再次播放的方式。我不理解双括号表示法。我认为它可能是一种使用If-Else的奇特方式,但是我的等效代码片段不起作用,但是,带有双括号的代码完美无缺。将两个开括号添加到If语句时,它究竟意味着什么?

以下是代码片段

// previousMusic should always be something valid
if (currentMusic != -1) {{
    previousMusic = currentMusic;
    Log.d(TAG, "Music is paused");
}

currentMusic = -1;
Log.d(TAG, "Paused music is prepared to play again (if necessary)");
}

这是我认为它可能意味着什么。它没有按预期工作,所以这实际上并不相同。

// previousMusic should always be something valid
if (currentMusic != -1) {
    previousMusic = currentMusic;
    Log.d(TAG, "Music is paused");
} else {
    currentMusic = -1;
    Log.d(TAG, "Paused music is prepared to play again");
}

提前感谢您的解释。

3 个答案:

答案 0 :(得分:3)

hat exactly does it mean when you add two open brackets to an If-statement?

没有什么特别的,它只是一个代码块,你将previousMusic = currentMusic放在方法的另一个范围内。

就像说:

if (currentMusic != -1) {
   previousMusic = currentMusic;
   Log.d(TAG, "Music is paused");

   currentMusic = -1;
   Log.d(TAG, "Paused music is prepared to play again (if necessary)");
}

但是如果你在代码块中创建一个变量,那么你就无法在块外部访问它,因为变量的范围只能被代码块访问。

    if(1==1)
    {
        int i2; 
        {
            int i;
            i2= 1; //can access from top level scope
        }
        i = 0; //compile time error cant access the variable in the block of code
    }

答案 1 :(得分:2)

我希望您了解scope个变量。

示例1:

if(some condition){

    { // x is born here
        int x = 32;
    } // x is dead here
    // not allowed!
    Log.d(TAG,"Value is: " + x);
}   

示例2:

if(some condition){
    int x = 32;
    // totally legit!
    Log.d(TAG,"Value is: " + x);
}   

看到两者之间的细微差别?

在示例1中,嵌套{}限制了x的范围。变量x仅可用于其相应的左括号}的右括号{

答案 2 :(得分:1)

理解该代码的正确方法是:

if (currentMusic != -1) {
    {
        previousMusic = currentMusic;
        Log.d(TAG, "Music is paused");
    }

    currentMusic = -1;
    Log.d(TAG, "Paused music is prepared to play again (if necessary)");
}

当您在代码中添加大括号时,您只需创建一个新范围来处理变量。