简体   繁体   English

n无法解析为变量

[英]n cannot be resolved to a variable

I am completely new to java and hence was trying some simple programs by my self I am not able to get the output for the below program. 我对Java完全陌生,因此我自己尝试了一些简单的程序,但我无法获得以下程序的输出。

public class For_loop {
  public static void main(String[] args) {      
    int Sum = 0;        
    for (int n=0; n<=100; n++);         
        Sum= Sum +n; // getting the error here as n cannot be resolved to a variable
    {
    System.out.println (Sum);                           
    }       
  }     
}

Please help me with the output. 请帮助我的输出。

Remove semicolon ; 删除分号; in for loop. 在for循环中。 if you add semicolon it means completed statement and n variable scope limited to for..loop not outside. 如果添加分号就意味着完成了陈述和n可变范围限于不在外面for..loop。

  for (int n=0; n<=100; n++){
        Sum= Sum +n; 
  }

for the correct version of code.. please find below.. 有关正确版本的代码..请在下面找到..

for (int n=0; n<=100; n++); 对于(int n = 0; n <= 100; n ++); on this line you r making the mistake. 在这条线上,您犯了错误。 once you putting the semicolon. 一旦你把分号。 the loop end there. 循环在那里结束。 and you are defining the variable n as local variable having the visibility only to the for loop block. 并且您将变量n定义为仅对for循环块可见的局部变量。 So when your are accessing the variable on the next line.. it gives you the error... 因此,当您访问下一行的变量时,它会给您错误...

look below for the error free code... 在下面查看无错误代码...

for (int n=0; n<=100; n++)
{       
 Sum= Sum +n; 
}

As previously noted - the ; 如前所述- ; at your for() causes your loop to end there - making n unknown outside of this scope . 在您的for()使您的循环在那里结束-在此scope之外使n未知。

But even with that fixed, you still have a {} group in your code which is strange. 但是即使修复了这个问题,代码中仍然有一个{}组,这很奇怪。 Did you want to output sum on every iteration? 您是否要在每次迭代中输出总和?

for (int n=0; n<=100; n++) { //where ; was before
    Sum +=n; // same as Sum = Sum +n; 
    System.out.println (Sum);        
}       

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

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