简体   繁体   English

这个公式在Java中如何工作?

[英]How does this formula work in java?

I'm trying to figure this out, but how does the double print 22? 我正在尝试解决这个问题,但是双重打印22是怎么回事? Also, what exactly does the semicolon do after the for loop? 另外,在for循环后分号到底要做什么? I'm going to assume that the final result is due to this. 我将假定最终结果是由于此。

public class termdeposit
{
    int sum;

public termdeposit()
{
    sum = 1;
}

public void test() 
{
int sum = 1;
for (int i = 0; i <= 4; i++); {
    sum = sum + 1;
}
System.out.println ("The result is: " + sum);
System.out.println("Double result: "+ sum+sum);
}
}

The semicolon ends the (useless) loop statement, and the curly braces start an unrelated block of code. 分号结束(无用的)循环语句,花括号开始一个不相关的代码块。 Your code is equivalent to this: 您的代码与此等效:

for (int i = 0; i <= 4; i++) {
    // do nothing
}
// run once:
sum = sum + 1;

Your print statement prints 22 because sum+sum is interpreted as string concatenation in the context of the previous + , and since sum now is 2 , it prints "2" and "2" . 您的打印语句打印22因为sum+sum在上一个+的上下文中被解释为字符串连接,并且由于sum现在为2 ,所以它打印"2""2"

I'm assuming that you were challenged to explain the program behavior. 我假设您在解释程序行为方面遇到了挑战。 It's a trick question. 这是一个技巧问题。 As you seem to be aware, the semicolon is very important. 如您所知,分号非常重要。 This code: 这段代码:

for (int i = 0; i <= 4; i++); {
    sum = sum + 1;
}

is deceptive. 具有欺骗性。 Properly indented, it would be something like: 适当缩进,将类似于:

for (int i = 0; i <= 4; i++)
    ; // do nothing
{
    sum = sum + 1;
}

The braces create a code block (which could have declared variables local to that block). 花括号创建一个代码块(可以在该块中声明局部变量)。 In this case, it has exactly the same effect as if sum = sum + 1; 在这种情况下,其效果与sum = sum + 1;完全相同sum = sum + 1; were written outside any braces. 被写在大括号外面。

You should be able to figure out the rest of the behavior from that plus the fact that, in the last print statement, the + operator associates left-to-right. 您应该能够从中找出其余的行为以及以下事实:在最后一个打印语句中, +运算符从左到右关联。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM