在for循环错位分号 [英] Misplaced semicolon in for loop

查看:124
本文介绍了在for循环错位分号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在做我的任务时,我做了一个小错误,在for循环中,就像下面的代码一样。

$ p $ for(i = 0; i N = N * I;





$ b当我编译程序时,它的编译没有错误,但是我没有得到输出一段时间。然后,后来发现我错误地放置了for循环中的分号。在for循环之后放置分号时出现了什么问题?

  class A 
{
public static void main(String args [])
{
int i,n = 1; (i = 1; i <= 5; i ++)的
;
n = n * i;
System.out.println(n);




$ b我将下面的代码输出为6如果你在for循环之后放置分号,那么它在技术上是正确的语法。因为它被认为是一个空的陈述 - 这意味着什么都不能执行。



在你的情况下 - $ /

pre $ for(i = 0; i< ; N;我++);

执行到 n 次的空语句。换句话说, for-loop 只是运行 n 次。

在for循环之后的花括号 {} 只执行一次。现在,将大括号内的代码块视为浮动块

When I am doing my assignments I done a small mistake by placing ; in the for loop like the following code.

for(i=0;i<n;i++);{
    n=n*i;
}

When I compiled the program its compiled with no error but I did not get the output for a while. Then later figured out that I misplaced the semicolon in for loop. What was the bug when I place semicolon after for loop.

class A
{
    public static void main(String args[])
    {
        int i, n=1;
        for(i=1; i<=5; i++);
        n=n*i;
        System.out.println(n);
    }    
}

I am getting output for the following code as 6 instead of 120.

解决方案

If you place semicolon after a for loop then it is technically correct syntax. Because it is considered as an empty statement - that means nothing to execute.

In your case -

for(i=0;i<n;i++);  

An empty statement executed up to n times. Or in other words the for-loop simply runs n times.

The curly braces {} after the for loop executed only once. Now the code block inside the curly braces {} considered as a floating block.

这篇关于在for循环错位分号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆