[英]Java If-Statement short form
I found the following code:我找到了以下代码:
static void CreatePartys(int n)
{
int num = 0;
int[] e = new int[n];
e[num] = n;
while (true)
{
int part = 0;
count = count +1;
while (num >= 0 && e[num] == 1)
{
part += e[num];
num--;
}
if (num < 0) return;
e[num]--;
part++;
while (part > e[num])
{
e[num+1] = e[num];
part = part - e[num];
num++;
}
e[num+1] = part;
num++;
}
}
And I'm stuck at the if-Statement, I've seen this never before, not even inside a Java-Book.我被困在 if 语句中,我以前从未见过这种情况,甚至在 Java 书中也没有见过。
if (num < 0) return;
What does it return?它返回什么? true, false, a number?
真、假、数字?
After if follows a statement.在if之后跟在一个语句之后。 Following is a valid code:
以下是有效代码:
if (a > 5) b = c + 2;
Here b = c + 2;这里b = c + 2; is a normal statement.
是一个正常的语句。
But statement can also defined by braces.但是语句也可以用大括号定义。 You can use braces also in a normal code as follows:
您也可以在普通代码中使用大括号,如下所示:
long i = 3;
long j = 4;
long k = 9;
{ i = j + 7; }
{ i = i * k + 123; }
i = 345;
{ k = j * 10; }
{
i = 234 * j;
k = 12 * j;
System.out.println(i);
}
Such form often makes no sense because it makes the code hard to understand :) But this is valid code which will correctly compile.这种形式通常没有意义,因为它使代码难以理解:) 但这是可以正确编译的有效代码。
What you often see after if is just a statement like above.你经常在if之后看到的只是像上面那样的语句。
Why do we see often braces after if ?为什么我们经常在if之后看到大括号? After if exactly one statement is executed.
如果只执行了一个语句之后。 If you have code like
如果你有类似的代码
if (a > 5)
b = c + 2;
k = i + 3;
then the statement b = c + 2;那么语句b = c + 2; will be executed if the condition a > 5 holds true.
如果条件a > 5成立,将被执行。 But the statement k = i + 3;
但是语句k = i + 3; will be executed always , independent on a > 5 .
将始终执行,独立于a > 5 。
If you want both statements executed only if a > 5 holds true, then you use braces:如果您希望仅当a > 5成立时才执行这两个语句,则使用大括号:
if (a > 5) {
b = c + 2;
k = i + 3;
}
When you want to execute exactly one statement depending on if , you can omit braces.当您想根据if 只执行一条语句时,可以省略大括号。 But your teammates in the project may be unsure if it was your intention to omit the braces or if it was just a mistake.
但是您项目中的队友可能不确定您是否有意省略大括号,或者这只是一个错误。 To avoid any such doubts, coding guidelines in many projects require that any statement after if must use braces, no matter how simple the statement is.
为了避免任何此类疑问,许多项目中的编码指南要求if之后的任何语句都必须使用大括号,无论语句多么简单。
Short explanation:简短说明:
If you just write return;如果你只写 return; you can stop the execution of the current method.
您可以停止当前方法的执行。
If statements don't need braces if they have a single statement following them like如果语句后面有一个单独的语句,则它们不需要大括号,例如
if(2<variable)
System.out.println("inIf")
System.out.println("outsideIf")
So.所以。
if (num < 0) return;
Just means: stop execution of method when number is smaller than 0 No other code in the method will be called只是意味着:当number小于0时停止执行方法不会调用方法中的其他代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.