java for循环不工作 [英] java for loop not working

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

问题描述

我希望这不是一个愚蠢的问题,但我已经查找了我能找到的每个示例,但似乎我的代码仍然正确,但它仍然无法正常工作......我输入一个数字,它继续前进到下一行代码而不是循环.我正在使用它来填充用户输入数字的数组.感谢您的帮助,谢谢.

I hope this isn't a stupid question but I have looked up every example I can find and it still seems like I have this code right and it still isn't working... I enter one number and it moves on to the next line of code instead of looping. I'm using this to fill an array with user input numbers. I appreciate any help, thanks.

for(i=0; i<9; i++);
{  
    System.out.println ("Please enter a number:");  
    Num[i] = keyboard.nextDouble();  
    Sum += Num[i];      
    Product *= Num[i];      
}   

推荐答案

for 循环末尾的 ; 被当作一个空语句,相当于你的 for- 的一个空块环形.编译器将您的代码读取为:

The ; at the end of the for loop is taken as an empty statement, the equivalent of an empty block for your for-loop. The compiler is reading your code as:

int i;
....
for(i=0; i<9; i++)
    /* no-op */;

/* inline block with no relation to for-loop */
{  
    System.out.println ("Please enter a number:");  
    Num[i] = keyboard.nextDouble();  
    Sum += Num[i];      
    Product *= Num[i];      
} 

删除 ; 以获得您的预期行为.

Remove the ; to get your intended behavior.

如果您不需要循环外的 i,您可以将其声明移到 for 语句中.

If you don't need the i outside of the loop, you could move its declaration within the for statement.

for(int i=0; i<9; i++)
{
   // `i` is only usable here now
}
// `i` is now out of scope and not usable

在错误的分号 ; 存在时使用此语法会产生一个编译错误,该错误会在之前提醒您注意错误的 ;.编译器会看到:

Using this syntax when the erroneous semicolon ; was present would have produced a compile error that would alerted you to the erroneous ; earlier. THe compiler would see this:

for(int i=0; i<9; i++)
    /* no-op */;

/* inline block with no relation to for-loop */
{  
    System.out.println ("Please enter a number:");  
    Num[i] = keyboard.nextDouble();     // compile error now - `i` is out-of-scope
    Sum += Num[i];      
    Product *= Num[i];      
} 

这将是一个示例,说明在可能的情况下限制变量的范围是一种很好的做法.

This would be an example why it is good practice to limit the scope of variables when possible.

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

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