for循环跳到最后? [英] for loop is skipping to the end?

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

问题描述



 的System.out.println(ⅰ); (i = 0; i< =(难度 -  2); i ++); {
System.out.println(i);
nextMineX =(int)(10 * Math.random());
nextMineY =(int)(10 * Math.random()); (y = 0; y< = 14; y ++){
System.out.println(y);


if(nextMineX == minesX [y]&&; nextMineY == minesY [y]){
i = i-1;
} else {
minesX [i] = nextMineX;
minesY [i] = nextMineY;







第一个循环是拧而嵌套的一个运行良好。变量i初始化为0,难度为16.这段摘录的输出如下:

$ $ p $ $ $ $ $ $ $ $ $ $ b 14
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14

如果有人能帮助我,他会非常感激。因为我是新手,所以我可能忽略了一些小的和基本的东西。

解决方案

问题是分号第二行的结尾。没有主体的循环有一个是有效的。在括号内有独立的代码块也是有效的(这为变量定义了一个范围 - 如果你在括号内定义了一个变量,它就不能在外面使用)。所以Java正在解释你的代码的开始是这样的:
$ b $ pre $ for(i = 0; i< =(难度 - 2 ); i ++); // for循环完成,所以我=难度 - 2

{
System.out.println(i);
...


I am fairly new to Java, but my for loop is instantly skipping to the highest possible value in the following code:

System.out.println(i);
    for(i = 0; i <= (difficulty - 2); i++);{
        System.out.println(i);
        nextMineX = (int) (10*Math.random());
        nextMineY = (int) (10*Math.random());

        for(y = 0; y <= 14; y++){
            System.out.println(y);
            if(nextMineX == minesX[y] && nextMineY == minesY[y]){
                i = i-1;
            } else{
                minesX[i] = nextMineX;
                minesY[i] = nextMineY;
            }
        }
    }

The first for loop is screwing up, while the nested one is running fine. the variable i is initialized as 0, and difficulty is at 16. the output of this excerpt is as follows:

0
14
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14

If anyone can help me with his that would be extremely appreciated. Since I'm new, it is probably something small and basic that I'm overlooking.

解决方案

The problem is the semicolon at the end of the second line. It's valid to have a for loop with no body. It's also valid to have standalone a block of code inside brackets (this defines a scope for variables--if you defined a variable inside the brackets, it wouldn't be available outside). So Java is interpreting the beginning of your code like this:

for(i = 0; i <= (difficulty - 2); i++); // for loop is done, so i = difficulty - 2

{
    System.out.println(i);
    ...

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

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