【发布时间】:2013-05-25 00:12:03
【问题描述】:
我正在开发一个程序,该程序使用 Java 中的 Color 方法从图像中提取像素。然而,这并不重要。
我需要将 X 和 Y 变量分别增加到它们的图像宽度和高度。我曾尝试嵌套 for 循环,但它只会在满足另一个循环的条件时触发另一个循环。
代码
for (int x = 0; x<ScreenWidth; x++)
{
for (int y = 0; y<ScreenHeight; y++)
{
Color c = new Color(DesktopCapture.getRGB(x,y));
int r = c.getRed();
int g = c.getGreen();
int b = c.getBlue();
System.out.println("Colour at location of screen is " + r + " " + g + " " + b + " Position is " + x + " " + y);
Thread.sleep(40);
输出
Colour at location of screen is 151 184 216 Position is 0 0
Colour at location of screen is 151 186 218 Position is 0 1
Colour at location of screen is 151 188 220 Position is 0 2
Colour at location of screen is 151 190 222 Position is 0 3
Colour at location of screen is 152 192 224 Position is 0 4
Colour at location of screen is 152 194 226 Position is 0 5
Colour at location of screen is 152 195 227 Position is 0 6
Colour at location of screen is 153 196 228 Position is 0 7
Colour at location of screen is 153 197 229 Position is 0 8
Colour at location of screen is 154 197 229 Position is 0 9
Colour at location of screen is 154 196 228 Position is 0 10
Colour at location of screen is 154 195 227 Position is 0 11
Colour at location of screen is 154 194 225 Position is 0 12
Colour at location of screen is 154 192 223 Position is 0 13
Colour at location of screen is 154 190 221 Position is 0 14
Colour at location of screen is 154 188 219 Position is 0 15
Colour at location of screen is 153 186 216 Position is 0 16
Colour at location of screen is 152 184 214 Position is 0 17
Colour at location of screen is 152 182 212 Position is 0 18
Colour at location of screen is 153 181 210 Position is 0 19
Colour at location of screen is 210 222 234 Position is 0 20
【问题讨论】:
-
这似乎按预期工作-它将为
x = 0执行所有y值,然后是x = 1,依此类推。你认为它到底有什么“错误”? -
你能解释更多你想要达到的目标吗?
-
@Quetzalcoatl 我想要一个 for 循环,它根据自己的条件增加 x 和 y,而不是单独执行每个变量。感谢您的提问,
-
...但它同时增加了它们?请记住,
x = 0的 y 值的完整循环必须在x递增之前经过,因为它是外部循环的变量。ScreenWidth和ScreenHeight的值是多少? -
@user2419270
increments both x and y with their own conditions是什么意思。你想用这样的东西吗for (int i = 0, j = 0; (i < 5 || j < 5); i++, j++) {
标签: java loops syntax nested-loops