2013-04-22 69 views
0

这可能看起来像一个非常简单的问题,但我很困惑。 我有一个if条件,它有很多条件,我无法弄清楚在这种情况下使用的括号语法。任何人都可以给我一些关于如何弄清楚这个或其他if语句中有多少条件的情况的正确语法的提示吗?谢谢!围绕每个条件处理括号的语法

void collisionEn() { 
    for (int i = 0; i < myPlats.length; i++) { 
     if (posEx > myPlats[i].xPos) 
     && (posEx+wEx > myPlats[i].xPos) 
      && (posEx+wEx < myPlats[i].xPos + myPlats[i].platWidth) 
      && (posEx < myPlats[i].xPos + myPlats[i].platWidth) 
       && (posEy > myPlats[i].yPos) 
       && (posEy < myPlats[i].yPos + myPlats[i].platHeight) 
        && (posEy+wEy > myPlats[i]yPos) 
        && (posEy+wEy < myPlats[i].yPos + myPlats[i].platHeight) 
         rect(0, 0, 1000, 1000); 

回答

1

圆括号不是必需的(但被允许)。每个条件都有括号,没关系。

一组圆括号需要围绕整个条件,但。

if (condition) 

所以你的情况,就在一开始并在最后一个右括号加一个左括号,你就会有它。

if ((posEx > myPlats[i].xPos) 
    && (posEx+wEx > myPlats[i].xPos) 
     && (posEx+wEx < myPlats[i].xPos + myPlats[i].platWidth) 
     && (posEx < myPlats[i].xPos + myPlats[i].platWidth) 
      && (posEy > myPlats[i].yPos) 
      && (posEy < myPlats[i].yPos + myPlats[i].platHeight) 
       && (posEy+wEy > myPlats[i]yPos) 
       && (posEy+wEy < myPlats[i].yPos + myPlats[i].platHeight)) 
        rect(0, 0, 1000, 1000) 

正因为你再有很多括号的,我建议删除周围的每个条件的可选的,如果你的风格指南允许的话。他们没有必要,在这种情况下,他们增加了困惑。

if (posEx > myPlats[i].xPos 
    && posEx+wEx > myPlats[i].xPos 
    && posEx+wEx < myPlats[i].xPos + myPlats[i].platWidth 
    && posEx < myPlats[i].xPos + myPlats[i].platWidth 
    && posEy > myPlats[i].yPos 
    && posEy < myPlats[i].yPos + myPlats[i].platHeight 
    && posEy+wEy > myPlats[i]yPos 
    && posEy+wEy < myPlats[i].yPos + myPlats[i].platHeight) 
     rect(0, 0, 1000, 1000); 
+0

我不知道Processing处理支持你所建议的第二种语法。我想我可能误解了我正在阅读的这本书,我会再次检查它。另外,我犯的错误是:“&& posEy + wEy> myPlats [i] yPos”。我忘了在myPlats [i](。)yPos之后加上这个点。谢谢! – Alvarop 2013-04-22 12:05:16

0

,我做的,让代码更简单的另一件事是具有表示暂时计算一些局部变量进行测试,后者,例如如果你想保证金添加到测试区这可以轻松完成一个地方,如:

float mpX = myPlats[i].xPos; 
float mpY = myPlats[i].yPos; 
float mpW = mpX + myPlats[i].platWidth; 
float mpH = mpY + myPlats[i].platHeight 
float pEx = posEx+wEx; 
float pEy = posEy+wEy; 

if ( posEx > mpX && pEx > mpX 
    && pEx < mpW && posEx < mpW 
    && posEy > mpY && posEy < mpH 
    && pEy > mpY && pEy < mpH) 
rect(0, 0, 1000, 1000); 

关于他们如果(工作括号),就像他们在任何其他的计算工作,所以你必须想到precedence of the operators,虽然这是不常见的,他们内部的if语句需要。但是......有时它们,尤其是& &之间的优先顺序!和||都需要注意