【问题标题】:x cannot be resolved to a variablex 无法解析为变量
【发布时间】:2014-01-23 18:38:03
【问题描述】:

我的代码遇到了一些问题。我将用粗体突出显示错误(星号**):) 提前致谢 (突出显示的代码有这个错误:x 无法解析为变量”)

package com.cmnatic.reborn.gui;

public class Bitmap {
    public final int width;
    public final int height;
    public final int[] pixels;

    public Bitmap(int width, int height) {
        this.width = width;
        this.height = height;
        pixels = new int[width * height];
    }

    public void draw(Bitmap bitmap, int xOffs, int yOffs)  {
        for (int y = 0; y<bitmap.height; y++) {
            int yPix = y+yOffs;
            if (yPix<0 || yPix>=height) continue;

            for(int xPix = 0; **x**<bitmap.width; x++) {
                int **xPix** = **x+x0ffs**;
                if (xPix<0 || xPix>=width) continue;

                pixels[xPix+yPix*width] = bitmap.pixels[x + y * bitmap.width];
            }
        }
    }
}

另外,我有一个奇怪的问题,我不确定: (下面突出显示的代码有以下错误:“Duplicate local variable xPix”

for(int xPix = 0; **x**<bitmap.width; x++) {
    int **xPix** = **x+x0ffs**;
    if (xPix<0 || xPix>=width) continue;

提前致谢, CMNatic

【问题讨论】:

  • xPix 和 x 是两个不同的变量。
  • 对这条消息的直接反应应该是:“为什么?我已经定义了它,等等,……嗯,那是什么……哦,我的天哪,愚蠢的我”。这比在 SO 上询问要快得多。

标签: java variables int pixel pixels


【解决方案1】:

xPix 已在内部 for 循环的范围内定义。 x 需要先声明才能使用,所以才有意义使用

for (int x = 0; x < bitmap.width; x++) {

还有

int xPix = x + x0ffs; // typo

应该是

int xPix = x + xOffs;

与往常一样,错误消息提供了关于问题性质的有意义的指标...

【讨论】:

  • 实际上他提到了这一点--我会用粗体(星号**)突出显示错误:)
【解决方案2】:

x 没有在哪里声明,而是在循环中使用,所以错误。 将循环变量更正为 x

for(int x = 0; x<bitmap.width; x++) {
        int xPix = x+x0ffs;
        if (xPix<0 || xPix>=width) continue;

所有问题都会迎刃而解。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-14
    • 1970-01-01
    • 2021-12-21
    • 2012-02-29
    • 2020-12-07
    • 2019-04-13
    相关资源
    最近更新 更多