You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java技术求助:代码中for循环未执行,循环体未被执行

问题分析与修复:For循环未执行的原因

嘿,我一眼就发现你代码里的问题了——你的for循环之所以完全没执行,是因为循环条件写反了!

错误根源

你看,你写的循环条件是:

for(i = 0; i > XArray.length; i++)

初始值i=0,而XArray.length是10000,0 > 10000显然是false,所以循环体直接就被跳过了,根本不会执行。Y数组的循环也是同样的问题,条件j > YArray.length同样不成立。

另外还有个小细节:i和j变量没有声明,这在Java里会导致编译错误,你得在循环里加上int来声明它们。

修正后的完整代码

public void timeInterval(){ 
    mouseX = (int)MouseInfo.getPointerInfo().getLocation().getX(); 
    mouseY = (int)MouseInfo.getPointerInfo().getLocation().getY(); 
    System.out.println("mouseX and mouseY are collected"); 
    
    // 修正循环条件为i < 数组长度,同时声明int i
    for(int i = 0; i < XArray.length; i++){ 
        XArray[i] = mouseX; 
        System.out.println("XArray works"); 
    } 
    
    // 同理修正Y数组的循环
    for(int j= 0; j < YArray.length; j++){ 
        YArray[j] = mouseY; 
        System.out.println("YArray works"); 
    } 
    
    System.out.println("The arrays have been created properly"); 
    System.out.println(mouseX+"X"); 
    // System.out.println(mouseY+"Y"); 
    // 这里打印XArray[0]更安全,避免循环未执行时的索引越界
    System.out.println(XArray[0]); 
}

额外建议(可能符合你的真实需求)

如果你的目的是记录鼠标的连续位置,而不是把整个数组都覆盖成同一个坐标,那上面的写法其实不太合理。你可以加一个计数器变量来记录当前存储的索引,每次调用timeInterval只存储一次鼠标位置:

// 额外声明一个public的计数器变量
public int currentIndex = 0;

public void timeInterval(){ 
    mouseX = (int)MouseInfo.getPointerInfo().getLocation().getX(); 
    mouseY = (int)MouseInfo.getPointerInfo().getLocation().getY(); 
    System.out.println("mouseX and mouseY are collected"); 
    
    // 只存储当前鼠标位置到数组的下一个索引,避免数组越界
    if(currentIndex < XArray.length){
        XArray[currentIndex] = mouseX;
        YArray[currentIndex] = mouseY;
        System.out.println("Stored mouse position at index: " + currentIndex);
        currentIndex++;
    } else {
        System.out.println("Array is full, can't store more positions!");
    }
    
    System.out.println("The arrays have been updated"); 
    System.out.println(mouseX+"X"); 
    // 打印最后一次存储的位置
    System.out.println(XArray[currentIndex-1]); 
}

内容的提问来源于stack exchange,提问作者Coder18010

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:41:40